Hello, please tell me how correctly in the php handler file to do the reverse answer on the page, this is the code for sending the form to the server:

<script type="text/JavaScript"> $(document).ready(function() { $("#form").submit(function(event) { event.preventDefault(); $.ajax({ url: "podpiski.php", type: "post", data: $("#form").serialize(), success: function(answer) { $("#answerlog").html(""); } }).done(function() { $("#loadlog").fadeOut(400); }); }); }); </script> 

    2 answers 2

    If you on the client do not need anything from the north, except to confirm “everything is OK”, simply return from the north true And on the client, check the answer. To do this in an anonymous function in .done , you have to add some parameter, to fit the answer from the server.

      1. It is better to transfer the form data as an array instead of serialize() it is better to use serializeArray() if there are several variables.
      2. Do not use success (outdated function) and done together.
      3. The response from the php script will be just echo 'true';
      4. And finally, if you want to return data from a script and not just the status of its execution, you should change the transfer method in the Ajax by adding a dataType: 'JSON', after type: "post" then the answer and its processing will change.

       $(document).ready(function() { $("#form").submit(function(event) { event.preventDefault(); var form_data = $("#form").serializeArray(); //удобней сразу передать массив; $.ajax({ url: "podpiski.php", type: "POST", dataType: "JSON", data: data }).done(function(res) { if (res.url) { // если url существует, воспринимаем как должное, выводим сообщение и перенаправляем alert(res.message); location.href = res.url; } else { // иначе что-то пошло не так и выводим для себя сообщение в консоль alert('Что-то пошло не так.'); console.log(res.message'); } }).fail(function(res) { console.log('fail'); }); }); }); 
       // а в php ответ стоит сделать таким образом (к примеру) if ($result = mysql_query($query)) { // проверяем удалось ли выполнить sql запрос if (count($result)) { // если да, и строку вернули то: echo json_encode(array( 'url' => $_SERVER['HTTP_REFERER'], 'message' => 'Пользователь с данным email адрес уже подписан!' )); } else { // если ответ пустой, то: echo json_encode(array( 'url' => $_SERVER['HTTP_REFERER'], 'message' => 'Некорректный email адрес!' )); } } else { // если не удалось выполнить sql запрос, то: echo json_encode(array( 'message' => 'Ошибка' )); } 

      • I need to get a response from the server: else {header ("Location:". $ _ SERVER ['HTTP_REFERER']); echo "<p> The user with this email address is already signed! </ p>"; }} else {header ("Location:". $ _ SERVER ['HTTP_REFERER']); echo "<p> Invalid email address! </ p>"; } - Dmitry
      • I corrected the code, in the example php wrote how to send a message and url and in js you can already display information in various ways. - RifmaMan