how do to polling in jquery? - javascript

I have a Post call. After the result I want to do another get CALL to check the status. But only if the status is FINISHED.
jQuery.ajax({
type: "POST",
contentType: "application/json",
url: "/doPostURL....,
headers: {
"x-csrf-token": sCsrftoken
},
success: function() {
.. now I want to do the polling on the status
jQuery.ajax({
type: "GET",
dataType: "json",
url: "/getStatusUrl ,
success: function(data, textStatus, response) {
// to continue only if status if Finished
},
error: function() {
}
});
}
});

$.ajax returns a deferred object.
You can do something like below. More info here
var doSomething = $.ajax({
url: '/path/to/file',
type: 'default GET (Other values: POST)',
dataType: 'default: Intelligent Guess (Other values: xml, json, script, or html)',
data: {param1: 'value1'},
})
function doneCallback(){
// Handle exit condition here.
doSomething();
}
function failCallback(){
// Handle failure scenario here.
}
doSomething.then(doneCallback, failCallback)

Just set your code in a function:
jQuery.ajax({
type: "POST",
contentType: "application/json",
url: "/doPostURL....,
headers: {
"x-csrf-token": sCsrftoken
},
success: function() {
doPoll();
}
});
var doPoll = function() {
jQuery.ajax({
type: "GET",
contentType: "application/json",
url: "/getStatusUrl ,
success: function(data, textStatus, response) {
//do stuff
doPoll();
},
error: function() {
//handle error
}
});
}

You can try to export the ajax call to a function and use recursion to pool.
Note: You should have a max counter so that you do not flood server with infinite calls.
var max_count = 20;
var counter = 0;
function getStatus() {
jQuery.ajax({
type: "GET ",
contentType: "application / json ",
url: " / getStatusUrl,
success: function(data, textStatus, response) {
// to continue only if status if Finished
if (textStatus != "status" && ++counter < max_count) {
getStatus();
}
},
error: function() {}
});
}

Related

Jquery - $.When not trigger ajax on done menthod

Was try to implement another ajax call based on the first two results with Jquery $.When method. Basically, all three Ajax will populate a carousel on the page based on the results. Therefore I choose $.When for continuous checking. But the third Ajax which under Done() method is not called even there was no result from above two APIs or with initial values zero(0). Not sure if I missed anything!
jQuery:
let itemCat1Count = 0;
let itemCat2Count = 0;
$.when(
$.ajax({
url: "/webmethod/GetItemsCatOne",
type: "POST",
data: '',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
if (typeof (data.ResponseObject) !== undefined && data.ResponseObject !== null) {
itemCat1Count = data.ResponseObject.Items.length;
// carousel inital codes
}
},
error: function (jqXHR, status, error) {}
}),
$.ajax({
url: "/webmethod/GetItemsCatTwo",
type: "POST",
data: '',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
if (typeof (data.ResponseObject) !== undefined && data.ResponseObject !== null) {
itemCat2Count = data.ResponseObject.Items.length;
// carousel inital codes
}
},
error: function (jqXHR, status, error) {}
}),
).done(function (xhrSavedRings, xhrShoppingBagItems) {
if (itemCat1Count == 0 && itemCat2Count == 0) {
$.ajax({
url: "/webmethod/GetItemsSpecial",
type: "GET",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (jObject) {
console.log(jObject);
// carousel inital codes
},
error: function (jqXHR, status, error) {}
});
}
});
Few things to highlight - $.when() requires promises as arguments. $.when does not have the powers to know when functions you passing are done or completed
From the official documentation of $.when You have return promises or return something from your ajax calls.
Here what its says => In the case where multiple Deferred objects are passed to jQuery.when(), the method returns the Promise from a new "master" Deferred object that tracks the aggregate state of all the Deferreds it has been passed.
I have assigned a retrun value from each $.ajax call you are making. $.when will know check if there is something coming from return and is resolved then it will go to .done
Run snippet below to see the console log on .done
let itemCat1Count = 0;
let itemCat2Count = 0;
function first() {
return $.ajax({
url: "/webmethod/GetItemsCatOne",
type: "POST",
data: '',
contentType: "application/json; charset=utf-8",
success: function(data) {
if (typeof(data.ResponseObject) !== undefined && data.ResponseObject !== null) {
console.log(data.ResponseObject.Items.length)
itemCat1Count = data.ResponseObject.Items.length;
// carousel inital codes
}
},
error: function(jqXHR, status, error) {}
});
}
function second() {
return $.ajax({
url: "/webmethod/GetItemsCatTwo",
type: "POST",
data: '',
contentType: "application/json; charset=utf-8",
success: function(data) {
if (typeof(data.ResponseObject) !== undefined && data.ResponseObject !== null) {
itemCat2Count = data.ResponseObject.Items.length;
// carousel inital codes
}
},
error: function(jqXHR, status, error) {}
});
}
$.when.apply(first(), second()).done(function() {
console.log("First and Second is done running - I am from done");
if (itemCat1Count == 0 && itemCat2Count == 0) {
return $.ajax({
url: "/webmethod/GetItemsSpecial",
type: "GET",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(jObject) {
console.log(jObject);
// carousel inital codes
},
error: function(jqXHR, status, error) {}
});
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

jQuery Ajax get value via function?

I have created a save(id) function that will submit ajax post request. When calling a save(id). How to get value/data from save(id) before going to next step. How to solve this?
For example:
function save(id) {
$.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
id: id,
}),
success: function (data) {
return data;
},
error: function (error) {
return data;
}
});
}
Usage:
$('.btn-create').click(function () {
var id = 123;
data = saveArea(id); //get data from ajax request or error data?
if (data) {
window.location = "/post/" + data.something
}
}
You have two options, either run the AJAX call synchronously (not recommended). Or asynchronously using callbacks
Synchronous
As #Drew_Kennedy mentions, this will freeze the page until it's finished, degrading the user experience.
function save(id) {
return $.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
async: false,
data: JSON.stringify({
id: id,
})
}).responseText;
}
$('.btn-create').click(function () {
var id = 123;
// now this will work
data = save(id);
if (data) {
window.location = "/post/" + data.something
}
}
Asynchronous (recommended)
This will run in the background, and allow for normal user interaction on the page.
function save(id, cb, err) {
$.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
id: id,
}),
success: function (data) {
cb(data);
},
error: err // you can do the same for success/cb: "success: cb"
});
}
$('.btn-create').click(function () {
var id = 123;
save(id,
// what to do on success
function(data) {
// data is available here in the callback
if (data) {
window.location = "/post/" + data.something
}
},
// what to do on failure
function(data) {
alert(data);
}
});
}
Just make things a bit simpler.
For starters just add window.location = "/post/" + data.something to the success callback.
Like this:
function save(id) {
return $.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
id: id,
}),
success:function(data){
window.location = "/post/" + data.something
}
}).responseText;
}
Or by adding all your Ajax code within the click event.
$('.btn-create').click(function () {
var id = "123";
$.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
id: id,
}),
success: function (data) {
window.location = "/post/" + data.something
},
error: function (error) {
console.log(error)
}
});
}

how to get the json string in a variable

i got my json string inside the ajax as function like this way
$.ajax({
type: "POST",
url: "http://localhost/./Service/GetPageInfo",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
filename: filename
}),
success: function (data) {
alert('Success');
},
error: function () {
alert('Error');
}
});
here i get data like
[{"main":{"sub":[],"tittle":"manu","startvalue":"","stopvalue":"","status":"","accumalated":"","comment":""}}]
i want it in a variable like
var myjsonobject =[{"main":{"sub":[],"tittle":"manu","startvalue":"","stopvalue":"","status":"","accumalated":"","comment":""}}]
There you go :
$.ajax({
type: "POST",
url: "http://localhost/./Service/GetPageInfo",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
filename: filename
}),
success: function (data) {
alert('Success');
var jsonobject = data;
},
error: function () {
alert('Error');
}
});
Also I strongly advise you to use promises to make API calls: https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Promise
var jsonobject= null;
$.ajax({
type: "POST",
url: "http://localhost/./Service/GetPageInfo",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
filename: filename
}),
success: function (data) {
jsonobject=data;
alert('Success');
},
error: function () {
alert('Error');
}
});
If you want wait for ajax response and fill up variable then pass async: false in ajax request options.
Based on your comment, you need to parse the JSON in your success handler,
success: function (data) {
alert('Success');
var myjsonobject = JSON.parse( data );
},

jQuery wait until function ends then do it again

var repeat = 5;
for (var i = 0; i < repeat.length; ++i)
{
$.ajax({
type: 'POST',
headers: { "cache-control": "no-cache" },
url: baseUri + '?rand=' + new Date().getTime(),
async: true,
cache: false,
dataType : "json",
data: 'something_to_post=1234'),
success: function(jsonData,textStatus,jqXHR)
{
//some functions
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
//some alert code
}
});
}
So this loop will repeat 2 times and will make 2 request at the same time, so my question is, how do I delay it , when first loop is done...move to second loop.
Thank you
You've got to think in terms of callbacks. You have a task - making an AJAX call - and you want to do it again after the AJAX call finishes. Put the task into a function, and then call that function from the success callback of the AJAX call. To keep track of the number of repeats, pass it into the function as an explicit variable:
function makeCalls(numCalls) {
if (numCalls <= 0) {
return;
}
$.ajax({
type: 'POST',
headers: { "cache-control": "no-cache" },
url: baseUri + '?rand=' + new Date().getTime(),
async: true,
cache: false,
dataType : "json",
data: 'something_to_post=1234'),
success: function(jsonData,textStatus,jqXHR)
{
//some functions
//make the next call
makeCalls(numCalls - 1);
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
//some alert code
}
});
}
makeCalls(5);
The way I wrote it here, it won't make the next call if there's an error, but it's up to you what you want to do in that case.
Use recursive function.
function callme(){
if(i<5){
$.ajax({
type: 'POST',
headers: { "cache-control": "no-cache" },
url: baseUri + '?rand=' + new Date().getTime(),
async: true,
cache: false,
dataType : "json",
data: 'something_to_post=1234'),
success: function(jsonData,textStatus,jqXHR)
{
callme();
i++;
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
//some alert code
}
});}
}

Jquery Ajax Call, doesn't call Success or Error [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I return the response from an asynchronous call?
I am using Jquery Ajax to call a service to update a value.
function ChangePurpose(Vid, PurId) {
var Success = false;
$.ajax({
type: "POST",
url: "CHService.asmx/SavePurpose",
dataType: "text",
data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
contentType: "application/json; charset=utf-8",
success: function (data) {
Success = true;//doesn't go here
},
error: function (textStatus, errorThrown) {
Success = false;//doesn't go here
}
});
//done after here
return Success;
}
and Service:
[WebMethod]
public string SavePurpose(int Vid, int PurpId)
{
try
{
CHData.UpdatePurpose(Vid, PurpId);
//List<IDName> abc = new List<IDName>();
//abc.Add(new IDName { Name=1, value="Success" });
return "Success";
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
the service is being called Successfully from the AJAX. Value is also being Changed. But after the Service, success: or error: functions are not being called, in this case success should have been called but it is not working.
I used firebug and found that, the success or error functions are being skipped and goes directly to return Success;
Can't seem to find what's the problem with the code.
Update:
adding async: false fixed the problem
change your code to:
function ChangePurpose(Vid, PurId) {
var Success = false;
$.ajax({
type: "POST",
url: "CHService.asmx/SavePurpose",
dataType: "text",
async: false,
data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
contentType: "application/json; charset=utf-8",
success: function (data) {
Success = true;
},
error: function (textStatus, errorThrown) {
Success = false;
}
});
//done after here
return Success;
}
You can only return the values from a synchronous function. Otherwise you will have to make a callback.
So I just added async:false, to your ajax call
Update:
jquery ajax calls are asynchronous by default. So success & error functions will be called when the ajax load is complete. But your return statement will be executed just after the ajax call is started.
A better approach will be:
// callbackfn is the pointer to any function that needs to be called
function ChangePurpose(Vid, PurId, callbackfn) {
var Success = false;
$.ajax({
type: "POST",
url: "CHService.asmx/SavePurpose",
dataType: "text",
data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
contentType: "application/json; charset=utf-8",
success: function (data) {
callbackfn(data)
},
error: function (textStatus, errorThrown) {
callbackfn("Error getting the data")
}
});
}
function Callback(data)
{
alert(data);
}
and call the ajax as:
// Callback is the callback-function that needs to be called when asynchronous call is complete
ChangePurpose(Vid, PurId, Callback);
Try to encapsulate the ajax call into a function and set the async option to false. Note that this option is deprecated since jQuery 1.8.
function foo() {
var myajax = $.ajax({
type: "POST",
url: "CHService.asmx/SavePurpose",
dataType: "text",
data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
contentType: "application/json; charset=utf-8",
async: false, //add this
});
return myajax.responseText;
}
You can do this also:
$.ajax({
type: "POST",
url: "CHService.asmx/SavePurpose",
dataType: "text",
data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
contentType: "application/json; charset=utf-8",
async: false, //add this
}).done(function ( data ) {
Success = true;
}).fail(function ( data ) {
Success = false;
});
You can read more about the jqXHR jQuery Object

Categories