I am trying to find out what parameters I can pass to a jQuery ajax call.
What I am used to is writing something like:
$.ajax({
....
success: function(response) {
// put callback here
}
....
});
So here is my question:
Obviously the "response" variable I put in the success function just takes back whatever the server sends back from the ajax call. Is there any possible way to send multiple variables back? Something like:
...
success: function(response,httpStatus,whateverElse) {
}
...
Or, is there some other way to get the http response codes?
Thanks to whoever can answer this!
You can get the response's status code on the success' third parameter or complete's first parameter, something like this:
$.ajax({
success: function(data, textStatus, xhr) {
console.log(xhr.status);
},
complete: function(xhr, textStatus) {
console.log(xhr.status);
}
});
Further to #Kokizzu you can check the jQuery API site to see what parameters are passed to the other functions http://api.jquery.com/jquery.ajax/.
Also another way that I find handy to work out what parameters are being passed when there are no docs available is:
success: function() {
console.log(arguments);
}
That will log to the console all of the arguments that were passed to that function when it was called.
You can also have the server send back json json_encode in php:
Php:
$array['status'] = 0;
$array['foo'] = 'bar';
json_encode($array);
Ajax:
$.ajax({
...
success: function (data) {
console.log(data);
}
});
Then obviously you could have your callback handle those variables.
$.ajax({
success: function(data, status, xhttp) {
console.log(status + ": " + data);
},
error: function(data, status, xhttp) {
console.log(status + ": " + data);
}
});
Related
I have built function that checks if record exist in local storage, if not trigger ajax call to get the data. Once data is returned I set the data in local storage. After this function completes I have to pass the data to another function that will feed the data in the form. I'm wondering what is the best practice now days to achieve this? I see more object oriented JavaScript now days and I'm wondering if any of OOP methods can be applied in this case. Here is example of my fucntion:
function getData(fnName,storageID,recID){
var inStorage = localStorage.hasOwnProperty(storageID) ? true : false,
frmData;
if(inStorage) {
frmData = JSON.parse(localStorage.getItem(storageID));
}else{
$.ajax({
type: 'POST',
url: 'AjaxFunctions.cfc?method='+fnName,
data: {'recID':recID},
dataType: 'json',
async: false
}).done(function(obj){
if(obj.STATUS == "200"){
var storageData = $.isEmptyObject(obj.DATA) ? null : JSON.stringify(obj.DATA);
localStorage.setItem(storageID,storageData);
frmData = storageData;
}else{
$('#error').html(obj.MESSAGE);
}
}).fail(function(jqXHR, textStatus, errorThrown){
alert("Error: "+errorThrown);
});
}
//frmFeed(frmData);
return frmData;
}
Function above once completed should pass the data in another function that will populate the form:
function frmFeed(frmData){
//Loop over frmData and populate the fields
}
I know the one way to accomplish this is to simply call frmFeed inside getData function that I showed above (commented code). is there any other way to call frmFeed and pass the data? If anyone can provide some example please let me know. Thank you!
There are several ways:
Callbacks
Promises
Not recommended would be to use synchronous ajax requests because it will block the UI.
Here's an implementation using promises:
function getData(fnName,storageID,recID){
return new Promise(function(resolve, reject) {
var inStorage = localStorage.hasOwnProperty(storageID) ? true : false;
if (inStorage) {
resolve(JSON.parse(localStorage.getItem(storageID)));
} else {
$.ajax({
type: 'POST',
url: 'AjaxFunctions.cfc?method='+fnName,
data: { 'recID': recID },
dataType: 'json'
// removed sync
}).done(function(obj){
if(obj.STATUS == "200"){
var storageData = $.isEmptyObject(obj.DATA) ? null : JSON.stringify(obj.DATA);
localStorage.setItem(storageID,storageData);
resolve(storageData);
}else{
$('#error').html(obj.MESSAGE);
// or reject here
reject(obj);
}
}).fail(function(jqXHR, textStatus, errorThrown){
alert("Error: "+errorThrown);
// or reject may be better here
reject({ 'jqXHR': jqXHR, 'textStatus': textSTatus, 'errorThrown': errorThrown });
});
}
});
}
getData('blah', 'storageId', 'recId')
.then(function(frmData) {
frmFeed(frmData);
});
I have a quiz type application. Each question has two answers with a value of 1 or 2. When the quiz is complete, if they have a score lower than 10, they get redirected to a page.
This is my code for this part.
while (n < numResults) {
increment = minScore + (interval * n);
if (totalScore <= increment) {
if(totalScore <= 10) {
$.ajax({
method: "POST",
url: "handleData.php",
dataType: "json",
data: { answers: ansArray, page: window.location.href }
})
.done(function( msg ) {
window.location.href("www.page2.html");
});
}
return;
} else {
n++;
}
}
I have a few things I am trying to solve. Firstly, before the redirect, some data (answers and url) is posted to PHP so I can process it. One thing I pass is the current window url. The reason I do this is because the
url has a format like
www.page1.com?a=1&b=2&c=3
In PHP, I parse this url and grab the values.
My first problem is that although the data is successfuly sent to PHP and handled, and returns a response of Success, the done function never seems to fire, therefore no redirect occurs (I put an alert in this function
to ensure it is not firing). In PHP, after I process the data, I do this
var_dump($response); //Outputs Success
return json_encode($response);
The second thing I am trying to work out is the redirect url (page2.html). Within this page, I have a button. This button has a standard link, and then I need to give it some params from the initial url.
So this pages button might be something like
www.externallink.com?a=1&c=2
How can I get the original URLs params into a button on the redirected url?
Thanks
USE below function insted of done:
$.ajax({
method: "POST",
url: "handleData.php",
dataType: "json",
data: { answers: ansArray, page: window.location.href }
success:function(data){
window.location.href("www.page2.html");
});
})
For your 1st part:
Try putting the error function of jQuery ajax call. Sometimes when the return type of result does not match with the expected datatype of ajax call, then result comes in the response of error.
error: function (data, status, e) {
}
For your 2nd part:
Attach click event for the button in the handler and read the current URL query string using window.location.search and then redirect using
window.location = newURL + "extra query params";
// Assign handlers immediately after making the request,
// and remember the jqXHR object for this request
var jqxhr = $.ajax( "example.php" )
.done(function(data, textStatus, jqXHR) {
alert( "success" );
})
.fail(function(jqXHR, textStatus, errorThrown) {
alert( "error" );
})
.always(function(data|jqXHR, textStatus, jqXHR|errorThrown) {
alert( "complete" );
});
If you .done() callback never invoked, try to set debuggers or alerts inside .fail() or .complete() callback functions. Check if you have an error during ajax call and at all if the call has complete statement.
Here more information: http://api.jquery.com/jquery.ajax/
I am running in to some interesting situation. on my application I have couple of situations.
1. I have to grab data from two different sources.(for that i have used ajax call).
2. I have to manipulate those data comparing to each other. if both are equal than third array will gets the value input from first array first array. and Eventually i have to return the third value and work on my graphs.
so for that I have :
getData : function(){
var bubbleArray= [];
var companyData=[];
var managerData =[];
$.ajax({
async: false,
url: "data/companyData.json",
dataType: "json",
success: function (bubbleJsonData){
$.each (bubbleJsonData.main.DATA_RECORD, function(index, response){
if(response.C_HRS!=0&&response.D_CUST_HRS!=0){
companyData.push([(response.C_HRS/442)*100, (response.D_CUST_HRS/442)*100, ((response.D_CUST_HRS/response.C_HRS)*100), response.C_HRS, response.D_CUST_HRS, response.CPY_NAME ]);
}
});
},
error: function(jqXHR, textStatus, errorThrown){
alert("Error:"+ errorThrown);
}
//ajax call to get the managerData.
$.ajax({
async: false,
url: "data/managerData.json",
dataType:"json",
success: function(managerjsonData){
$.each (managerjsonData.main.DATA _RECORD, function(index, responsedata){
if(responsedata.CPY_NAME!=""){
managerData.push([responseData.CPY_NAME]);
}
});
},
error: function(jqXHR, textStatus, errorThrown){
alert("Error:"+ errorThrown);
}
});
});
now, I have to compare the managerData. CPY_NAME with companyData.CPY_NAME if the match found generate the bubbleArray with the details of companyData means bubbleArray should have C_HRS, D_CUST_HRS,..........
if any help available form anybody would be highly appreciated
You need to wait until both the requests finish and save their results in some variable, and then compare them.
var yourAjaxRequests = [];
var jqXHR = $.ajax();
yourAjaxRequests.push(jqXHR);
$.when.apply($, yourAjaxRequests).done(function() {
/* compare logic here */
);
I have no idea how I can achieve this.
I am using jQuery 1.9 for ajax call back.
I have a function, let's say:
function a (param){
//calling a function this will perform ajax
data = performAjax(param, url, etc);
// render response
renderResponse(data);
}
We are executing our ajax in perform ajax function.
Issue is when ajax fails then it perform ajaxError function.
I put a message in div that please refresh this again.
But how can I get function a and all the parameter of that in ajaxError function? So that I can put a link to refresh again.
Not sure if I understand correctly, but here it goes:
function performAjax() {
return $.ajax({
....
});
}
var lastFailedFunction;
function a (param){
var args = arguments;
//calling a function this will perform ajax
performAjax().then(function(data) { // on success
// render reponse
renderResponse(data);
}, function() { // on failure
lastFailedFunction = function() {
a.apply(a, args);
};
// now you can call lastFailedFunction() to try again
});
}
When the ajax-call fails, it will store the failed function call to lastFailedFunction. So somewhere else you might show this message:
<div>Function A failed, click here to try again</div>
Using error callback of ajax, you can get the error message
function a(param) {
var performAjax = $.ajax({
type: "",
url: "",
data: "",
success: function(msg){
//success msg
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
//can access param of fun a and the error message
//append it to the body
$('body').append('<div>'+param+' error: '+errorThrown+'</div>');
}
});
}
I am developing a heavily scripted Web application and am now doing some Error handling. But to do that, I need a way to access the AJAX parameters that were given to jQuery for that specific AJAX Request. I haven't found anything on it at jquery.com so I am asking you folks if you have any idea how to accomplish that.
Here is an example of how I want to do that codewise:
function add_recording(filename) {
updateCounter('addRecording','up');
jQuery.ajax({
url: '/cgi-bin/apps/ajax/Storyboard',
type: 'POST',
dataType: 'json',
data: {
sid: sid,
story: story,
screen_id: screen_id,
mode: 'add_record',
file_name: filename
},
success: function(json) {
updateCounter('addRecording','down');
id = json[0].id;
create_record(id, 1, 1, json);
},
error: function() {
updateCounter('addRecording','error',hereBeData);
}
})
}
hereBeData would be the needed data (like the url, type, dataType and the actual data).
updateCounter is a function which updates the Status Area with new info. It's also the area where the User is notified of an Error and where a Dismiss and Retry Button would be generated, based on the Info that was gathered in hereBeData.
Regardless of calling complete() success() or error() - this will equal the object passed to $.ajax() although the values for URL and data will not always be exactly the same - it will convert paramerters and edit the object around a bit. You can add a custom key to the object to remember your stuff though:
$.ajax({
url: '/',
data: {test:'test'},
// we make a little 'extra copy' here in case we need it later in an event
remember: {url:'/', data:{test:'test'}},
error: function() {
alert(this.remember.data.test + ': error');
},
success: function() {
alert(this.remember.data.test + ': success');
},
complete: function() {
alert(this.remember.data.url + ': complete');
}
});
Of course - since you are setting this data originally from some source - you could rely on the variable scoping to keep it around for you:
$("someelement").click(function() {
var theURL = $(this).attr('href');
var theData = { text: $(this).text(); }
$.ajax({
url: theUrl,
data: theData,
error: function() {
alert('There was an error loading '+theURL);
}
});
// but look out for situations like this:
theURL = 'something else';
});
Check out what parameters you can get in the callback for error.
function (XMLHttpRequest, textStatus, errorThrown) {
// typically only one of textStatus or errorThrown
// will have info
this; // the options for this ajax request
}
You can use the ajax complete event which passes you the ajaxOptions that were used for the request. The complete fires for both a successful and failed request.
complete : function (event, XMLHttpRequest, ajaxOptions) {
//store ajaxOptions here
//1 way is to use the .data on the body for example
$('body').data('myLastAjaxRequest', ajaxOptions);
}
You can then retireve the options using
var ajaxOptions = $('body').data('myLastAjaxRequest');