Can't Get Correct Return Value from an Jquery Ajax Call

Can't get correct return value from an jQuery Ajax call

You are calling the asynchronous $.get() method, where its callback function will be called after your getPicsInFolder() function returns. Follow the comments in the example below:

function getPicsInFolder(folder) {
return_data = "error";
// Since the $.get() method is using the asynchronous XMLHttpRequest, it
// will not block execution, and will return immediately after it is called,
// without waiting for the server to respond.
$.get("getpics.php", function (data) {
// The code here will be executed only when the server returns
// a response to the "getpics.php" request. This may happen several
// milliseconds after $.get() is called.
return_data = data;
});

// This part will be reached before the server responds to the asynchronous
// request above. Therefore the getPicsInFolder() function returns "error".
return return_data;
}

You should consider refactoring your code in such a way that the logic to handle the JSON object is in the $.get() callback. Example:

$.get("getpics.php?folder=test", function (data) {
// Handle your JSON data in here, or call a helper function that
// can handle it:
handleMyJSON(data); // your helper function
});

jQuery AJAX get request doesn't work normally and the return value can't be displayed in the console

The result you are getting in both examples is completely normal. The reason you are getting an undefined value is because both requests are happening asynchronously. The correct place where to return something or take some action with the results you get are:

1) request.addEventListener('load', event => {} .... within the event here you can perform the action on a succesfull response.

2) with the $.ajax() call you do it within the done() promise handler.

Those are the right places to take proper action on the results. You have to modify your mindset to start using the responses from the asynchronous callbacks.

The problem there is that you are returning the result, even before the callback has some value filled in the variable.

There are new constructions this days to make asynchronous calls behave synchronously withe async-await constructions. But besides this I think you have to modify or adjust your code to react to the async results in a way it works.

AJAX method Jquery can't return data

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

});

Return value of JQuery ajax call

Unfortunately, you cannot return values to functions that wrap asynchronous callbacks. Instead, your success callback from the AJAX request will handoff the data and control to another function. I've demonstrated this concept below:

Definition for myFunction:

// I added a second parameter called "callback", which takes a function
// as a first class object
function myFunction(data, callback) {
var result = false;
$.ajax({
type: "POST",
contentType: "application/json",
dataType: "json",
url: "url",
data: data,
error: function(data){
result = false;

// invoke the callback function here
if(callback != null) {
callback(result);
}

// this would return to the error handler, which does nothing
//return false;
},
success: function(data){
result = true;

// invoke your callback function here
if(callback != null) {
callback(result);
}

// this would actually return to the success handler, which does
// nothing as it doesn't assign the value to anything
// return true;
}
});

// return result; // result would be false here still
}

callback function definition:

// this is the definition for the function that takes the data from your
// AJAX success handler
function processData(result) {

// do stuff with the result here

}

invoke your myFunction:

var data = { key: "value" }; /* some object you're passing in */

// pass in both the data as well as the processData function object
// in JavaScript, functions can be passed into parameters as arguments!
myFunction(data, processData);

jquery ajax get return value

I think what you want to do is this.

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"><\script>
<script type="text/javascript">
function showGetResult( name )
{
jQuery.ajax({
url: 'http://localhost/index.php',
type: 'get',
dataType: 'text/html',
success:function(data)
{
alert(data);
document.write(data);
}
});
}

showGetResult('test');
</script>

Variable doesn't get returned from AJAX function

You can't do that : as the call is asynchronous, the get_data function can't return the result of the ajax call.

What you should do is provide a callback to the get_data function and handle the result in the callback.

function get_data(data, destination, callback) 
{

if (lock_get == 0)
{
lock_get = 1;
$.ajax({
type: "POST",
url: destination,
async: true,
data: data,
success: function(data)
{
lock_get = 0;
if (data && callback)
{
callback(data);
}
}
});
}
};

And call it like that :

get_data(data, destination, function(test){
notice(test);
});

Returning a value from a jQuery Ajax method

In a nutshell, you can't do it the way you're trying to do it with asynchronous ajax calls.

Ajax methods usually run asynchronous. Therefore, when the ajax function call itself returns (where you have return addressList in your code), the actual ajax networking has not yet completed and the results are not yet known.

Instead, you need to rework how the flow of your code works and deal with the results of the ajax call ONLY in the success handler or in functions you call from the success handler. Only when the success handler is called has the ajax networking completed and provided a result.

In a nutshell, you can't do normal procedural programming when using asynchronous ajax calls. You have to change the way your code is structured and flows. It does complicate things, but the user experience benefits to using asynchronous ajax calls are huge (the browser doesn't lock up during a networking operation).

Here's how you could restructure your code while still keeping the AddressRetriever.find() method fairly generic using a callback function:

AddressRetriever = function() { 
AddressRetriever.prototype.find = function(zip, callback) {
$.ajax({
/* setup stuff */
success: function(response) {
var addressList = [];
var data = $.parseJSON(response.value);
for (var i = 0; i < data.length; i++) {
var city = data[i].City; // "City" column of DataTable
var state = data[i].State; // "State" column of DataTable
var address = new PostalAddress(postalCode, city, state); // This is a custom JavaScript class with simple getters, a DTO basically.
addressList.push(address);
}
callback(addressList);
}
});
}
}

$('#txtZip').blur(function() {
var retriever = new AddressRetriever();
retriever.find($(this).val(), function(addresses) {
if (addresses.length > 0) {
$('#txtCity').val(addresses[0].getCity());
$('#txtState').val(addresses[0].getState());
}
});

});

Can't evaluate true / false return from AJAX call

Reframed your code a bit. Try,

PHP:

...
...

$json = array();

if (!$resp->is_valid)
$json['result'] = true;
else
$json['result'] = false;

header('Content-Type: application/json; charset=utf-8');
echo json_encode($json);


JS:

...
...

jQuery.post(
'verify_recaptcha.php',
{
recaptcha_challenge_field: jQuery('#recaptcha_challenge_field').val(),
recaptcha_response_field: jQuery('#recaptcha_response_field').val()
})
.done(function(response){

console.log(response);

if(response.result == true)
{
// Entered captcha is correct
}
else
{
// Entered captcha is incorrect
}
});


Explanation:

1) Always return boolean true/false and not in form of string.

2) Use .done(). Won't make much difference from your code, but .done() make your ajax call code much clear.

3) Always open your console and try printing objects and see the output if it is what you are expecting.

jQuery AJAX: return value on success

You'd better change your approach to reflect an asynchronous nature of AJAX request.

Using callback function

function ChatServerQuery(data, callback) {
$.ajax({
url: 'chat/backend/',
type: 'POST',
data: data,
success: callback
});
}

Then you would use it:

ChatServerQuery(dataObject, function(data) {
// work with your data came from server
});

Using promise object

$.fn.ajax returns object implementing Promise iterface, so you can use it like this:

function ChatServerQuery(data) {
return $.ajax({
url: 'chat/backend/',
type: 'POST',
data: data
});
}

ChatServerQuery(dataObject).done(function(data) {
// work with your data came from server
});

This option offers you more flexibility.



Related Topics



Leave a reply



Submit