I'm sending ajax call and getting an answer that I need from the first ajax then I want to pass my result to my nested ajax, my var (result) is null in the nested ajax/settimeout fun, can I pass it ? Am I missing something ?
$.ajax({
url: '#Url.Action("getCustomerGuidId", "Document")',
type: 'POST',
cache: false,
data: { "classNum": currentclassNum},
contentType:'json' ,
dataType:'text',
success: function (result) {
alert(result);**-> is fine - not null**.
// a or result is null when I hit the getCurrentDoc- function althought I get the data I need from getCustomerGuidId function
var a = result;-> tried to pass it to a new var..IDK.. I
thought it will help... it didn't.
setTimeout(function () {
$.ajax({
type: "GET",
url: '#Url.Action("getCurrentDoc", "Document")',
contentType:'text',
data: a,-> here it's null
success: function (data) {
}
});
}, 2000);
},
error: function (result) {
alert("fail " + result);
}
});
You can try something like this will help to pass value to nested ajax call
function test(){
var myText = 'Hello all !!';
$.get({
//used the jsonplaceholder url for testing
'url':'https://jsonplaceholder.typicode.com/posts/1',
'method':'GET',
success: function (data) {
//updating value of myText
myText = 'welcome';
$.post({
'url':'https://jsonplaceholder.typicode.com/posts',
'method':'POST',
//data.title is the return value from get request to the post request
'data':{'title':data.title},
'success':function (data) {
alert(data.title +'\n' + myText);//your code here ...
}
});
}
});
}
An old question and you've likely moved on, but there's still no accepted answer.
Your setTimeout takes an anonymous function, so you are losing your binding; if you have to use a Timeout for some reason, you need to add .bind(this) to your setTimeout call (see below)
setTimeout(function () {
$.ajax({
type: "GET",
url: '#Url.Action("getCurrentDoc", "Document")',
contentType:'text',
data: a,
success: function (data) {
}
});
}.bind(this), 2000);
At a guess you're using a Timeout because you want to ensure that your promise (i.e. the first ajax call) is resolving prior to making the nested call.
If that's your intention, you can actually scrap setTimeout completely as you have the nested call in the first ajax success call, which only runs once the promise has been resolved (providing there isn't an error; if so, jQuery would call error rather than success)
Removing setTimeout means you won't lose your binding, and a should still be result (hopefully a is an object, otherwise your second call is also going to experience issues...)
Lastly, after overcoming the binding issue you wouldn't need var a = result; you should be able to pass result directly to your nested ajax call.
Good luck!
In the nested ajax you send a as a param name, not as a param value.
So you can try the following (change param to actual param name which your server expects):
$.ajax({
url: '#Url.Action("getCustomerGuidId", "Document")',
type: 'POST',
cache: false,
data: { "classNum": currentclassNum},
dataType:'text',
success: function (result) {
setTimeout(function () {
$.ajax({
type: "GET",
url: '#Url.Action("getCurrentDoc", "Document")',
data: {param: result},
success: function (data) {
}
});
}, 2000);
},
error: function (result) {
alert("fail " + result);
}
});
Related
I'm trying to implement a function that after consulting a service brings the variables as global.
function ajax_test(str1, callback){
$.ajax({
url: '/path/service',
type: 'POST',
dataType: "json",
data: {'vars':$('form').serialize(), 'test':123},
success: function(data, status, xhr){
callback(data);
}
});
}
and I'm trying to call like this:
ajax_test("str", function(url) {
//do something with url
console.log(url);
});
Now, if I just call ajax_test() it returns an error, saying that callback is not a function.
How would be the best way to simply call the function and get the results to use global variables?
Edit:
I think a good question is: what is a good alternative to async: false? How is the best way to implement synchronous callback?
Edit 2:
For now, I'm using $.post() with $.ajaxSetup({async: false}); and it works how I expect. Still looking a way I could use with a callback.
Have to set the scope inside the success method. Adding the following should work.
function ajax_test(str1, callback){
$.ajax({
url: '/path/service',
type: 'POST',
dataType: "json",
data: {'vars':$('form').serialize(), 'test':123},
success: function(data, status, xhr){
this.callback(data);
}.bind(this)
});
}
As an argument of the ajax_test function, callback is in the scope of the ajax_test function definition and can be called anywhere there, particularly in the successcase. Note that calling ajax_test() without arguments will as expected make your code call a function that does not exist, named callback.
The following sends an Ajax request to the jsFiddle echo service (both examples of callback as anonymous or global function are given in the jsFiddle), and works properly :
function ajax_test(str1, callback){
$.ajax({
url: '/echo/json',
type: 'POST',
dataType: "json",
data: {
json: JSON.stringify({
'vars':$('form').serialize(),
'test':123
})
},
success: function(data, status, xhr){
callback(data);
}
});
}
ajax_test("unusedString", function(data){
console.log("Callback (echo from jsFiddle called), data :", data);
});
Can you check that the webservice you're calling returns successfully ? Here is the jsFiddle, I hope you can adapt it to your need :
https://jsfiddle.net/dyjjv3o0
UPDATE: similar code using an object
function ajax_test(str1) {
this.JSONFromAjax = null;
var self = this;
function callback(data) {
console.log("Hello, data :", data);
console.log("Hello, this :", this);
$("#callbackResultId").append("<p>Anonymous function : " + JSON.stringify(data) + "</p>");
this.JSONFromAjax = JSON.stringify(data);
}
$.ajax({
url: '/echo/json',
type: 'POST',
dataType: "json",
data: {
json: JSON.stringify({
'vars': $('form').serialize(),
'test': 123
})
},
success: function(data, status, xhr) {
console.log("Success ajax");
// 'self' is the object, force callback to use 'self' as 'this' internally.
// We cannot use 'this' directly here as it refers to the 'ajax' object provided by jQuery
callback.call(self, data);
}
});
}
var obj = new ajax_test("unusedString");
// Right after the creation, Ajax request did not complete
console.log("obj.JSONFromAjax", obj.JSONFromAjax);
setTimeout(function(){
// Ajax request completed, obj has been updated
console.log("obj.JSONFromAjax", obj.JSONFromAjax);
}, 2000)
You cannot expect the Ajax request to complete immediately (don't know how it behaves with async: false though, this is why you need to wait for a while before getting the actual response.
Updated jsFiddle here : http://jsfiddle.net/jjt39mg3
Hope this helps!
Given this code,
var submit = {
send:function (form_id) {
var url = $(form_id).attr("action");
$.ajax({
type: "POST",
url: url,
data: $(form_id).serialize(),
dataType: 'json',
success: function(result) {
this.ret(result.message);
},
error: function(result) {
// Some error message
}
});
},
ret:function (result) {
this.result_data = result;
},
result_data:""
};
will send a data from the form to a controller which if will return a json
$result['message'] = validation_errors();
echo json_encode($result);
I try to call this javascript object in this code,
var res = submit.send(form_id);
wherein form_id is the form id, and look for the output using
console.log(res);
In the console, it shows undefined. After searching for an explaination using google and stackoverflow itself I got the idea that,
this.ret(result.message);
is being called inside ajax which is another object, indicating that it's not part of it's method.
My problem is, how to call the method ret() inside ajax?
Is anyone can explain it to me?
There is several ways to deal with it.
One is ES5 compatible (and this is actually quite common pattern):
var submit = {
send: function (form_id) {
var url = $(form_id).attr("action");
var self = this; // << this is binded to self varialble
$.ajax({
type: "POST",
url: url,
data: $(form_id).serialize(),
dataType: 'json',
success: function(result) {
self.ret(result.message); // << replaced this to self so it has all the methods from the submit object.
},
error: function(result) {
// Some error message
}
});
},
ret:function (result) {
this.result_data = result;
},
result_data:""
};
And another is using arrow function from ES2015 plus deferred object returned by $.ajax:
var submit = {
send: function (form_id) {
var url = $(form_id).attr("action");
$.ajax({
type: "POST",
url: url,
data: $(form_id).serialize(),
dataType: 'json'
})
.then((result) => {
this.ret(result.message); // << arrow function is called in context of the parent function, so no needs to change anything.
})
.fail(function(result) {
// Some error message
});
},
ret:function (result) {
this.result_data = result;
},
result_data:""
};
Explanation: context of this in callback function will be bind to global scope not to the object's one. So you need somehow to change it.
You can actually match and mix these two methods.
You can also use bind or put success as a object method. As it mentioned in other answers. Same thing, you want to keep this to be object's context.
There is a good article about this in javascript.
You've two options.
1. The "bind()" method (recommended)
The method bind is for changing the context of a function. From the docs:
The bind() method creates a new function that, when called, has its
this keyword set to the provided value, with a given sequence of
arguments preceding any provided when the new function is called.
Here the bind will change the context of success function with the reference of this i.e. the submit.
$.ajax({
type: "POST",
url: url,
data: $(form_id).serialize(),
dataType: 'json',
success: function(result) {
this.ret(result.message);
}.bind(this), // <== bind method
error: function(result) {
// Some error message
}
});
That .bind(this) can also be written as .bind(submit);
2. Using the scope variable
Since you already have access to the submit variable, why not directly call with submit instead of this
$.ajax({
type: "POST",
url: url,
data: $(form_id).serialize(),
dataType: 'json',
success: function(result) {
submit.ret(result.message);
}.bind(this),
error: function(result) {
// Some error message
}
});
success: function(result) {
this.ret(result.message);
}
In the above block the this refers to the function you are operating in.
To use ret method you should use it submit.ret.
I have a small code fragment, that simulates this:
var submit = {
send:function (form_id) {
var self = this;
setTimeout(function()
{
console.log('send', this);
self.ret('message'); //will do
//submit.ret('message'); //will do
//this.ret('message'); this.ret is not a function
//ret('message'); ret is not defined
}, 0);
},
ret:function (result) {
console.log('ret', result, this)
this.result_data = result;
},
result_data:""
};
There you can see your possible choices to handle this.
Or use this fiddle: https://jsfiddle.net/syqjwk2q/#&togetherjs=mpwEnNDeIJ
In the submit define
self = this
And then use ret() with self: self.ret()
I have a function:
function add() {
$.ajax({
type: "POST",
url: "add.php",
async: "false", // Tried both- async: "false/true"
data: {
name: 'Test',
},
success: function(data) {
document.getElementById('id').value = data;
id = document.getElementById('id').value;
alert(id); // alerts here proper value
}
});
}
function testMyFunction() {
add();
// 'id' was set in add function.
id = document.getElementById('id').value;
alert(id); // Here does not alert value but blank(no value)
// This 'id' value is used at other place but here is issue.
}
Calling testMyFunction() function gives above mentioned issue.
What could be a issue?
$.ajax is an asynchronous call and it updates "id" field after if it is completed. Your code checks for its value in function testMyFunction() instantly after the invocation (and before success: function(data) is invoked).
JavaScript is an asynchronous language. In a nutshell, this means that your code should NEVER block: functions should either complete immediately or get called later, i.e. after some input/output operation is complete (e.g. AJAX request).
Edited: BTW, your code does not work because even with async: false the success function is called in the event loop, thus this can occur even after the code that follows synchronous AJAX. If you use async: true, the AJAX will block, but the success function will be called asynchronously in any case.
So to handle data synchronously, you have to work not with success function, but rather with an object that is returned by $.ajax() call:
var xhr = $.ajax({
type: "POST",
async: false,
url: "add.php",
data: {
name: 'Test',
},
});
alert(xhr.responseText); // Alerts result
Thus, you should never use async: false. Instead, better refactor your code to be like this:
function add(callback) {
$.ajax({
type: "POST",
url: "add.php",
data: {
name: 'Test',
},
success: callback
});
}
function testMyFunction() {
add(function(data) {
// This closure will be called AFTER the request is complete.
document.getElementById('id').value = data;
alert(data); // Alerts proper value.
});
}
Basically, this pseudo-code is WRONG:
result1 = action1();
result2 = action2(result1);
result3 = action3(result2);
...and should be written like this:
action1(function(result1) {
action2(result1, function(result2) {
alert(action3(result2));
});
});
So I have had to modify some old existing code and add another ajax event to onclick
so that it has onclick="function1(); function2();"
This was working fine on our testing environment as it is a slow VM but on our live environment it causes some issues as function1() has to finished updating some records before function2() gets called.
Is there a good way to solve this without modifying the js for function2() as this the existing code which is called by other events.
Thanks
Call function2 upon returning from function1:
function function1() {
$.ajax({
type: "POST",
url: "urlGoesHere",
data: " ",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
//call function2
},
error:
});
}
Or wrap them in a function that calls both 1 and 2.
You need to use always callback of ajax method, check out always callback of $.ajax() method http://api.jquery.com/jquery.ajax/.
The callback given to opiton is executed when the ajax request finishes. Here is a suggestion :
function function1() {
var jqxhr = $.ajax({
type: "POST",
url: "/some/page",
data: " ",
dataType: "dataType",
}).always(function (jqXHR, textStatus) {
if (textStatus == 'success') {
function2();
} else {
errorCallback(jqXHR);
}
});
}
I'm assuming you use Prototype JS and AJAX because of your tags. You should use a callback function:
function function1(callback) {
new Ajax.Request('http://www.google.nl', {
onSuccess: function(response) {
callback();
}
});
}
function function2(callback) {
new Ajax.Request('http://www.google.nl', {
onSuccess: function(response) {
callback();
}
});
}
function both() {
function1(function() {
function2();
});
}
Then use onclick="both();" on your html element.
Example: http://jsfiddle.net/EzU4p/
Ajax has async property which can be set false. This way, you can wait for that function to complete it's call and set some value. It actually defeats the purpose of AJAX but it may save your day.
I recently had similar issues and somehow calling function2 after completing function1 worked perfectly. My initial efforts to call function2 on function1 success didn't work.
$.ajax({
type: "POST",
url: "default.aspx/function1",
data: "",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false, // to make function Sync
success: function (msg) {
var $data = msg.d;
if ($data == 1)
{
isSuccess = 'yes'
}
},
error: function () {
alert('Error in function1');
}
});
// END OF AJAX
if (isSuccess == 'yes') {
// Call function 2
}
My function looks like that
var mail_ntfy=$("#nav_mail"), question_ntfy=$("#nav_question"), users_ntfy=$("#nav_users");
function CheckAll(){
var data=checkFor("m,q,u");
if(mail_ntfy.attr("data-number")!=data.m_count && data.m_count!=0)
mail_ntfy.attr("data-number", data.m_count);
if(question_ntfy.attr("data-number")!=data.q_count && data.q_count!=0)
question_ntfy.attr("data-number", data.q_count);
if(users_ntfy.attr("data-number")!=data.u_count && data.u_count!=0)
users_ntfy.attr("data-number", data.u-count);
showNotes(data.msg);
chngTitle(data.msg);
}
$(document).ready(function () {
setInterval(CheckAll(), 10000);
})
function checkFor(param){
$.ajax({
url: "core/notifications.php",
type: "POST",
dataType: "json",
data: {
chk:param
},
success: function (data) {
if(data.status!="error") {
console.log(data);
return data;
}
}
});
}
I got 2 questions:
1) I see that, checkFor function returns result (console.log shows result) but still getting data is undefined error message on line if(mail_ntfy.attr("data-number")!=data.m_count && data.m_count!=0). What am I missing?
2) I want to execute, CheckAll in every 10 seconds. But it doesn't start more than 1 time. why setinterval doesn't work properly?
checkFor() does not return any result. The console.log() statement is in the anonymous function attached to the success handler of your AJAX request; its return does not return from the checkFor() function.
If you want checkFor to return the data the AJAX call has to be synchronous. This is, however, bad Javascript practice (for example, it will hang the execution of scripts on the page until the request is complete). Unfortunately this whole design is flawed, but you could use this code if you REALLY have to:
function checkFor(param){
var result;
$.ajax({
url: "core/notifications.php",
type: "POST",
async: false,
dataType: "json",
data: {
chk:param
},
success: function (data) {
if(data.status!="error") {
console.log(data);
result = data;
}
}
});
return result;
}
You can't return data from success callback. Instead you can call CheckAll from success callback like this
success: function (data) {
if(data.status!="error") {
console.log(data);
//return data;
CheckAll(data);
}
}
To run checkFor instead every 10 seconds you can set the timer from within success callback too. That will call the checkFor 10 seconds after every successful ajax request. Using setInterval can end up with multiple simultaneous ajax calls.
success: function (data) {
if(data.status!="error") {
console.log(data);
//return data;
CheckAll(data);
setTimeout(checkFor,10000);
}
}
And your updated checkAll would be like
function CheckAll(data){
if(mail_ntfy.attr("data-number")!=data.m_count && data.m_count!=0)
mail_ntfy.attr("data-number", data.m_count);
if(question_ntfy.attr("data-number")!=data.q_count && data.q_count!=0)
question_ntfy.attr("data-number", data.q_count);
if(users_ntfy.attr("data-number")!=data.u_count && data.u_count!=0)
users_ntfy.attr("data-number", data.u-count);
showNotes(data.msg);
chngTitle(data.msg);
}
You are calling Ajax asynchronously therefore the system wont wait for ajax to end in order to continue proccessing. You'll have to add
async:false,
To your ajax call, like this:
function checkFor(param){
$.ajax({
url: "core/notifications.php",
type: "POST",
async:false,
dataType: "json",
data: {
chk:param
},
success: function (data) {
if(data.status!="error") {
console.log(data);
var ret=data;
}
}
});
return ret;
}
Hope it helps!