When to use and not use AJAX in submitting forms?

10

If I have a huge question form, would sending via AJAX be the best way?

<form id="formulario" method="POST">
    <!--vários Questionarios aqui-->
</form>

JavaScript:

$.ajax({
    type: "POST",
    data: $("#formulario").serialize(),
    url: "algumaurl.php",
    success: function(resposta){
       alert(resposta);
    }
});

In the URL algumaurl.php would have a update in a given id and within this page would have a echo response ( Erro na conexão or OK ).

    success: function(resposta){
       if(resposta== "Erro na conexão"){
           alert("Erro ao inserir dados");
       } else if(resposta== "OK"){
           alert("Formulario ok");
           window.location = "https://www.youtube.com";
       }
    }

If I do using action="algumaurl.php" I will have problems if the form is already filled (I will lose all the data later filled in) in case of an error, is not it?

$update = mysql_query("UPDATE tabela set nome=\"algo\" WHERE ID=$id");

if($update === false){   
    $mensagem ="Erro na conexão";
    header("location: ../pagina-2.php?mensagem=$mensagem");
} else{
    $mensagem ="OK";
    header("location: https://www.youtube.com");
}
    
asked by anonymous 07.10.2015 / 16:07

2 answers

12

There are no clear cases where you should or should not use. It depends on the experience you want to give the user.

First of all, one of the most common but very common mistakes I see in applications that use AJAX or other similar technologies is that there is no fallback . That is, if for some reason the technology is not available, the page does not work. The first thing you should worry about is if sending with simple HTML is working perfect in all situations . Then think about giving a slightly better experience if it is available. But do not let the page stop working because the browser does not support the technology.

Although it's like, I think this technique holds true even when the fallback is not required by the client where one can ensure that the feature is available. I think the cost is very low and avoids a lot of future headache. It is a matter of methodology and organization. The cost of disorganization is usually higher. Of course the experience of each will make you choose the best path. I am not against anyone who does not want to fallback when it is not really needed according to the requirements. I just find a way worse and more disadvantageous. And the customer is not always right. Most of the time I decide for him. He decides when he has knowledge, is reasonable or I need the money: P You will do what is right for you.

Running AJAX

The only great advantage that AJAX brings is that you do not need to load another page, or the same again, to send the data and have a response. This is done transparently to the user. It makes a better impression, it's usually faster (I've seen people slow down) and can reduce the volume of data trafficked. But nothing very important. Experience is what counts.

Eventually the PHP script that will receive the request needs to be adapted to meet the needs of AJAX. But do not change in a way that prevents normal access. If this is the case, create two scripts , one to fulfill the normal submission form generating a complete page and another sending only the confirmation data that the operation was successful and informing something else that is relevant. If you can do it, the work is almost the same.

Advantage in your case

Sending each question answered really can be very interesting.

The loss or not of the data, will depend on your script PHP to handle this. It will have to persist somewhere (database, memory, etc.), have session control, etc. You'll have to control the status of the form not being completely filled, have garbage collection policies if a form is abandoned in the middle. Anyway, there are several things to think about if you want to give the user a good experience.

Have you ever wondered if there were any problems at the time of sending and you do not have AJAX? The loss is huge. With AJAX done the way you are thinking, or take advantage of the already done part or prevent the user to continue wasting their time on something that will not serve anything.

This is all complicated, having a fallback is simple. This is why many sites prefer to have AJAX. The cost of putting this feature in the right way increases. But who pays the cost is the user who will experience a lot worse.

If you're doing something real, even if you're still testing, and you're having specific questions, you're researching whether you already have it here or ask.

    
07.10.2015 / 16:26
5

The question has a certain ambiguity because the title gives a notion of being a broader and generic theme regarding the use of ajax.

However, the context brings a specific problem that is to keep the data that the user sent even if there is an error and there are redirects.

Considering the context, it is possible to keep the data entered by the user in session variables or cookies.

As an example, action="someurl.php".

On the "someurl.php" page, which will receive the data (GET / POST), save all incoming information without session variables.

Example:

<?php

/**
Inicia o uso de sessões.
*/
session_start();

/**
Os dados digitados pelo usuário serão salvos nessa sessão:
*/
$_SESSION['formulário_x'] = $_POST;

/**
Abaixo continua os seus scripts normalmente.
*/

On the form page (page-2.php), add conditionals to check if a session is present.

Example

<input type="text" name="nome_do_campo" value="<?php isset($_SESSION['formulário_x']['nome_do_campo']){echo $_SESSION['formulário_x']['nome_do_campo'];}?>">

Note: Whenever you use the $ _SESSION global variable, you must start sessions with the session_start() function.

The session_start() function fires headers to the client, so it should never be called after a header is sent. When this occurs, it triggers errors of type "header already sent ..".

    
07.10.2015 / 20:47