AJAX method Jquery can't return data - javascript

I can't return the value of an ajax request in Jquery. Here's my code:
function ajaxUniversal(datos, url) {
$.ajax({
url: url,
data: {
valores: datos
},
type: "POST",
dataType: "html",
success: function (data) {
console.log("Datos recibidos: "+data)
return data; //This does not returns the data
},
error: function (errorThrown) {
return false;
}
});
}
And if I add the return statement to the final:
function ajaxUniversal(datos, url) {
$.ajax({
url: url,
data: {
valores: datos
},
type: "POST",
dataType: "html",
success: function (data) {
console.log("Datos recibidos: "+data)
return data;
},
error: function (errorThrown) {
return false;
}
});
return data;//This is the statement but not works
}
And I get this error:
Uncaught ReferenceError: data is not defined
How can I return the data? Thank you. And sorry for my bad english but I speak spanish.

Ajax calls are asynchronous so you can not return value immediately from them. Instead they return a promise to return a value so what you can do is:
function ajaxUniversal(datos, url, callback) {
return $.ajax({
url: url,
data: {
valores: datos
},
type: "POST",
dataType: "html"
});
}
And call it like this:
ajaxUniversal( datos, url, callback ).then( function(data){
//manipulate data here
});

Ajax calls are asynchronous, therefore you cannot return data with them. If you want to use that data, you need to use a callback function instead.
function ajaxUniversal(datos, url, callback) {
$.ajax({
url: url,
data: {
valores: datos
},
type: "POST",
dataType: "html",
success: function (data) {
console.log("Datos recibidos: "+data)
callback(data);
},
error: function (errorThrown) {
callback(errorThrown);
}
});
}
Elsewhere...
ajaxUniversal(someData, someUrl, function(data){
// Do work with data here
console.log(data);
});

As the others have said, this is failing due to the request being asynchronous. You could either fix your code as they suggest, by handling it asynchronously, OR you can set your request to be synchronous using async: false.
function ajaxUniversal(datos, url) {
var data;
$.ajax({
url: url,
async: false, // <---- this will cause the function to wait for a response
data: {
valores: datos
},
type: "POST",
dataType: "html",
success: function (data) {
console.log("Datos recibidos: "+data)
data = data;
}
});
return data;
}

You can't return the item cause it no longer exists. try to define it first, like this:
function ajaxUniversal(datos, url) {
var returlVal;
$.ajax({
url: url,
async: false,
data: {valores: datos},
type: "POST",
dataType: "html",
success: function (data) {
console.log("Datos recibidos: "+data)
returlVal = data;
},
error: function (errorThrown) {
returlVal = false;
}
});
return returlVal;
}

Related

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)
}
});
}

Double ajax request response

I'm using ajax successives requests and I need do a callback when all the successives requests are done
function doAjaxRequest(data, id) {
// Get payment Token
return $.ajax({
type: "POST",
url: 'exemple1.php',
data: data
success: function(msg){
$.ajax({
type: "POST",
url: 'exemple2.php',
data: msg,
success: function(msgr) {
document.getElementById(id).value=msgr;
},
error:function (xhr, status, error) {
//Do something
}
});
},
error:function (xhr, status, error) {
//Do something
}
});
}
$.when(
doAjaxRequest(data, "input-1"),
doAjaxRequest(otherData, "input-2")
).done(function(a1, a2){
//Need do something when both second ajax requests (example2.php) are finished
}
With this code, the done function is call before my calls to "exemple2.php" are succeeded.
How can I wait for that?
Thanks for answering!
function doAjaxRequest(data, id) {
// Get payment Token
return new Promise(function(resolve,reject){
$.ajax({
type: "POST",
url: 'exemple1.php',
data: data
success: function(msg){
$.ajax({
type: "POST",
url: 'exemple2.php',
data: msg,
success: function(msgr) {
document.getElementById(id).value=msgr;
resolve();
},
error:function (xhr, status, error) {
//Do something
reject();
}
});
},
error:function (xhr, status, error) {
//Do something
reject();
}
});
});
}
Promise.all([
doAjaxRequest(data, "input-1"),
doAjaxRequest(otherData, "input-2")])
.then(function(values){
//Need do something when both second ajax requests (example2.php) are finished
}
Your sub ajax request is independant of the first ajax result, then the call to example2 is completely separated from the $.when() promise.abort
Just try to use the fact that jquery $.ajax return promise like object
Here my code from plnkr
// Code goes here
function doAjaxRequest(data, id) {
// Get payment Token
return $.ajax({
type: "GET",
url: 'example1.json',
data: data
}).then(function(msg, status, jqXhr) {
return $.ajax({
type: "GET",
url: 'example2.json',
data: msg
});
}).done(function(msgr) {
console.log(msgr);
return msgr;
});
}
var data = {foo:'bar'};
var otherData = {foo2:'bar2'};
$.when(
doAjaxRequest(data, "input-1"),
doAjaxRequest(otherData, "input-2")
).done(function(a1, a2) {
console.log(a1, a2);
//Need do something when both second ajax requests (example2.php) are finished
});
Attention, I replace POST by GET and use exampleX.json files for my tests on plnkr
You can test it here : https://plnkr.co/edit/5TcPMUhWJqFkxbZNCboz
Return a custom deferred object, e.g:
function doAjaxRequest(data, id) {
var d = new $.Deferred();
// Get payment Token
$.ajax({
type: "POST",
url: 'exemple1.php',
data: data
success: function(msg){
$.ajax({
type: "POST",
url: 'exemple2.php',
data: msg,
success: function(msgr) {
document.getElementById(id).value=msgr;
d.resolveWith(null, [msgr]); // or maybe d.resolveWith(null, [msg]);
},
error:function (xhr, status, error) {
//Do something
d.reject();
}
});
},
error:function (xhr, status, error) {
//Do something
d.reject();
}
});
return d;
}
Now, i'm not sure what is your expected datas passed to $.when().done() callback.

Not able to fetch data/Response on Success of Jquery.Ajax()

Hi people, I am craving myself from past 3 days and I just couldn't find the way to access json response seen on my browser
Here is my Ajax code :
$("[id*=btnModalPopup]").live("click", function () {
$("#tblCustomers tbody tr").remove();
$.ajax({
type: "POST",
url: "CallDataThroughJquery.aspx/GetLeadDetails",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert("Hi Json");
alert(data.Leadno); // **Says data.leadno is undefined**
response($.map(data.d, function (item) { // **here I am going some where wrong**
//**cannot catch response. Help!**
}))
},
failure: function (response) {
alert(response.d);
}
});
});
Please help me on this.. Thanks in Advance!
I see that your JSON is an array with an object. Try data[0].Leadno
$.ajax({
type: "POST",
url: "CallDataThroughJquery.aspx/GetLeadDetails",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert("Hi Json");
alert(data.d[0]['Leadno']); // **Says data.leadno is undefined**
response($.map(data.d, function (item) { // **here I am going some where wrong**
//**cannot catch response. Help!**
}))
},
failure: function (response) {
alert(response.d);
}
});
Try your alert with 'data.d[0]['Leadno']'.

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

How to ensure that code is run when when ajax call is finished?

I'm used to writing ruby where I get data, then I manipulate it, then I display it.
In javascript land, I'm getting some json, on success: manipulate and display.
I want to separate out my code to look like this
$("#uiElement").click(function(){
data = getData();
upDateUi(data);
})
function getData(){
var fishes;
$.ajax({
url: '/api/fishes/'+q,
dataType: 'json',
success: function(data){
return data;
//I don't want to manipulate the ui in this code;
//upDateUi(data)
},
error: function(req,error){
console.log(error);
}
})
return fishes;
}
You can separate the logic that updates the UI from the logic that retrieves the data from the server using a callback pattern:
$("#uiElement").click(function(){
var upDateUi = function(data) {
/* ... logic ... */
};
getData(upDateUi);
})
function getData(callback){
$.ajax({
url: '/api/fishes/'+q,
dataType: 'json',
success: function(data){
callback(data);
},
error: function(req,error){
console.log(error);
}
})
}
For more information on functions and scopes:
https://developer.mozilla.org/en/JavaScript/Reference/Functions_and_function_scope
For more information on how I defined the upDateUi function:
https://developer.mozilla.org/en/JavaScript/Reference/Functions_and_function_scope#Recursion
Hard to tell what your question is, but success is any function, so this:
...
success: function(data){
upDateUi(data);
},
...
Can be equivalently written as:
...
success: upDateUi,
...
Other than that, not sure what you mean by "I don't want to manipulate the ui in this code".
Define a callback, and then in the success method invoke the callback:
$("#uiElement").click(function(){
data = getData(upDateUi);
})
function getData(callback) {
$.ajax({
url: '/api/fishes/'+q,
dataType: 'json',
success: function(data){
if (callback !== undefined) {
callback(data);
}
},
error: function(req,error){
console.log(error);
}
})
}
The only way to do that is to use a synchronous fetch, which waits for the response, but its a bad idea, as no other javascript can run (and in some browsers - nothing can run) until the response is received.
If you really, really, really want it though:
$("#uiElement").click(function(){
data = getData();
upDateUi(data);
})
function getData(){
var fishes;
$.ajax({
url: '/api/fishes/'+q,
dataType: 'json',
async: false,
success: function(data){
fishes = data;
},
error: function(req,error){
console.log(error);
}
})
return fishes;
}
I'm not shure if is this what you want.
successFunction(data){
//you can do everything here
}
errorFunction(req,error){
console.log(error);
}
function getData(){
var fishes;
$.ajax({
url: '/api/fishes/'+q,
dataType: 'json',
success: successFunction,
error: errorFunction
})
return fishes;
}
This code might be good for your needs:
var myData = $.parseJSON($.ajax({
url: "./somewhere",
type: 'get|post',
async: false,
data: { what: "ever" }
}).responseText);
Then you just proceed with whatever you want to do with the results.
$("#uiElement").click(function(){
var myData = $.parseJSON($.ajax({
url: "./somewhere",
type: 'get|post',
async: false,
data: { what: "ever" }
}).responseText);
upDateUi(myData);
})
You should probably get used to event-based programming. Your code could use callbacks:
$("#uiElement").click(function(){
getData(upDateUi); // make sure upDateUi is defined, it will be passed data
})
function getData(callback){
var fishes;
$.ajax({
url: '/api/fishes/'+q,
dataType: 'json',
success: function(data){
//I don't want to manipulate the ui in this code;
//upDateUi(data)
callback(data);
},
error: function(req,error){
console.log(error);
}
})
return fishes;
}

Categories