How to get multiple responses from PHP file via AJAX? - php

My PHP file doing 2 operations: 1. Submits data from form into db table, 2. Sends email.
What I want to do is to show status messages via ajax. For example, "First operation done, please wait for second" and then when second one will be finished show the next message "Second operation done too". Now my ajax looks like that.
How can I modify it?
//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');
}
});
}

in the success block you can perform another ajax call. That's the simplest. You can do it to in .success(), .ajaxSucces(), .complete(), or .then() function like this: $.ajax(...).success(...);
ideally you would embed the code in a function, by example
$.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
});
}

If you've to do two operations that have different execution times, just send two different AJAX queries, and get the responses from them.
Divide your PHP service in two parts. If the second part depends on the first, instead of sending the two requests at the same time, send the second request when the first one returns.
In other words, in your success callback, you're going to notify the user that the first operation has been completed and you proceed to call the second operation, whose success callback will inform that the second operation has been completed.

Related

Ajax request returns failure

I have written a small script to make an Ajax request. I use jQuery for this purpose. I have done this several times but this is the first time I get a failure message. This is my script:
$(document).ready(function(){
$("#btnExecute").click(function(){
var numberOfClusters = $('#inputNumCab').val();
alert(numberOfClusters);
$.ajax({
type: "POST",
url: 'RunPythonThroughPHP/insertData_2.php',
//data: { numberOfClusters: numberOfClusters },
success: function(msg){
alert('thanks');
},
error: function(){
alert("failure");
}
});
});
});
The concept is the following. When I press the button (which is in a form) I get the value of a text field (based on id) and I pass this data into my ajax request. The problem is I get the failure alert.
Why this happens? If I make my request not async (async: false) then it works.

How to write an Ajax code to fetch new row when it is inserted in MySQL?

I have a simple chat service. I store messages, login and time etc. in Mysql database. The chat messages are displayed below with the help of Ajax & PHP
<div id="messages"> </div><!--- chats are displayed here -->
I have following Ajax code which fetches datas from Mysql in every 2 seconds. Ofcourse, everyone recommends not to do this way. It might effect server performances negatively. And its unnecessary.
$(document).ready( function() {
var destination_hashed = $("#destination_hashed").val();
var interval = setInterval( function() {
$.ajax ({
type: "POST",
url: "chat.php",
data: { destination_hashed1: destination_hashed },
success: function(data) {
$("#messages").html(data);
}
});
}, 2000);
});
In nutshell, I have two chat clients A & B. When A sends message to B, there are new rows inserted in Mysql.
So, how can I write Ajax & PHP code to fetch only when there are new rows. Rather than fetching data from Mysql every 2 seconds whether new rows inserted or not
Recently I have worked on a chat module of this kind and I can say some correction in you code
First of all don't use setInterval in the way you are using ,
Why
because in your particular code the request is send to the server every 2 second , so if the network is slow your code will have the tendency to send to much request to the server and coordination between those request would be difficult.
So what you do is
function getNewMessage(){
$.ajax ({
type: "POST",
url: "chat.php",
data: { destination_hashed1: destination_hashed },
success: function(data) {
$("#messages").html(data);
},
complete : function(){ // this will be called even if our request fail, success etc
setTimeout(function(){ // send request after 2 second from the complition of the previous request
getNewMessage();
},2000);
}
});
}
There are two approach in parsing the chat result from the ajax call
a) get the html from the ajax call (this would be slow and inefficient in case you want to extend your module in the future)
You can simpley get the html content from the ajax call on succes parameter you can append that to the table
For example : -
if the response from the server on new message is
<div class="chat">
<lable>John</lable>
Hi there !!!
</div>
Then parsing the content will be something like this
success: function(data) {
// $("#messages").html(data); //this will change the content in every request
$("#messages").append(data); // this will append the new conent
},
b) Well the other approch would be to get data in json format(a lot better approch )
For example : -
if the response from the server on new message is
{
username : 'john',
message : 'Hi there !!!'
}
Then parsing the content will be something like this
success: function(data) {
// $("#messages").html(data); this will change the content in every request
$("#messages").append('<div class="chat">'+
'<lable>'+data.username+'</lable>'+
data.message +
'</div>'); this will append the new conent
},

PHP script not echoing data when called via AJAX

I have been staring at this problem for the past 2 hours and can't seem to fathom it, even after validating that everything loads correctly when scouring the console.
I basically have two sliders on my page which will eventually populate results in a table, every time I change my slider I send an array of two values to my AJAX script:
function update_results(values)
{
$.ajax({
type: "GET",
url: "./app/core/commands/update_results.php",
data: { query : values },
cache: false,
success: function(data) {
// eventually some success callback
}
});
}
The browser successfully finds update_results.php but it does not perform the logic on the page ( I assume it has found the page as the 404 error does not appear in my console. )
At this point in time the script is extremely bare-bones as I'm obviously trying to establish communication between both files:
<?php
$vals = $_GET['values'];
echo $vals;
In this case $vals is never echoed to the page, am I missing something in my AJAX? I know the values enter the function as alerted them out before attaching the PHP script.
Ajax Calls are suffering from Browser Cache. If your browser thinks, that he already knows the content of update.php, he will return the cached content, and not trigger the script. Therefore your
modified code might simply not get executed. (Therefore your insert query wasn't executed)
To ensure this is not happening in your case, it is always a good idea to pass a parameter (timestamp) to the script, so your browser thinks it's another outcome:
function update_results(values)
{
$.ajax({
type: "GET",
url: "./app/core/commands/update_results.php?random_parameter=" + (new Date().getTime());
data: { query : values },
cache: false,
success: function(data) {
// eventually some success callback
}
});
}
This will ensure that - at least - the browser cache is refreshed once per second for update_results.php, no matter what browser cache-settings or server-side cache advices are telling.
when Ajax is done, the success callback is triggered and the output of you php script is saved in data.
you can handle the data like this:
$.ajax({
type: "GET",
url: "./app/core/commands/update_results.php",
data: { query : values },
cache: false,
dataType: "text",
success: function(data) {
document.write( data )
}
});
PHP, running at server, is unaware of what happening at the front-end browser and it simply respond to ajax request as any other normal http request. So the failure of SQL query has nothing to do with javascript, which only responsible for sending ajax request and receiving and handling the response. I guess there's some errors in your php script.

jquery multiple ajax calls without using asynch false

I have a page that has to run an ajax command a few times. It has to use the results of the previous ajax call in for the current one.
in laymen's terms:
call ajax, build entity on remote server, return result (i get a proprietary id as result)
...
call ajax, use result to post additional data to remote server, get id of this post
...
call ajax, post ids..etc
my first idea was async:false, but i see this is widely unacceptable and it ruins code execution order. My goal too, is to have a dialog window that prints the results of the ajax calls as they happen. Currently, the dialog window appears once all ajax calls are done. I don't get the pretty little: Build....done then additional Options.....done and so on...
if i make asynch:true, i wont have the id's need to process the next ajax..
what other options do i have have?
//form var is set earlier, standard serialized form.
var functions = ['build','additionalOptions','completion'];
$('#submitButton').click(function(){
$('#createGroupDialog').dialog({
autoOpen:false,
width: 1200,
height:800,
modal: true,
position: {my: "top", at: "top"},
resizable: false,
closeOnEscape: true
});
$("#createGroupDialog").dialog('open').html("<p>Please Wait...</p>");
function fireAjax(form,func)
{
$.ajax({
type: "POST",
url: "createGroup/createGroupDo.php",
data: form+"&func="+func,
asynch: false,
success: function (result) {
$('#createGroupDialog').append(result);
}
});
}
jQuery.each(functions , function(i,func){
fireAjax(form,func);
});
});
asynch:false is indeed a terrible way to deal with asynchronous data. It doesn't mess with the execution order but it blocks until the request finishes meaning no other JavaScript can run in the mean time, this includes things like onclick handlers and animations.
Since your requests rely on a previous request you have to write them like that:
$.ajax({
url: "request1.php",
data: data,
success: function (result_1) {
$.ajax({
url: "request2.php",
data: result_1,
success: function (result_2) {
$.ajax({
url: "request3.php",
data: result_2,
success: function () {}
});
});
});
}
});
But as you can see this gets tedious. You can use callbacks, but it's better use the Promise API.
Use like:
$.ajax({
url: "request1.php",
data: data
}).then(function (result_1) {
alert(result_1);
return $.ajax({
url: "request2.php",
data: result_1,
});
}).then(function (result_2) {
alert(result_2);
return $.ajax({
url: "request3.php",
data: result_2
});
}).then(function (result_3) {
alert(result_3);
});
It's worth noting that jQuery does a lot of work under the hood to make this API possible. $.ajax is a very flexible function. This means you can use it in many ways. It's best to chose one way and to stick with it. The current state of art really leans towards Promises.

Optimize ajax synchronously calls

I have some ajax script that fire off about 250 synchronous PHP calls . This is my script
$(document).ready(function(){
$("#generate").html("<div class='modal'><p>Initializing...</p></div>");
$.ajax({
url:'/fetch around 250 url from database.php',
async:false,
dataType: 'json',
success: function(data){
$.each(data,function(key,val){
$("#generate").html("<div class='modal'><p>Fetching "+val.url+"</p></div>");
saveimage(val.url);
}
$("#generate").html("<div class='modal'><p>done</p></div>");
finalcreate();
},
});
});
function saveimage(){
$.ajax({
url: 'do some php work.php',
async: false,
});
}
function finalcreate(){
$.ajax({
url: 'do some php work.php',
async: false,
});
}
In the first part script fetch more than 250 urls from database and for every url script do some php calculation using another ajax call. when the loop ends script do final ajax call.
When i run this programe in firefox, it run successfully for only 40 urls, then browser shows dialog box with option of whether user want to stop this script or not, if user want to run this script then the script run again for next 40 urls , same proccess occure till the end.
How i can optimize this script, i dont want browser show option to stop this script. Please help.
Thanks
Try this:
function nextrequest() {
if (requests.length == 0) {
$("#generate").html("<div class='modal'><p>done</p></div>");
finalcreate();
return;
}
var val = requests.pop();
$("#generate").html("<div class='modal'><p>Fetching "+val.url+"</p></div>");
saveimage(val.url);
}
var requests = [];
$(document).ready(function(){
$("#generate").html("<div class='modal'><p>Initializing...</p></div>");
$.ajax({
url:'/fetch around 250 url from database.php',
dataType: 'json',
success: function(data){
requests = data;
nextrequest();
},
});
});
function saveimage(){
$.ajax({
url: 'do some php work.php',
success: function(data) {
// do something...
nextrequest();
}
});
}
function finalcreate(){
$.ajax({
url: 'do some php work.php',
});
}
You store all the URLs in a global variable, and everytime a request is done, you get the next one, until all of them are consumed, (requests.length == 0), you call the final request.
This way the user can still do something else on the page, and you can display progress everytime a request is done. Also, a good thing is that you can make 2 calls at once, or more, to make the process faster.
Ajax call needs much time to complete, as it communicates with remote server. The slowest thing there is a query to the server. You should send one batch request with all data needed to the server, that should separate the data and handle it. Everything should be completed about 250 times faster.
make some time interval for each ajax request
success: function(data){
$.each(data,function(key,val){
$("#generate").html("<div class='modal'><p>Fetching "+val.url+"</p></div>");
setTimeout(saveimage(val.url),3000);
}

Categories