Making AJAX Call For Use In Multiple Methods [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I have to make numerous AJAX calls and want to set up a simple method to handle this. I created the following
function testingAjax(url) {
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: url,
data: "{}",
dataType: "json",
success: function(data) {
//alert(data);
return data;
},
error: function(err) {
alert('error')
}
});
};
When I call testingAjax from another method, I get an Undefined error, yet when I alert from within testingAjax it is correct.
function testingCall(){
var data = testingAjax(url);
alert(data);
}
Basically, I want to return the data from the AJAX call, and parse it elsewhere. What am I doing wrong?

You'll want to add a callback param (which is a function) and pass it to success in place of what you already have.
function testingAjax(url, cb) {
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: url,
data: "{}",
dataType: "json",
success: cb,
error: function(err) {
alert('error')
}
});
};
To use it:
testingAjax('myurl', function(data) {
console.log(data);
});
This will take the value of the success callback and immediately pass it as an argument to your custom callback, which will allow you access to data.

Related

How to access data from a function that return an ajax get json response? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
I have a function that return json data using ajax:
function validateTagRequest(fileName) {
$.ajax({
type: "GET",
dataType: "json",
url: "/tags/find-tag/"+fileName.tag,
success: function(data){
console.log(data);
return data;
}
});
};
console.log(data) show exactly what I need.
But then I call the function:
var response = validateTagRequest(fileName);
useResponse(response); // this don't work, response = undefined
console.log(response);
console.log(response) return undefined
How can I handle the asynchronous of js to execute this code in order?
try a callback
function validateTagRequest(fileName, cb) {
$.ajax({
type: "GET",
dataType: "json",
url: "/tags/find-tag/"+fileName.tag,
success: function(data){
console.log(data);
cb(data);
}
});
}
validateTagRequest(fileName, function(response){
useResponse(response);
console.log(response);
});

JSON AJAX - Return empty object [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I'm using an AJAX call in a function to retrieve some data from the server, in this way:
getPolicies: function() {
$.ajax({
async: false, // wait for response
type: "GET",
url: "http://localhost:8080/getPolicies",
contentType: "application/json",
dataType: "json",
success: function(jsonList) {
for(var i in jsonList) {
console.dir(jsonList[i].policyName);
}
return jsonList;
},
failure: function(err) {console.log("Error");}
});
}
I correctly get the JSON array:
[
{
"policyName": "policy1"
},
{
"policyName": "policy2"
},
{
"policyName": "policy3"
}
]
This JSON array is returned by the function.
But when I call the function getPolicies() I only get an empty JSON object {}. Specifically, if i try
var policies = getPolicies();
console.log(policies[1].policyName);
I get this:
Uncaught TypeError: Cannot read property 'policyName' of undefined
So, how is possible that even if I correctly get the JSON array, the function returns an empty object?!
Thanks...
Even though the AJAX request is synchronous *), the return statement still returns only from the success handler. Try something like this:
getPolicies: function() {
// Declare variable here
var resultList = null;
$.ajax({
async: false, // wait for response
type: "GET",
url: "http://localhost:8080/getPolicies",
contentType: "application/json",
dataType: "json",
success: function(jsonList) {
for(var i in jsonList) {
console.dir(jsonList[i].policyName);
}
// Set the variable in the scope of getPolicies.
resultList = jsonList;
},
failure: function(err) {console.log("Error");}
});
// This one actually returns getPolicies
return resultList;
}
But in general, it's regarded bad practice to make AJAX calls synchronous. Instead, you can better call the necessary functionality from the success handler. That can also be another function. For instance, you can declare
function processPolicies(policies)
{
console.log(policies[1].policyName);
}
And your call handler can look like this (:
$.ajax({
async: true, // just let it run,
type: "GET",
url: "http://localhost:8080/getPolicies",
contentType: "application/json",
dataType: "json",
success: function(jsonList) {
processPolicies(jsonList);
},
...
*) The first A even stands for Asynchronous. But on the other hand, the X stands for XML, so what you're doing here should actually be called JaJ rather than AJAX. ;)

Can't pass data to function (jQuery) [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I'm trying to successfully pass the result to another function and it's simply returning an undefined value:
function tagCustomer(email, tags) {
var o = new Object();
o.tags = tags;
o.email = email;
o.current_tags = getCustomerTags(email);
o.new_tags = tags;
console.log(o);
return true;
}
function returnData( data ) {
return data;
}
function getCustomerTags(email) {
$.ajax({
url: "xxx.io/index.php",
type: "POST",
dataType: "json",
data: {email: email, "action": "getCustomerTags"},
contentType: "application/x-www-form-urlencoded; charset=utf-8",
success: function (data) {
returnData( data );
return data;
}
});
}
o.current_tags should get the result of getCustomerTags.
You should change getCustomerTags to something like this since it makes an asynchronous request:
function getCustomerTags(email) {
return $.ajax({
url: "xxx.io/index.php",
type: "POST",
dataType: "json",
data: {
email: email,
action: "getCustomerTags"
},
contentType: "application/x-www-form-urlencoded; charset=utf-8",
});
};
and then use it like this:
getCustomerTags(email).done(function(data) {
console.log(data)
});
You normal approach will not work here, because you try return before response comes back from server. Instead you use callback function or promises.
You are dependent on ajax response to return data from the function. But ajax by default is asynchronous and does not wait for the server response. therefore your function does not return anything.
Try this (It's not good for UI, but with your current code it will work, also, look at the "BETTER PRACTICE" on the bottom of my answer):
function getCustomerTags(email) {
var result = null;
$.ajax({
url: "xxx.io/index.php",
type: "POST",
dataType: "json",
async: false,
data: {
email: email,
"action": "getCustomerTags"
},
contentType: "application/x-www-form-urlencoded; charset=utf-8",
success: function (data) {
result = data;
}
});
return result;
}
The reason your code didn't work, is that the $.ajax success function is returning the data var, but getCustomerTags isn't returning anything. Also, pay attention to the "async: false", because if you use it as async, the function will return null because it will return before the ajax completes.
BETTER PRACTICE
The ajax function has a callback (success), USE IT!
design your code not as a method waiting for the ajax request result, but as an ajax request that does something upon it's completion!
EXAMPLE
function tagCustomer(email, tags, data) {
var o = new Object();
o.tags = tags;
o.email = email;
o.current_tags = data
o.new_tags = tags;
console.log(o);
return true;
}
function getCustomerTags(email, tags) {
$.ajax({
url: "xxx.io/index.php",
type: "POST",
dataType: "json",
data: {email: email, "action": "getCustomerTags"},
contentType: "application/x-www-form-urlencoded; charset=utf-8",
success: function (data) {
tagCustomer(email, tags, data);
}
});
}
If you have any further questions, don't hesitate to comment.

jQuery Wait until async ajax calls are finished

Hi I have 2 ajax calls in my script, I need them run asnyc to spare time, but I need the second to wait until the first is finished.
$.ajax({
type: "POST",
url: "getText.asmx/ws_getText",
data: parO1,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d.data);
},
error: function () {
chyba("chyba v požadavku", "df");
}
});
if (parO2.length > 0) {
$.ajax({
type: "POST",
url: "getText.asmx/ws_getText",
data: parO2,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
/*WAIT UNTIL THE FIRST CALL IS FINISHED AND THAN DO SOMETHING*/
},
error: function () {
chyba("chyba v požadavku", "df");
}
});
}
So any ideas? Thanks
If using jQuery 1.5+, you can use jQuery.when() to accomplish this. Something like (shortened the ajax calls for brevity, just pass the objects as you're doing above)
$.when($.ajax("getText.asmx/ws_getText"),
$.ajax("getText.asmx/ws_getText")).done(function(a1, a2){
// a1 and a2 are arguments resolved for the
// first and second ajax requests, respectively
var jqXHR = a1[2]; // arguments are [ "success", statusText, jqXHR ]
});
You don't know in which order they will return so if you were rolling this by hand, you would need to check the state of the other request and wait until it has returned.
You need to wire up the second call to be contained within the callback of your first ajax call. Like so:
success: function(msg)
{
alert(msg.d.data);
if(par02.length > 0)
{
// Your 2nd ajax call
}
},
Since JavaScript doesnt run in multiple threads on the client, you can't block the thread until certain conditions are met.
Using jquery
$.ajax({
type: "POST",
async:false, // ** CHANGED **
url: "getText.asmx/ws_getText",
data: parO1,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d.data);
}
, error: function () {
chyba("chyba v požadavku", "df");
}
});
Here is another answer on running dual ajax requests. Like Tejs, the user makes an ajax call within the success method...
The poster states You're better off having the success method launch a new ajax request.."
Having two $.ajax() calls in one script

Return value from function with ajax call [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Synchronous calls with jquery
I am trying to return a value from a function that contains an ajax call (please see code below).
The returnValue variable is undefined at the alert and when it returns. Can anyone help please?
function getLightboxImages(){
var returnValue;
jQuery.ajax({
url: "http://test.domain.com/WebService.svc/GetAllI",
data: { id: "2", hash:"MaD01" },
async: false,
dataType: "jsonp",
success: function (result) {
returnValue = result
}
});
alert(returnValue);
return returnValue;
}
The alert would have to be placed in the success function, as that is called when ajax returns. What you have above will send the request and then try to alert the returned value before the request is completed.
try this code, for JSONP you have to use callback function rather than success method.
$.ajax({
url: 'http://test.domain.com/WebService.svc/GetAllI',
type: 'GET',
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
jsonp: "callback",
jsonpCallback: "jsonpCallbackfunction",
error: function () {
alert("Error in Jsonp");
}
});
function jsonpCallbackfunction(responseData) {
alert(responseData);
}
http://cmsnsoftware.blogspot.com/2012/02/how-to-use-cross-domain-ajax-request.html#0
function getLightboxImages(){
var returnValue;
jQuery.ajax({
url: "http://test.domain.com/WebService.svc/GetAllI",
data: { id: "2", hash:"MaD01" },
async: false,
dataType: "jsonp",
success: function (result) {
returnValue = result
}
});
alert(JSON.stringify(returnValue));
return returnValue;
}
Cross-domain requests can only be async, as cross-domain requests rely on a dynamic script tag, which can never be synchronous and must use datatype json and the GET method.
For same domain requests, try stringifying json objects before alerting, like above!
You can't make synchronous JSONP requests.
Use a callback instead of return:
function getLightboxImages(callback) {
jQuery.ajax({
url: "http://test.domain.com/WebService.svc/GetAllI",
data: { id: "2", hash:"MaD01" },
dataType: "jsonp",
success: function (result) {
callback(result);
}
});
}
Usage:
getLightboxImages(function(result){
alert(result);
});

Categories

Resources