D
D
Dmitry2018-02-25 22:04:43
JavaScript
Dmitry, 2018-02-25 22:04:43

The ajax function to the form that is created by the template does not work. How to fix?

There are div .groups

<div class="col area">
        <div class="row">
            <div class="col-5 groups table-responsive" id="groups">
            </div>
            <div class="col-6 posts">
            </div>
        </div>
 </div>

Inside it, at the click of a button, a form is created using Handlebars
<script id="entry-template" type="text/x-handlebars-template">
  <form action="function.php" method="get" id="btnposts">
    {{#each response}}
    <label><input type="checkbox" name={{screen_name}} value={{gid}}><img src={{photo}} alt={{screen_name}}> {{name}}</label><br>
    {{/each}}
    <input type="submit" value="Посты" class="btn btn-outline-success" onclick=f()>
  </form>
</script>

There is a script that ajax request should send the data of this form
$(document).ready(function(){

  $( "#btnposts" ).submit(function( event ) {

    event.preventDefault();

    $.ajax({
      type: 'get',
      url: 'function.php',
      data: {'getPosts':'yes'},
      contentType: false,
      cache: false,
      proccessData: true,
      success: function(result) {
        alert(result);
      }
    })
  });
})

But when the button is pressed, it is not sent using ajax, but by a regular get request with a redirect to function.php

I must say right away that the form is created by pressing another button and initially it is not on the page. How can I get it all to work.

PS The level of knowledge is quite small, so while I'm learning on my project and making a lot of mistakes. Do not judge strictly.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ilya, 2018-02-25
@DmitriyNW

Do it in this way:

$(document).on('submit', '#btnposts', functions() { /*код формы*/})

E
Egor Zhivagin, 2018-02-25
@Krasnodar_etc

You have already been answered correctly, I will add - read about event delegation in JS in order to better understand what is happening

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question