Hello. The task is as follows.
There is a page with a certain number of pop-ups (with the same class) containing different forms.
Inside each form there is an empty

<div id="result"></div> 

which will receive and display the server response after submitting the form. The forms themselves are essentially identical, only different fields.
How to make a selection correctly, so that when submitting, the answer is displayed in #result, which is in the form that the user sent, and not in the first page that was found?

submission script:

 $('.formAjax').submit(function(event) { /* отключение стандартной отправки формы */ event.preventDefault(); /* собираем данные с элементов страницы: */ var $form = $( this ), h1_form = $('h1').text(), h2_form = $('h2').text(), link = $form.find( 'input[name="url"]' ).val(), ajax = $form.find( 'input[name="ajax"]' ).val(), name = $form.find( 'input[name="name"]' ).val(), phone = $form.find( 'input[name="phone"]' ).val(), diapazon = $form.find( 'select[name="diapazon"]>option' ).val(), url = $form.attr( 'action' ); /* отправляем данные методом POST */ var posting = $.post( url, { h1: h1_form, h2: h2_form, url: link, ajax: ajax, name: name, phone: phone, diapazon: diapazon } ); /*после отправки формы*/ posting.done(function( data ) { /*выводим результат запроса*/ // alert( data ); // alert('Вы записались на прием, мы скоро свяжемся с вами'); // $('form').html(result); // $( "#result" ).empty().append( data ); $( "#result" ).text(data); console.log ('ok'); /*очищаем поля формы*/ $(':input','form') .not(':button, :submit, :reset, :hidden') .val('') .removeAttr('checked') .removeAttr('selected'); }); }); 

form example

 <form action="/algo/addappointment.php" class="formAjax"> <input type="text" placeholder="Ваше имя*" name="name" required class="form__input form__input_popup"/> <input type="text" placeholder="Телефон*" name="phone" required class="form__input form__input_popup"/> <input type="hidden" name="url" required value="<?=$APPLICATION->GetCurDir()?>"/> <input type="hidden" name="h1" required id="h1_form" value=""/> <input type="hidden" name="ajax" required value="y"/> <select name="diapazon" class="form__input form__input_popup"> <option value="9-12">С 9 до 12</option> <option value="12-15">С 12 до 15</option> <option value="15-18">С 15 до 18</option> <option value="18=21">С 18 до 21</option> </select> <input type="submit" value="Записаться" class="button button_big"/> <div id="result"></div> </form> 
  • one
    Do you have the same id div on all forms the same? The id attribute is a unique element name that is used to change its style and access it through scripts. The identifier in the code of the document must be in a single copy, in other words, to occur only once. - Ishutinov Dmitry
  • Yes, a div for outputting an answer, let's say it is not an idi, but a class. how to be? - wannaBpro
  • Assign an individual id to each div, then process it. - Ishutinov Dmitry
  • @Ishutinov, i.e. You want to say that for this model it is impossible to sample? - wannaBpro
  • add examples of forms to the question, and how submit is done - Grundy

2 answers 2

Error in the sample itself

 $( "#result" ).text(data); 

The selection is made in the context of all pages. To solve it, you need to produce it in the context of a form that has already been saved.

 var $form = $( this ), 

Using for example the find method

 form.find('#result').text(data); 

But id in this case is better to replace with a class, because id can be non-unique, there may be other problems, for example, using styles.

Example:

 $('.formAjax').submit(function(event) { /* отключение стандартной отправки формы */ event.preventDefault(); /* собираем данные с элементов страницы: */ var $form = $(this), h1_form = $('h1').text(), h2_form = $('h2').text(), link = $form.find('input[name="url"]').val(), ajax = $form.find('input[name="ajax"]').val(), name = $form.find('input[name="name"]').val(), phone = $form.find('input[name="phone"]').val(), diapazon = $form.find('select[name="diapazon"]>option').val(), url = $form.attr('action'); /* отправляем данные методом POST */ var posting = $.post(url, { h1: h1_form, h2: h2_form, url: link, ajax: ajax, name: name, phone: phone, diapazon: diapazon }); /*после отправки формы*/ posting.complete(function(data) { /*выводим результат запроса*/ // alert( data ); // alert('Вы записались на прием, мы скоро свяжемся с вами'); // $('form').html(result); // $( "#result" ).empty().append( data ); $form.find("#result").text(`Form ${$form.attr('id')}: Answer from server - ${JSON.stringify(arguments)}`); console.log('ok'); /*очищаем поля формы*/ $(':input', 'form') .not(':button, :submit, :reset, :hidden') .val('') .removeAttr('checked') .removeAttr('selected'); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form action="/algo/addappointment.php" id="firstFrom" class="formAjax"> <input type="text" placeholder="Ваше имя*" name="name" required class="form__input form__input_popup" /> <input type="text" placeholder="Телефон*" name="phone" required class="form__input form__input_popup" /> <input type="hidden" name="url" required value="<?=$APPLICATION->GetCurDir()?>" /> <input type="hidden" name="h1" required id="h1_form" value="" /> <input type="hidden" name="ajax" required value="y" /> <select name="diapazon" class="form__input form__input_popup"> <option value="9-12">С 9 до 12</option> <option value="12-15">С 12 до 15</option> <option value="15-18">С 15 до 18</option> <option value="18=21">С 18 до 21</option> </select> <input type="submit" value="Записаться" class="button button_big" /> <div id="result"></div> </form> <form action="/algo/addappointment.php" class="formAjax" id="secondFrom"> <input type="text" placeholder="Ваше имя*" name="name" required class="form__input form__input_popup" /> <input type="text" placeholder="Телефон*" name="phone" required class="form__input form__input_popup" /> <input type="hidden" name="url" required value="<?=$APPLICATION->GetCurDir()?>" /> <input type="hidden" name="h1" required id="h1_form" value="" /> <input type="hidden" name="ajax" required value="y" /> <select name="diapazon" class="form__input form__input_popup"> <option value="9-12">С 9 до 12</option> <option value="12-15">С 12 до 15</option> <option value="15-18">С 15 до 18</option> <option value="18=21">С 18 до 21</option> </select> <input type="submit" value="Записаться" class="button button_big" /> <div id="result"></div> </form> 

  • I need to register instead of my $ ("#result") .text (data); ? the answer is never displayed in #result; even the usual string is not written there, what could be the problem? - wannaBpro
  • @wannaBpro, added an example to the answer. Check the value of the variable that you insert, and errors in the console, maybe just a request error and you don't get into the done method - Grundy
  • Thank! Now everything works, the console did not issue errors, only .log was output without an answer, apparently, something was missing from the beginning. - wannaBpro

In fact, it is absolutely wrong to do several identical id on the same page. This is bad.

However, if you do not want to rewrite anything in the code, but only to find the right selector, then inside $.submit() it will be something like this: $(this).find('#result')

That is, instead of:

 $("#result").empty().append(data); 

Write:

 $(this).find('#result').empty().append(data); 

However, I strongly recommend that you fix the attribute on the class (then in the selector you will need to change the grid to a point, so that the class is chosen) <div class="result"></div> and the problem is solved, in my opinion.

  • also does not prescribe any data in # result for some reason - wannaBpro
  • Please compare your version with mine ( jsfiddle.net/higimo/zhbkgsty ). I can not tell you what the difference is with you. - higimo
  • I thank for the answer, used as a result of the option proposed above - wannaBpro