When to use and not use AJAX when submitting forms?

Asked

Viewed 1,641 times

11

If I have a giant form of questions, sending via AJAX is 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 reply (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 data later filled) in case of error, is not?

$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");
}
  • My answer is: You decide. Srsrsrsrsrsrs

  • 1

    @Wallacemaxters And mine is, The client decides. :D

  • In time: when I say "customer," I don’t just mean Your Joe who owns the bakery. Software client can be a complex entity with many forms.

2 answers

14


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

First of all, one of the most common but very common mistakes that 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 is whether sending with simple HTML is working perfect in all situations. Then think about giving a slightly better experience if it is available. But don’t let the page stop working because the browser doesn’t support the technology.

Although it’s like, I think this technique is worth even when the fallback is not required by the customer, where it can be guaranteed that the resource is available. I think the cost is very low and avoids a lot of future headache. It’s a matter of methodology and organization. The cost of disorganization is usually higher. Of course the experience of each one will make choose the best way.

I’m not against people who don’t want to fallback when it is not really needed according to requirements. I just find a worse and more disadvantageous way. And the customer is not always right. Most of the time I decide for him. He decides when he knows, is reasonable or I need the money :P You will do whatever is best for you.

Functioning of the AJAX

The only great advantage that AJAX brings is that you don’t have to upload another page, or the same one again, to send the data and have a response. This is done transparently for the user. It gives a better impression, is usually faster (I’ve seen people manage to slow down) and can reduce the volume of data traffic. But nothing very important. The experience really counts.

Eventually the script PHP that will receive the request needs to be adapted to meet the need of AJAX, but does not change in a way that prevents normal access. If so, create two scripts, one to answer the form by normal sending generating a full page and the other sending only the confirmation data that the operation was successful and inform something else that is relevant. If you know how to do the job it’s almost the same.

Advantage in your case

Sending each answered question really can be very interesting.

Whether or not data is lost will depend on your script PHP know how to manipulate this. It will have to persist somewhere (database, memory, etc.), have session control, etc. You will have to control the status of the form not being fully filled in, have garbage collection policies if a form is dropped in the middle. Anyway, there are several things to think about if you want to give a good user experience.

Have you ever wondered if there is a problem at the time of sending and you don’t have AJAX? The loss is huge. With AJAX done the way you’re thinking, either take advantage of the part that’s already been done, or stop the user from wasting their time on something that will serve no purpose.

It’s all complicated, having a fallback It’s simple. That’s why many sites prefer not to have AJAX. The cost of putting this feature the right way increases, but then who pays the cost is the user who will have a much worse experience.

If you’re doing something real, even if you’re testing yet, and you’re having specific questions, you look up whether you already have it here or ask.

  • Incorrect. An application having to use Ajax, and having to keep running if the client’s browser does not support it, is a project requirement and not a common obligation to all applications. See: if the project client requires Ajax experience, and accepts that in return the project requires certain browser with JS enabled (and for many clients this is very simple), why I will spend money offering support to both models (Ajax)?

  • Read the first paragraph. Don’t be biased and pinch loose things to find trouble where you don’t have it. Reading the whole text is important not to pass by troll.

  • The first paragraph answers when using or not using Ajax, which is the answer to the question. The second paragraph speaks otherwise: it says that, when using, you must ensure the experience also in case Ajax is not available; and that not doing so would be a mistake. And this is what my comment refers to.

  • But the first paragraph cannot be ignored. If you do not want to do this, do not, the experience will be limited to browsers that have this capability. The second does not invalidate the first. I just wanted you to have all the willingness you have to find egg hair on things I write to find real problems in others posts around the site. There are a lot of really bad things for you to have fun with. You don’t have to be on top of my stuff.

  • 1

    I do not understand Ajax well enough to properly interpret what you mean by "the technology is not available". Anyway, from the point of view of UX, I essentially agree with your answer. In the example scenario, the user should be warned previously in the event of any unavailability for you not to have the trouble of filling out the long form unnecessarily (something bad for the experience).

  • 1

    If this prior detection of unavailability is not possible, the data must be kept in any available form (cookies, session, whatever). The idea of getting the questions answered one by one is also good, because it dilutes the user’s perceived work, and an error with data loss becomes less impactful.

  • 1

    @Luizvieira In general it is possible to detect that a resource is available. And you can even solve it differently when it is not available transparently to the user. I improved and put link to talk about it. When I answered I didn’t have to tag UX and I don’t know if AP wanted this, but since it does, I went that way.

  • 1

    @Luizvieira Basically all browsers support Ajax and only older versions, which even have security problems and are little used, is that they may not have support. Eventually the client can disable JS execution and this would cause Ajax and many other usability features to stop working. JS today is relatively safe and disabling it is an unusual practice. A Single Page Application uses JS and Ajax heavily, being sometimes almost 100% built using JS. Ie: in many scenarios, ensure the operation of the App with and without Ajax is highly costly.

  • 1

    @Luizvieira Already the check that the JS has been disabled is quite simple and cheap - we can say that "it costs nothing" check if the browser is point out of the curve before letting the user waste time; and, in case the JS has been disabled, warn and stop the app. This has relatively low cost (nothing compared to running also without JS/Ajax in applications rich client).

  • 1

    @Caffé Well, I went down this line of reasoning just because the question has the UX tag (which, from what I saw in the review, you added yourself). Whether or not it’s costly from an implementation point of view, a usability/experience problem that makes a user lose everything they’ve typed in a long form is severe enough to possibly cost the customer. So you can see that the problem goes beyond JS or Ajax. Check disable is an idea, but it can prevent the service from being used (which also isn’t necessarily the best output).

  • @Caffé That is, this question has relevant aspects both from the point of view of UX and from the technological point of view (as in the real world). Perhaps it would be interesting to reduce the focus by removing the UX tag, or - if the AP has broader interests - open other related questions.

  • @Luizvieira I thought it was a good idea to Tag but I don’t cling to it; no problem removing it. My point is: block the use of the app or support browser with and without Ajax are project decisions and neither of the two models is incorrect. In my company we have Apps used daily by more than 200 thousand people internally that require JS. There will be no customer loss if the app blocks browser with JS disabled. It is only 1 of numerous examples of when it is not a mistake to stop spending money ensuring two working models when 1 of them may never be demanded. For this reason: project decision.

Show 7 more comments

5

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

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

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

For example, action="algumaurl.php".

On the "algumaurl.php" page, which will receive the data (GET/POST), save all information received 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 that check for a present session.

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 should start sessions with the function session_start().

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.