Good day. I implement data sending from form input to mail.

I set everything up, works fine, sends mail, but only if there is one form on the page. If I want to make 2 forms, then when you click on the "send" button of the second form, an empty message comes to the mail, this is due to the fact that mail.php contains data on sending only for form 1.

I want to make for each form my own file with the settings mail1.php and mail2.php

It is necessary to make so that js would define from what form <form id="oneForm"> or <form id="twoForm"> request comes. If from the form, <form id="oneForm"> then sent data to mail1.php if with <form id="twoForm"> then to mail2.php

I give below my js code.

 $(document).ready(function () { $("form").submit(function () { // Получение ID формы var formID = $(this).attr('id'); // Добавление решётки к имени ID var formNm = $('#' + formID); var message = $(formNm).find(".msgs"); // Ищес класс .msgs в текущей форме и записываем в переменную var formTitle = $(formNm).find(".formTitle"); // Ищес класс .formtitle в текущей форме и записываем в переменную $.ajax({ type: "POST", url: 'sendmail/mail.php', data: formNm.serialize(), success: function (data) { // Вывод сообщения об успешной отправке message.html(data); formTitle.css("display","none"); setTimeout(function(){ //$(formNm).css("display","block"); $('.formTitle').css("display","block"); $('.msgs').html(''); $('input').not(':input[type=submit], :input[type=hidden]').val(''); }, 3000); }, error: function (jqXHR, text, error) { // Вывод сообщения об ошибке отправки message.html(error); formTitle.css("display","none"); // $(formNm).css("display","none"); setTimeout(function(){ //$(formNm).css("display","block"); $('.formTitle').css("display","block"); $('.msgs').html(''); $('input').not(':input[type=submit], :input[type=hidden]').val(''); }, 3000); } }); return false; }); //для стилей формы var $input = $('.form-fieldset > input'); $input.blur(function (e) { $(this).toggleClass('filled', !!$(this).val()); }); }); 

In mail.php is a direct data collection from input and sending mail.

I would be very grateful for any help!

  • one
    It seems to me the easiest solution in this situation is to push your code into a function, the arguments of which will be the name of the form and the path to the handler file - ChromeChrome

1 answer 1

Add formID to php file

url: 'sendmail / mail' + formID + '.php'

Let's call formID = 'FormOne'; accordingly, the file should be called mailFormOne.php

  • Thank! works but not to the end. formID in the second form gives the correct name twoform and in the first form gives undefined for some reason - OuFinx
  • so in the first form there is no ID, apparently - Romzik85
  • The problem was that I had an unclosed <form> a little higher, I did not notice it at the beginning. Now everything works, thanks! - OuFinx