I am creating a application where I have lot of ajax calls to a remote server and use them extensively. As the code is almost same in all calls, I want to create a new function which I can reuse. I am struck up in defining the parameter structure for the "data" parameter. I will explain below my problem.
Sample of my current ajax call is provided below.
Current Call Sample:
$.ajax({
beforeSend: function() {
$.mobile.loading('show');
},
complete: function() {
$.mobile.loading('hide');
},
type: 'GET',
url: 'http://localhost/test-url/',
crossDomain: true,
data: {appkey: '1234567', action: 'action1','name':'me'},
dataType: 'jsonp',
contentType: "application/javascript",
jsonp: 'callback',
jsonpCallback: 'mycallback',
async: false,
error: function() {
//some operations
},
success: function(data) {
//some operations
}
});
The re-usable function that I have created:
function newAjax(parm, successCallback, errorCallback) {
$.ajax({
beforeSend: function() {
$.mobile.loading('show');
},
complete: function() {
$.mobile.loading('hide');
},
type: 'GET',
url: 'http://localhost/test-url',
crossDomain: true,
data: {appkey: '1234567', parm: parm},
dataType: 'jsonp',
contentType: "application/javascript",
jsonp: 'callback',
jsonpCallback: 'mycallback',
async: false,
success: function() {
successCallback();
},
error: function() {
errorCallback();
}
});
}
Question:
I will be passing the the parameters for the ajax call via "parm" parameter. I want the data value to be directly added to the parent "data" parameter. And not as a sub-object of data. The appKey remains same across all calls and so I keep it in the actual function.
I want both the success and error callback functions to be optional. If not provided they should be ignored.
You can use the jQuery.extend method to combine two or more objects together.
data: jQuery.extend({appkey: '1234567'}, parm),
You can check that you were actually passed functions for successCallback and errorCallback using typeof var === 'function';
success: function () {
if (typeof successCallback === 'function') {
successCallback();
}
},
error: function () {
if (typeof errorCallback === 'function') {
errorCallback();
}
}
... although it might be nicer if you just returned the Promise created by the AJAX request, and let the caller add their success, error handlers if they wanted;
function newAjax(parm) {
return jQuery.ajax({
/* as before, but without success and error defined */
});
}
... then:
newAjax().done(function () {
// Handle done case
}).fail(function () {
// Handle error case.
});
If a caller doesn't want to add an error handler, they just don't call fail();
newAjax().done(function () {
// Handle done case
});
Related
I've already read this article How do I return the response from an asynchronous call? However I couldn't come up with a solution.
I'm doing an ajax request
function getdata(url)
{
console.log('Started');
jQuery.ajax({
type: "GET",
url: "http://myserver.com/myscript.php",
dataType: "json",
error: function (xhr) {
console.log('Error',xhr.status);
},
success: function (response) {
console.log('Success',response);
}
});
}
And Console displays everything fine but when I say
var chinese = getdata();
to get the data. I keep getting:
Uncaught TypeError: Cannot read property 'length' of undefined error for this line
var text = chinese[Math.floor(Math.random()*chinese.length)];
Can anybody help me here?
The problem is that you are using an asynchronous method expecting a synchronous result.
Therefore you should use the code in the result of the asynchronous call like the following:
function getdata(url) {
console.log('Started');
jQuery.ajax({
type: 'GET',
url: url,
dataType: 'json',
error: function(xhr) {
console.log('Error', xhr.status);
},
success: function(chinese) {
var text = chinese[Math.floor(Math.random()*chinese.length)];
// Do something else with text
}
});
}
getData('http://myserver.com/myscript.php');
I hope it helps :)
The error you get is because of the asynchronous nature of the call. I suggest you to assign the value after you get the success response from the API like below.
var chinese = getdata();
Then the function getdata() will be like
function getdata(url)
{
console.log('Started');
jQuery.ajax({
type: "GET",
url: "http://myserver.com/myscript.php",
dataType: "json",
error: function (xhr) {
console.log('Error',xhr.status);
},
success: function (response) {
initChinese(response.data);
}
});
}
And create a function initChinese() like
var text;
function initChinese(chinese){
text = chinese[Math.floor(Math.random()*chinese.length)];
}
You can also declare the text variable in global scope and then assign the value to text variable inside the success function without having to create a new function initChinese.
The problem is your getdata function does not return anything. In your getdata function you're doing a ajax request, which is an asynchronous request. So the data you're requesting won't, and can't be returned with your getdata function.
But you will have the requested data in your success function:
function getdata(url)
{
console.log('Started');
jQuery.ajax({
type: "GET",
url: "http://myserver.com/myscript.php",
dataType: "json",
error: function (xhr) {
console.log('Error',xhr.status);
},
success: function (response) {
console.log('Success',response);
var text = response[Math.floor(Math.random()*response.length)];
}
});
}
As I'm not able to test your code, you've to debug the rest on your own. But the response variable will be most likely your "chinese" variable.
You could try using callbacks or you could look at Promises.
The idea with callbacks is that you pass a function that is run after the ajax request is finished. That callback can accept a parameter, in this case the response.
Using callbacks:
function getData(url, successCallback, errorCallback) {
console.log('Started');
jQuery.ajax({
type: "GET",
url: url,
dataType: "json",
error: function(xhr) {
errorCallback(xhr.status);
},
success: function(response) {
successCallback(response);
}
});
}
var chinese;
getData("http://myserver.com/myscript.php", function(response) {
chinese = response; // you can assign the response to the variable here.
}, function(statusCode) {
console.error(statusCode);
});
Using Promises (< IE11 doesn't support this):
function getData(url) {
return new Promise(function(resolve, reject) {
console.log('Started');
jQuery.ajax({
type: "GET",
url: url,
dataType: "json",
error: function(xhr) {
reject(xhr.status);
},
success: function(response) {
resolve(response);
}
});
});
}
var chinese;
getData("http://myserver.com/myscript.php").then(function(response) {
chinese = response;
console.log(chinese);
}, function(statusCode) {
console.error(statusCode);
});
I think it is simple question. I've tried to search but still not found an answer yet.
deleteComment: function (commentJson, success, error) {
$.ajax({
type: "POST",
async: false,
url: deleteCommentConfig.url,
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ commentId: commentJson.CommentId }),
dataType: "json",
success: function (result) {
if (result.d) {
success();
}
messageBox(result.d);
},
error: error
});
},
var messageBox = function (hasDeleted) {
if (hasDeleted) {
alert("Deleted successfully");
} else {
alert("Error");
}
}
I want to show message after success() performed.
That means the comment left already then show message.
Thanks anyway!
P/s: I read a topic about jQuery Callback Functions at https://www.w3schools.com/jquery/jquery_callback.asp.
Can we use it in here? If we can, how to use?
You can try like this
deleteComment: function (commentJson, success, error) {
$.ajax({
type: "POST",
async: false,
url: deleteCommentConfig.url,
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ commentId: commentJson.CommentId }),
dataType: "json",
success: function (result) {
if (result.d) {
success();
}
$.when(this).then(setTimeout(function(){ messageBox(result.d)}, 200));
// if you dont want use set timeout then use
// $.when(this).then(messageBox(result.d), 200));
},
error: error
});
},
var messageBox = function (hasDeleted) {
if (hasDeleted) {
alert("Deleted successfully");
} else {
alert("Error");
}
}
Provides a way to execute callback functions based on zero or more Thenable objects, usually Deferred objects that represent asynchronous events.
Considering your implementation of var success = function() you may try with following approach:
Modify the success() to accept callback function as follows:
var success = function(callback) {
self.removeComment(commentId);
if(parentId)
self.reRenderCommentActionBar(parentId);
if(typeof callback == "function")
callback();
};
var messageBox = function (hasDeleted) {
if (hasDeleted) {
alert("Deleted successfully");
} else {
alert("Error");
}
}
deleteComment: function (commentJson, success, error) {
$.ajax({
type: "POST",
async: false,
url: deleteCommentConfig.url,
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ commentId: commentJson.CommentId }),
dataType: "json",
success: function (result) {
if (result.d) {
//passing the callback function to success function
success(function(){
messageBox(result.d);
});
}
},
error: error
});
},
The following call works great in every browser but IE. $.ajaxSetup doesn't get recognized. The error and complete functions won't be called unless I add them directly into the $.ajax call.
Any idea why?
function setupAjaxCalls() {
$.ajaxSetup({
type: 'GET',
dataType: "jsonp",
contentType: "application/json",
data: {
deviceIdentifier: deviceIdentifier,
deviceType: deviceType,
memberId: loggedInMemberId,
authToken: authToken,
cache: false,
responseFormat: 1
},
error: function (x, e) {
defaultError(x, e);
},
complete: function () {
apiCallInProgress = 'false';
//alert('complete!');
}
});
}
function logInForm(memLogin, memPassword, callback) {
apiCallInProgress = 'true';
$.ajax({
type: 'POST',
dataType: "json",
url: baseApiUrl + '/MembershipService/AuthLoginSecure',
data: {
login: memLogin,
password: memPassword,
responseFormat: 0
},
success: function (data) {
if (data.Success == false) {
apiError(data);
} else {
loggedInMemberId = data.Member.Id;
authToken = data.Token;
if (typeof (callback) != "undefined" || callback) {
callback(data);
}
}
}
});
}
Straight from the documentation:
http://api.jquery.com/jQuery.ajaxSetup/
Note: Global callback functions should be set with their respective global Ajax event
handler methods—.ajaxStart(), .ajaxStop(), .ajaxComplete(), .ajaxError(), .ajaxSuccess(),
.ajaxSend()—rather than within the options object for $.ajaxSetup().
You should move the error and complete properties into their own methods. :) Or, you can just put them into the $.ajax method. Whatever works best for your preferred code pattern!
I have the following working Ajax call -
$.ajax({
url: ajaxUrl,
type: sendHttpVerb,
dataType: 'json',
processData: false,
contentType: 'application/json; charset=utf-8',
complete: function () {
setTimeout($.unblockUI, 2000);
},
success: function (response, status, xml) {
clearTimeout(delayLoadingMsg);
$.unblockUI();
callbackFunction(response);
},
error: function (jqXHR, textStatus, errorThrown) {
clearTimeout(delayLoadingMsg);
$.unblockUI();
dcfForm.ajaxErrorDisplay(jqXHR, textStatus, errorThrown)
}
});
My problem is the I conditionally want to add an option when I invoke the Ajax call. For example, adding data: sendRequest before I issue the Ajax request.
My problem I cannot find an example for the syntax on how to do this without completely duplicating the entire function.
what about a ternary operation:
$.ajax({
data: condition ? sendRequest : undefined,
... the rest
});
If that's not your taste, some people seem to forget $.ajax doesn't take a long group of paramters, but an object:
var ajax = {};
ajax.success = function (data) { ... };
ajax.type = 'GET';
if (myCondition) {
ajax.data = sendRequest;
}
$.ajax(ajax);
I would like to put an ajax call within a function since I use it repeatedly in multiple locations. I want a manipulated version of the response returned. Here's what I'm trying to do (greatly simplified).
a = getAjax();
$('body').append('<div>'+a+'</div>');
function getAjax() {
$.ajax({
type: "GET",
url: 'someURL',
success: function(response) {
return response;
});
}
What's happening, however, is that the append function is running before "a" has been defined in the getAjax function. Any thoughts?
AJAX is asynchronous. This means that the code in the success handler is delayed until the request is successful, while the rest of the code continues as normal. You need to put the relevant code in the AJAX success handler:
getAjax();
function getAjax() {
$.ajax({
type: "GET",
url: 'someURL',
success: function(response) {
$(document.body).append('<div>'+response+'</div>');
});
}
Note that I have also optimised your body selector by using the native Javascript document.body rather than using the standard tag selector.
Edit Callback version
function getAjax(callback) {
$.ajax({
type: 'GET',
url: 'someURL',
success: callback
});
}
You can now do the code inline using a callback function:
getAjax(function(response) {
$(document.body).append('<div>'+response+'</div>');
});
or
getAjax(function(response) {
alert(response);
});
or whatever.
The code inside the anonymous function call will be processed when the AJAX request is complete.
There are two ways to taggle this. one is to use the success callback:
$.ajax({
type: "GET",
url: 'someURL',
success: function(response) {
AppendResponse(response);
});
the other is to set async to false http://api.jquery.com/jQuery.ajax/:
var a;
getAjax();
$('body').append('<div>'+a+'</div>');
function getAjax() {
$.ajax({
type: "GET",
url: 'someURL',
async: false,
success: function(response) {
a = response;
});
}
Important note on non async:
Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation.
Why don't you return the response to another function in the success callback. This should handle your need for different responses:
getAjax();
function getAjax() {
$.ajax({
type: "GET",
url: 'someURL',
success: function(response) {
AppendResponse(response);
});
}
function AppendResponse(response) {
$('body').append('<div>'+response+'</div>');
}
One suggestion I have is to pass a trigger to the command you want to run into the AJAX function so that it will run after AJAX has received a response-
a = getAjax();
function getAjax() {
$.ajax({
type: "GET",
url: 'someURL',
success: function(response) {
inputText(response);
});
}
inputText(someText) {
$(document.body).append('<div>'+ someText +'</div>');
}
That way you can create if statements / other alternatives to continue to use the same AJAX command for different results
You can give a handler to the function getAjax(), but if the user needs the information for the next decision then why not wait using async: false?
function getAjax(handler) {
$.ajax({
type: "GET",
url: 'someURL',
success: function(response) {
handler(response);
});
};
function callGetAjax(response) {
if(response === undefined) {
getAjax(callGetAjax);
} else {
$('body').append('<div>'+response+'</div>');
}
}