I have a problem with this code.
This happens:
just launch the code from console.log I get null, if I press the update button function works.
why is this happening?
how do I fix?
var urljson = "data_json.php";
var data = null;
var jqXHR = $.ajax
({
type: "GET",
url: urljson,
dataType: 'json',
success: successHandler
});
function successHandler(result) {
data = result;
}
function update(){
var jqXHR = $.ajax
({
type: "GET",
url: urljson,
dataType: 'json',
success: successHandler
});
function successHandler(result) {
data = result;
}
}
$(document).ready(function(){
console.log(data) //// null
});
document.getElementById('update').addEventListener('click', function() {
update();
console.log(data) //// Array [ Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, other 3213… ]
});
$.ajax() returns results asynchronously. Use success handler or .then() chained to $.ajax() to process response returned from request.
function update() {
var jqXHR = $.ajax({
type: "GET",
url: urljson,
dataType: "json",
success: successHandler
});
function successHandler(result) {
data = result;
// do stuff with `data` here
console.log(data);
}
}
$(document).ready(update);
jsfiddle https://jsfiddle.net/89jkzzyk/
When the page loads, update() is not getting called, thus data is null. Add your function call to $(document).ready() and it should work.
Related
I have a specific requirement with nested ajax calls. I am trying to set a globally accessible variable inside success of one ajax call and this ajax call is being invoked inside success of another ajax call. Eventually the parent success method of parent ajax call utilizes the global variable to perform further operations. The problem is that the value of global variable always remains blank. It works if I make the second ajax request as async:false; but this solution defeats the very purpose of using ajax in the first place.
Let me share a small sample code to illustrate my problem:
//global variables
var xURL = "https://sampleurl.com";
var glblID = "";
//first ajax call
$.ajax({
url: url1,
data: data1,
type: "POST",
contentType: "application/json",
success: function (msg) {
//some js code here
//second ajax call
FetchID();
//more js code here
if(glblID != "")
{
window.location.href = xURL + "?id=" + glblID
}
else
{
window.location.href = xURL;
}
}
});
function FetchID()
{
$.ajax({
url: url2,
data: data2,
type: "POST",
contentType: "application/json",
success: function (data) {
glblID = data.d;
}
});
}
As of jQuery 1.5 implement the Promise interface, giving them all
the properties, methods, and behavior of a Promise
//first ajax call
$.ajax({
url: url1,
data: data1,
type: "POST",
contentType: "application/json"
}).then(function (msg) {
//second ajax call
FetchID().then((data) => {
var glblID = data.d;
if (glblID != "") {
//do something with glblID
} else {
//do something else
}
});
});
function FetchID() {
return $.ajax({
url: url2,
data: data2,
type: "POST",
contentType: "application/json"
});
}
Why does the function call that contains an ajax request fire off before the append?
$("#range").on("click", function(){
$("#control").empty().append(.....); //why does this get executed after?
var data = 'something';
some_function_with_ajax(data);
}
function some_function_with_ajax(data){
$.ajax({
url: '/url',
type: 'POST',
data: {data: data},
success: function(resp){
// seems the append actually happens here
}
});
}
I'm trying to pass an object around in JS (with some jQuery thrown in). :)
I want to call the FlappyBarHelper.getUserPropertyCount() method once the promise.success function has run. I've tried passing this.FlappyBarHelper to :
return $.ajax({
type: "GET",
url: 'get-the-score',
flappy: this.FlappyBarHelper,
});
But that still makes flappy undefined in promise.success
My full code is:
function Rating(FlappyBarHelper) {
this.FlappyBarHelper = FlappyBarHelper;
}
Rating.prototype.attachRaty = function(property_id)
{
var promise = this.getPropertyScoreAjax(property_id);
promise.success(function (data) {
$('#'+property_id).raty({
click: function (score, evt) {
$.ajax({
type: "GET",
url: '/set-the-score',
})
.done(function (msg) {
$('#extruderTop').openMbExtruder(true);
//**** FlappyBarHelper is undefined at this point ****///
FlappyBarHelper.getUserPropertyCount('.flap');
});
}
});
});
};
Rating.prototype.getPropertyScoreAjax = function(property_id)
{
return $.ajax({
type: "GET",
url: 'get-the-score',
});
}
Read from the documentation of ($.ajax](https://api.jquery.com/jQuery.ajax/)
The this reference within all callbacks is the object in the context option passed to $.ajax in the settings; if context is not specified, this is a reference to the Ajax settings themselves.
Therefore you should pass your variable along the multiple call you are doing:
Rating.prototype.attachRaty = function(property_id){
var promise = this.getPropertyScoreAjax(property_id);
// it's best to use done
promise.done(function (data) {
$('#'+property_id).raty({
// use proxy to keep context when the click will be received
click: $.proxy(function(score, evt) {
$.ajax({
type: "GET",
url: '/set-the-score',
// propagate your variable
FlappyBarHelper: this.FlappyBarHelper
}).done(function (msg) {
$('#extruderTop').openMbExtruder(true);
// here it should be defined
this.FlappyBarHelper.getUserPropertyCount('.flap');
});
}, this);
});
});
};
Rating.prototype.getPropertyScoreAjax = function(property_id) {
return $.ajax({
type: "GET",
url: 'get-the-score',
// propagate your variable
FlappyBarHelper: this.FlappyBarHelper
});
}
You can also consider making a closure variable:
Rating.prototype.attachRaty = function(property_id){
// here is the closure variable
var helper = this.FlappyBarHelper;
var promise = this.getPropertyScoreAjax(property_id);
// it's best to use done
promise.done(function (data) {
$('#'+property_id).raty({
click: function(score, evt) {
$.ajax({
type: "GET",
url: '/set-the-score'
}).done(function (msg) {
$('#extruderTop').openMbExtruder(true);
// you can still use the defined variable: power (and danger) of closures
helper.getUserPropertyCount('.flap');
});
}, this);
});
});
};
Rating.prototype.getPropertyScoreAjax = function(property_id) {
return $.ajax({
type: "GET",
url: 'get-the-score'
});
}
I'm trying to a jquery ajax call on jsfiddle but am having an issue:
var ajax1 = function () {
return $.ajax({
type: "post",
url: "/echo/json/",
data: {
name: "thomas!"
},
dataType: 'json'
});
};
var res = ajax1();
console.log(res);
prints an entire deferred object to the console. It includes responseText which I thought perhaps is what I should try to access, but I get undefined.
console.log(res.responseText);
I tried this once before with HTML and everything seemed to work, but the JSON is failing for some reason.
ajax returns a promise object, not the result of the ajax request. You need to register a success callback to get the value returned by the ajax request
It should be
var ajax1 = function () {
return $.ajax({
type: "post",
url: "/echo/json/",
//also the format for json request is as follows
data: {
json: JSON.stringify({
name: "thomas!"
})
},
dataType: 'json'
});
};
var res = ajax1();
res.done(function (data) {
console.log(data)
})
Demo: Fiddle
You are correct, JQuery returns a Deferred object instance.
You should therefore be calling done() on the object to get the data:
var res = ajax1();
res.done(function(data) { console.log(data); });
$.ajax() returns a jqHXR instance (which implements the Deferred pattern). When you return this from the function you are returning the jqHXR object. This implements a done() method which is passed a callback function.
I am making a simple ajax request using jquery . Below is my ajax function .
var makeJqueryAjaxRequest = function(arrParam) {
var request = $.ajax({
url : arrParam['url'],
async: false,
type: arrParam['type'],
data: arrParam['data'],
dataType: arrParam['data_type'],
success: function(data) {
if(data){
return data;
}
}
});
}
here is my function calls :
var items = {
"type" : 'POST',
"url" : ajaxGetUrl,
"data" : arrParam['data'],
"data_type" : 'html'
};
var msg = makeJqueryAjaxRequest(items);
Now don't know why my makeJqueryAjaxRequest function always returns the null value. If I alert the data in the success : I'm getting the data perfect . But when I try to return it gives me the null value
You can't return value from an Asynchronous callback function.
Because success is a async callback which is called by jQuery when a ajax Event(success in this case) fires. So returning something from this functions will not have any effect as they will be returned to jQuery code.
You can use the following
var makeJqueryAjaxRequest = function(arrParam) {
var request = $.ajax({
url : arrParam['url'],
async: false,
type: arrParam['type'],
data: arrParam['data'],
dataType: arrParam['data_type']
});
return request;
}
Then do
makeJqueryAjaxRequest(items).done(function(data){
if(data){
var msg = data;
// do whatever you like with msg now
}
});
Alternative Callback Approach:
var makeJqueryAjaxRequest = function(arrParam,callback) {
var request = $.ajax({
url : arrParam['url'],
async: false,
type: arrParam['type'],
data: arrParam['data'],
dataType: arrParam['data_type'],
success: function(data) {
if(data){
callback(data);
}
}
});
}
Then use it like
makeJqueryAjaxRequest(items,function(data){
// do whatever you like with data
});
Doc on $.ajax()
Note
And with either of these approach async: false is not necessary. You can remove that. As the doc says
As of jQuery 1.8, the use of async: false is deprecated