AJAX request sometimes out of order - javascript

I'm having trouble with POST and GET request. On my server side right up until the moment before I send I have what I expect but then on my client side I get things out of order. For example these two should be in the reverse order I have here:
Sending from server{"grid":["","","","","","","","",""],"winner":""}
Received at server: {"grid":["X","","","","","","","",""],"winner":""}
function sendData(json) {
$.ajax({
type: "POST",
url: "/ttt",
data: json,
dataType: "json",
success: receiveData()
});
}
function receiveData() {
var response = $.ajax({
type: "GET",
url: "/ttt",
dataType: "json",
success: function(){
grid = response.responseJSON;
console.log("Receved at client: " + JSON.stringify(grid));
}
});
console.log("Also after receiving " + JSON.stringify(grid));
}
gives me:
Also after receiving {"grid":["X","","","","","","","",""],"winner":""}
Receved at client: {"grid":["X","O","","","","","","",""],"winner":""}
I think this may two different problems. One for getting things out of order and another for why my grid doesnt reflect the changes after my success clause function in my GET request.

You're making a common mistake. You need to use a function reference without the parens here for receiveData. Change this:
function sendData(json) {
$.ajax({
type: "POST",
url: "/ttt",
data: json,
dataType: "json",
success: receiveData()
});
}
to this:
function sendData(json) {
$.ajax({
type: "POST",
url: "/ttt",
data: json,
dataType: "json",
success: receiveData // no parens here
});
}
When you include the parens, it calls the function IMMEDIATELY and puts the return value from the function as the success handler and thus you see them run out of order. You want to pass a function reference to it can be called later. A function reference is the function's name without the parens.
It also appears like you have another mistake in receiveData(). You are using the wrong thing for the response. The response is not returns from $.ajax(). The response is passed to the success handler.
I don't know exactly what your response is supposed to look like, but change this:
function receiveData() {
var response = $.ajax({
type: "GET",
url: "/ttt",
dataType: "json",
success: function(){
grid = response.responseJSON;
console.log("Receved at client: " + JSON.stringify(grid));
}
});
console.log("Also after receiving " + JSON.stringify(grid));
}
to something like this:
function receiveData() {
$.ajax({
type: "GET",
url: "/ttt",
dataType: "json",
success: function(response){
grid = response.responseJSON;
console.log("Received at client: " + JSON.stringify(grid));
console.log("Also after receiving " + JSON.stringify(grid));
}
});
}
And, because your ajax calls are asynchronous, you also had this statement console.log("Also after receiving " + JSON.stringify(grid)); in the wrong place. If you want to see the results of the grid after you've modified it, then you have to put that inside the success handler.
Summary of Fixes
Change success: receiveData() to success: receiveData.
Use response as it is passed to the success handler.
Put console.log() to see final results inside the success handler.
It appears that you may not fully understand how ajax calls are asynchronous and what that really means for your programming. I'd suggest doing some searching and reading on that topic. Learning that now will save you a lot of agony as you develop.

Related

Getting Certain values from an AJAX return JSON object

I am trying to retrieve certain values in a JSON object retrieved from AJAX.
Using console.log(), I was able to view these:
0: Object
title: "First post"
body: "This is a post"
id: 1
userId: 27
.
.
.
100: //same format of data as object 0
Now I want to try storing the whole JSON object above so that I can use the userId and match it with another list of data to find the user who made the post. Problem is, I can't store it to a global variable. Here is my jscript snippet:
var postJson; //global variable
---somewhere in a function---
$.ajax({
url: root + '/posts',
type: "GET",
dataType: "JSON",
success: function(response){
postJson = response;
console.log(response);
}
});
I also tried doing postJson = $.ajax but nothing happened and postJson continues to be undefined.
$.ajax is async function, you need to use callback or do all the code in success function
var postJson; //global variable
function doSomething(r){
//r is here
}
---somewhere in a function---
$.ajax({
url: root + '/posts',
type: "GET",
dataType: "JSON",
success: function(response){
postJson = response;
//do something with postJson or call function doSomething(response)
}
});
function doSomething(r){
//r is here
}
---somewhere in a function---
$.ajax({
url: root + '/posts',
type: "GET",
dataType: "JSON",
success: function(response){
doSomething(response);
//do something with postJson or call function doSomething(response)
}
});
You can do directly via calling function from response no need to declare variable. Hope it will also helps you

jQuery ajax in ajax request

We have some code(simplified) that looks like bellow. We run function x which does an ajax call. When the call is done we call a different function recalculateOrderObjects which also does an ajax call. When this one is completed, it should output the data that which is obtained via the second call. However, what actually happens is that only the first ajax call is made and the second is not executed (or at least immediately goes to done) but does show the data obtained from the first call as the data obtained from the second one.
When running only the recalculateOrderObjects function the function does work as expected.
Edit 1
The subscription variable is a global
There are no errors on the console
Also, when I first call recalculateOrderObjects independent the function work when first x is called and after that I call recalculateOrderObjects independently the function will not work and shows the same behaviour as when called from `x.'
Edit 2
I tried the suggestion to use successinstead of doneas well. With the same result. recalucateOrderObjects is called succesfully, thought after one executing x the whole ajax call in recalucateOrderObjects is never requested again but instead thinks that it is succesfully executed.
function recalculateOrderObjects() {
$.ajax({
type: 'post',
url: url + "something",
data: {data: subscription}
})
.done(function (data) {
console.log('Data ' + data);
});
}
function x(){
jQuery.ajax({
type: "get",
dataType: "json",
url: url,
async: false
}).done(function (response) {
recalculateOrderObjects();
}
});}
x();
You can't get success responce by ".done" function.
"success" function gives you responce after ajax load.
Please try below code
function recalculateOrderObjects() {
$.ajax({
type: 'post',
url: url + "something",
data: {data: subscription},
success: function(data) {
console.log('Data ' + data);
}
});
}
function x(){
jQuery.ajax({
type: "get",
dataType: "json",
url: url,
success: function(data) {
recalculateOrderObjects();
}
});
}
x();
OR
function x(){
jQuery.ajax({
type: "get",
dataType: "json",
url: url,
success: function(data) {
$.ajax({
type: 'post',
url: url + "something",
data: {data: subscription},
success: function(data) {
console.log('Data ' + data);
}
});
}
});
}
x();

How to run another JS method from longPolling?

How in method with longPolling:
function getNewMessagesLong() {
pollingFishingStarts();
$request = $.ajax({
type: 'POST',
url: "listenMessageLong",
data: lastIncomingMessageLongJson,
dataType: 'json',
success: function(data) {
}, complete: getNewMessagesLong})
}
on complete to run another method?:
function pollingFishingEnds() {
document.getElementById("fishing-end").src = "resources/img/fishing-end.png";
document.getElementById("fishing-start").src = "resources/img/fishing-start-empty.png";
}
With the example you posted, you could simply do something like this, adding an anonymous function that calls your "ends" method AND restarts your polling method:
function getNewMessagesLong() {
pollingFishingStarts();
$request = $.ajax({
type: 'POST',
url: "listenMessageLong",
data: lastIncomingMessageLongJson,
dataType: 'json',
success: function(data) {
},
complete: function() {
getNewMessagesLong();
pollingFishingEnds();
}
});
}
You could also change up to a window.setInterval() long-polling paradigm that would allow you to use your complete option to set your actual end method, rather than hijacking it for long-polling.
I'm assuming here that you want to call the "end" state code after the first round completion. Otherwise, there's literally no end to your polling, unless you have some server message to terminate, in which case you need to post that code for additional information.

AJAX trigger remote script then check for success-response

I've been searching my brains out but I can't seem to wrap my head around the little help I find.
I'm running a database that is being fed by data from another DB. The csv transport is handled by a third party server providing executable "flows" which compile and deliver the data.
I have a php script to handle the request (can't be done directly via Javascript because of the missing 'Access-Control-Allow-Origin' header). But this runs nicely. I can trigger the flow.
This is not the problem though.
What I want to do: trigger the flow #onClick of a button with something like this:
function trigger_func(flowID) {
$.ajax({
url: './ajaxPHP_handler.php',
data: "flowid="+flowID,
dataType: 'json',
success: function(result) {
var jsonResult = jQuery.parseJSON(result);
console.log(jsonResult.runID);
}
});
}
With the flowID and the resulting runID I want to check back like every second or so.
function check_status(flowID, runID) {
$.ajax({
url: './ajaxPHP_handler.php',
data: "flowid="+flowID+"&action=status&runId="+runID,
dataType: 'json',
success: function(result){...}
});
}
This will return the status / progress of the flow.
It will start for a few seconds with status==null, then go on to status=='running' and finally status=='success'.
I have gotten check_status() to run for i.e. 15 times with a setTimeout in a for loop within the success-function of trigger_func() and it works fine too.
But I cannot for the life of me figure out how I would link this stuff together to have it checking until status is 'success' and then stop checking, update page content and so on...
I have also fiddled with something like
trigger_func(id).done(function(result){
console.log(result);
});
This works too but still I can't think my way further to the checking every second until 'success'. I guess it comes down to getting the variable 'status' back into my loop so I can break it.
Maybe someone knows of a comprehensible example somewhere online...
You could do this:
function periodically_check_status_until_success(flowID, runID) {
setTimeout(function() {
$.ajax({
url: './ajaxPHP_handler.php',
data: { flowid: flowID, action: status, runId: runID },
dataType: 'json',
success: function(result){
if (result != 'success') {
periodically_check_status_until_success(flowID, runID);
}
}
});
}, 5000); // Five seconds
}
Note: You can use an object for the data option, rather than concatenate the string yourself.
So just keep calling it
var flowID, runID;
function trigger_func(flowID) {
$.ajax({
url: './ajaxPHP_handler.php',
data: "flowid="+flowID,
dataType: 'json',
success: function(result) {
var jsonResult = jQuery.parseJSON(result);
runID= jsonResult.runID;
check_status();
}
});
}
function check_status() {
$.ajax({
url: './ajaxPHP_handler.php',
data: "flowid="+flowID+"&action=status&runId="+runID,
dataType: 'json',
success: function(result){
if (result is not what you want) {
setTimeout(check_status,1000);
}
}
});
}
ajax are async so you have to manage by this via some 3rd party variable
Like Init with value 0
var _status = 0
than change it on your first call set it 1
function trigger_func(flowID) {
$.ajax({
url: './ajaxPHP_handler.php',
data: "flowid="+flowID,
dataType: 'json',
success: function(result) {
var jsonResult = jQuery.parseJSON(result);
console.log(jsonResult.runID);
check_status(flowID, runID);
}
});
}
function check_status(flowID, runID) {
$.ajax({
url: './ajaxPHP_handler.php',
data: "flowid="+flowID+"&action=status&runId="+runID,
dataType: 'json',
success: function(result){
//at end status=='success'.
if(status=='success'){
// end part
}else{// running
check_status(flowID, runID);
}
// clear timeout will stop that time interval after success
}
});
}

AJAX: How to use returned array?

I have an ajax POST that sends data to a controller function and that function returns a string array back to the ajax call as the default 1st parameter in the ajax success method. When I tried to use the returned data, it won't let me print the 1st element to an alert box. How come?
i.e.
$.ajax(
{
type: "POST",
url: "../Home/stringSplitFunct",
data: { 'parameter1': Input },
success: function (response)
{
alert(response[0]);
}
});
In fact, I don't think it even recognize it as a string array.
You need to specify dataType. Read more here.
$.ajax({
type: "POST",
url: "../Home/stringSplitFunct",
data: { 'parameter1': Input },
dataType: 'json',
success: function (response)
{
alert(response[0]);
}
});
Looks like the data is being returned as a raw sting.
Use dataType property for your ajax request
dataType: 'json'
Also avoid using alert as it stops the execution flow. Use console.log instead

Categories