JS Ajax function not setting variable value - javascript

I have a simple ajax function
function get_country(request_term) {
var country_list = '';
$.ajax({
url : "activity/get_country",
type : "POST",
cache : false,
data : {
request_term : request_term
},
success : function(data) {
if(data != '') {
country_list = $.parseJSON(data);
alert(country_list); ----> Got value here
}
}
});
alert(country_list); ----> Not getting value here
return country_list;
}
the problem is, i'm getting the data in the success function, but unable to return it from the main function.

Because ajax is asynchronous, you can't know when the success function will complete (or if it will ever complete). Therefore any code that requires the result of the ajax call must depend on the ajax callback too.
jQuery makes it very easy to bind additional callbacks.
return $.ajax({ /* rest of your code */
get_country(request_term).done(function (data) {
//are you sure JSON isn't returned already?
country_list = $.parseJSON(data);
});

You can do it by making async as false. But it is not a recommented way.
This code will return country_list
function get_country(request_term) {
var country_list = '';
$.ajax({
url : "activity/get_country",
type : "POST",
cache : false,
async : false,
data : {
request_term : request_term
},
success : function(data) {
if(data != '') {
country_list = $.parseJSON(data);
alert(country_list);
}
}
});
alert(country_list);
return country_list;
}

Related

How to create callback function using Ajax?

I am working on the jquery to call a function to get the return value that I want to store for the variable email_number when I refresh on a page.
When I try this:
function get_emailno(emailid, mailfolder) {
$.ajax({
url: 'getemailnumber.php',
type: 'POST',
data : {
emailid: emailid,
mailfolder: mailfolder
},
success: function(data)
{
email_number = data;
}
});
return email_number;
}
I will get the return value as 6 as only when I use alert(email_number) after the email_number = data;, but I am unable to get the value outside of a function.
Here is the full code:
var email_number = '';
// check if page refreshed or reloaded
if (performance.navigation.type == 1) {
var hash = window.location.hash;
var mailfolder = hash.split('/')[0].replace('#', '');
var emailid = 'SUJmaWg4RTFRQkViS1RlUzV3K1NPdz09';
get_emailno(emailid, mailfolder);
}
function get_emailno(emailid, mailfolder) {
$.ajax({
url: 'getemailnumber.php',
type: 'POST',
data : {
emailid: emailid,
mailfolder: mailfolder
},
success: function(data)
{
email_number = data;
}
});
return email_number;
}
However, I have been researching and it stated that I would need to use callback via ajax but I have got no idea how to do this.
I have tried this and I still don't get a return value outside of the get_emailno function.
$.ajax({
url: 'getemailnumber.php',
type: 'POST',
async: true,
data : {
emailid: emailid,
mailfolder: mailfolder
},
success: function(data)
{
email_number = data;
}
});
I am getting frustrated as I am unable to find the solution so I need your help with this. What I am trying to do is I want to call on a get_emailno function to get the return value to store in the email_number variable.
Can you please show me an example how I could use a callback function on ajax to get the return value where I can be able to store the value in the email_number variable?
Thank you.
From the jquery documentation, the $.ajax() method returns a jqXHR object (this reads fully as jquery XMLHttpRequest object).
When you return data from the server in another function like this
function get_emailno(emailid, mailfolder) {
$.ajax({
// ajax settings
});
return email_number;
}
Note that $.ajax ({...}) call is asynchronous. Hence, the code within it doesn't necessarily execute before the last return statement. In other words, the $.ajax () call is deferred to execute at some time in the future, while the return statement executes immediately.
Consequently, jquery specifies that you handle (or respond to) the execution of ajax requests using callbacks and not return statements.
There are two ways you can define callbacks.
1. Define them within the jquery ajax request settings like this:
$.ajax({
// other ajax settings
success: function(data) {},
error: function() {},
complete: function() {},
});
2. Or chain the callbacks to the returned jqXHR object like this:
$.ajax({
// other ajax settings
}).done(function(data) {}).fail(function() {}).always(function() {});
The two methods are equivalent. success: is equivalent to done(), error: is equivalent to fail() and complete: is equivalent to always().
On when it is appropriate to use which function: use success: to handle the case where the returned data is what you expect; use error: if something went wrong during the request and finally use complete: when the request is finished (regardless of whether it was successful or not).
With this knowledge, you can better write your code to catch the data returned from the server at the right time.
var email_number = '';
// check if page refreshed or reloaded
if (performance.navigation.type == 1) {
var hash = window.location.hash;
var mailfolder = hash.split('/')[0].replace('#', '');
var emailid = 'SUJmaWg4RTFRQkViS1RlUzV3K1NPdz09';
get_emailno(emailid, mailfolder);
}
function get_emailno(emailid, mailfolder) {
$.ajax({
url: 'getemailnumber.php',
type: 'POST',
data : {
emailid: emailid,
mailfolder: mailfolder
},
success: function(data)
{
// sufficient to get returned data
email_number = data;
// use email_number here
alert(email_number); // alert it
console.log(email_number); // or log it
$('body').html(email_number); // or append to DOM
}
});
}

AJAX is not receiving data on success, it shows the result as "undefined"

This is jQuery code snippet is not getting valid data through AJAX and keeps updating data in divs as undefined. I don't know what the problem is.
function success(data) {
alert(data.amount);
$('#summary').html(data.count + "|" + data.amount);
};
$(document).ready(function () {
$("#button1").click(function (evt) {
evt.preventDefault();
var $form = $("#form1");
$.ajax({
type: $form.prop('method'),
url: $form.prop('action'),
data: $form.serialize() ,
datatype: "json",
tradition: true,
success: function(data) {
success(data);
}
});
});
});
If I modify following success function to simply load a new page that shows the correct results that Action returns
function success(data) {
$('#summary').html(data);
};
This is the controller action code snippet that receives the form fields data (id and quantity) from the view and returns count and amount:
public JsonResult AddtoCartDt(string id,string quantity)
{
int id2 = int.Parse(id);
Product pro = Data.Products.Single(c => c.Id == id2);
var cart = ShoppingCart_BusinessLayer.GetCart(this.HttpContext);
int l = int.Parse(quantity);
for (int i = 0; i < l; i++)
{
cart.AddToCart(pro);
}
var Cart = ShoppingCart_BusinessLayer.GetCart(this.HttpContext);
cartSummary summ = new cartSummary()
{
amount = Cart.GetTotal(),
count = Cart.GetCount()
};
return Json(summ, JsonRequestBehavior.AllowGet);
}
Your code looks fine, but you should add some debug statements to check the response.
For starters, you could pass the success method directly as your ajax success handler, and add an error handler to log out any error:
$.ajax({
type: $form.prop('method'),
url: $form.prop('action'),
data: $form.serialize() ,
datatype: "json",
traditional: true,
// no need for the function()...
success: success,
error: console.log
});
// Alternatively, you could chain it:
$.ajax(/*...*/).done(success).fail(console.log);
That will call pass the JSON response as your success method parameter.
Then, try to add a console.log() statement to debug the response in the console:
function success(data) {
console.log(data);
$('#summary').html(data.count + "|" + data.amount);
};
Edit
Check the tradition parameters in your ajax call. In the doc it's called traditional.
Also, check the route name and http method in your controler.
You may want to add something like this in your controller:
[Route("~/myroute"), HttpPost]
public JsonResult AddtoCartDt(string id,string quantity)
{
/*
*/
}

AJAX call within Javascript class (prototype function)

I am implementing a Javascript class which I am having trouble getting to work.
After I initialize an instance of the class, I then call a method of that class which makes an AJAX request. The data that is returned on 'success' of the AJAX function is then needed to be set to the a property of that instance. When I output the this.results variable later in my code, it is empty when it shouldn't be. Here is my code:
//Individual Member Class
function GetReports(options) {
this.options = options;
this.results = {};
}
GetReports.prototype.getResults = function() {
jQuery.ajax({
type : 'post',
dataType : 'json',
url : 'reporting/getStaffMemberReports',
async : false,
data : options,
success : function(data) {
this.results = data;
setResult(this.results);
}
});
}
GetReports.prototype.returnResults = function(type) {
if(type === "JSON") {
JSON.stringify(this.results);
} else if (type === "serialize") {
this.results.serialize();
}
return this.results;
};
GetReports.prototype.setResult = function(data) {
this.results = data;
};
And my code which creates an instance of the 'class':
var jsonString = <?php echo json_encode($JSONallocatedStaffMembers); ?>;
options = {
all : true,
members : JSON.parse(jsonString),
type : 'highperform'
};
var all = new GetReports(options);
all.getResults();
var results = all.returnResults("JSON");
console.log(results);
Now, as the AJAX call is asynchronous, I was thinking this may be the issue? I have tried putting 'async : false,' in but that doesn't help.
Can anyone see where I am going wrong?
There is one thing to be fixed here.
The this
inside ajax callback refers to ajax object, and not your
GetReport instance. You have to declare a var on getResults and point
it to this before make the ajax.
GetReports.prototype.getResults = function() {
var self = this;
jQuery.ajax({
type : 'post',
dataType : 'json',
url : 'reporting/getStaffMemberReports',
async : false,
data : options,
success : function(data) {
self.results = data;
setResult(self.results);
};
});
}

Object reference error after ajax success operation - jquery

In above ajax call the object jData returns null .. but returns the object successfully if displayed with success:
var jData = null;
function x() {
$.ajax({
url : 'http://...",
success : function(data) {
jData = data;
alert(jData); // displays the object
}
});
return jData; //returns null ??
};
$.ajax() is asynchronous. You have to work with jData directly in success callback
var jData = null;
function x() {
$.ajax({
url : "http://...",
success : function(data) {
jData = data;
alert(jData); // displays the object
//do stuff here
}
});
}
Your are getting the data out of the scope of your block , that for very reason it not occuring ,, return your jdata inside the success operation
Ajax is asynchronous, you need to return jdata from inside the success callback. Otherwise when you return jdata, the ajax call has not yet returned and jdata has not been assigned a value.

How do I return a value from the success and error handlers in jQuery.ajax() to the parent method?

Ok, for sake of argument, let's say that the AJAX call MUST BE ASYNCHRONOUS.
Basically, I have a jQuery AJAX call, and I want the success and error handlers to return a value to the parent method:
The code below does not work, since the AJAX call is asynchronous. Thus, the return value at the bottom of the function is returned before the repsonse is received:
var isValid = false;
$.ajax({
type: "POST",
url: myurl,
dataType: "JSON",
data: $myData,
async: true,
success: function(data) {
isValid = true;
},
error: function() {
isValid = false;
}
});
return isValid;
So, is there some way to pass a value BACK to the calling method for asynchronous AJAX calls?
Here's a solution I have come up with that answers my question.... (Thanks to #Rodaine for giving me the idea!)
In the calling method, I am specifying a callback function. Here is the plug-in that contains the AJAX call:
function ajaxCall(options) {
var url = options["url"] === undefined ? "" : options["url"];
var addLink = options["addLink"] === undefined ? "" : options["addLink"];
var $form = $(this).closest("form");
var $formParamsString = $form.serialize();
var aSuccess = [];
var aError = [];
if ($.isFunction(options["success"]))
aSuccess.push(options["success"]);
if ($.isFunction(options["error"]))
aError.push(options["error"]);
$.ajax({
type: "POST",
url: url,
dataType: "JSON",
data: $formParamsString,
async: true, // Asynchronous to allow for loading image
success: aSuccess,
error: aError
});
}
Now, when I call this function, I can specify a callback in the options Object:
ajaxCall({
url: "myWebService.cfm",
success: function() {
alert("We did it!");
},
error: function() {
alert("Try again, fool!");
}
});
The line
Return isValid;
Is going to execute before the call completes, because it's asynchronous.
Use
async: false,
You can't do this because isValid would be always false.
If you need to do something following success/failure you should do:
success: function(data) {
isValid = true;
otherFunction(isValid);
},
error: function() {
isValid = false;
otherFunction(isValid);
}
In this way you could handle the different cases
Use synchronouse ajax call
set async to false.

Categories

Resources