There is a form with multiple inputs:

<form method="post" id="addForm"> input input input ... <button type="submit" class="btn btn-primary">Отправить</button> </form> 

ajax:

 $("#addForm").submit(function(event) { // Предотвращаем обычную отправку формы event.preventDefault(); $.post('add.php', $("#addForm").serialize(), function(data) { $('#result').html(data); }); }); 

Handler:

 <? if($_SERVER['REQUEST_METHOD'] === 'POST'){ print_r($_POST); } ?> 

The jquery.js file is included once. The handler displays the data array from the post request and only once, and in httpAnalyzer 'e displays two consecutive requests. What's wrong?

  • add.php twice called in a row or all the same once? - Alexus
  • insert Echo before if ($ _ SERVER ['REQUEST_METHOD'] === 'POST' to know exactly how many times the script is called ... Yes, by the way, why are there 3 signs ===? - Alexus
  • @Alexus, the request is sent to add.php once. The file with the form is called test.php. And by the way, nothing comes in the result div. What could be wrong? Three times === put out of habit)) This is the type of strict observance of the type. I agree, there is nothing to this place. - Cinema Trailers
  • one
    @ MovieTrailers are not connected jquery on the page. Mistake as old as world - Vasily Barbashev
  • one
    In any incomprehensible situation, see the browser console. What is there? And if before event.preventDefault(); add console.log('test'); How many times does the test get to the browser console? Well, the advice @ andrey-avseenko you can try. - MrClon

1 answer 1

You do the submit form first, and then you do the post request. Here are 2 requests.

  <button type="submit" class="btn btn-primary"> на <button type="button" class="btn btn-primary"> и $("#addForm").submit(function(event) на $("button").click(function(event)