How to get multiple responses from a PHP file via AJAX?

My PHP file performs 2 operations: 1. sends data from the form to the database table, 2. sends email.

What I want to do is show status messages via ajax. For example, β€œThe first operation completed, please wait a second,” and then when the second operation is completed, the following message β€œThe second operation completed too” will appear. Now my Ajax looks like this.

How can i change this?

//add status data to form form.data('formstatus', 'submitting'); if (validate()) { //send data to server for validation $.ajax({ url: formUrl, type: formMethod, dataType: "json", data: formData, success: function (data) { $.notifyBar({ cls: data.status, html: data.message }); form.data('formstatus', 'idle'); } }); } 
+4
source share
3 answers

in success block, you can make another ajax call. This is the simplest. You can do this in .success (),. AjaxSucces () ,. complete () or .then () as follows: $ .ajax (...). Success (...);

Ideally, you should embed code in a function like

 $.ajax({ url: formUrl, type: formMethod, dataType: "json", data: formData, success: function (data) { notifyResponse(data); form.data('formstatus', 'idle'); sendMail(); } }); function sendMail() { $.get(mailUrl, function(data) { // or $.post(... notifyResponse(data); }); } function notifyResponse(data) { $.notifyBar({ cls: data.status, html: data.message }); } 
+3
source

If you need to perform two operations with different runtimes, just send two different AJAX requests and get answers from them.

Divide your PHP service in two. If the second part depends on the first, instead of sending two requests at the same time, send the second request when the first returns.

In other words, in your success callback, you must notify the user of the completion of the first operation, and you proceed to call the second operation, whose success callback indicates that the second operation is completed.

+3
source

Another approach, different from the proposed steve, is to use a kind of long survey similar to the one explained in this answer:

How to implement the basic "Long Polling"?

Not so simple and with a more complex server configuration.

0
source

Source: https://habr.com/ru/post/1380902/


All Articles