Ajax callback to check variables as global - javascript

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!

Related

How to pass a variable from ajax to nested ajax

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

How to transform $.post to $.ajax?

I have this $.post peace of code:
$.post("../admin-login",
{
dataName:JSON.stringify({
username:uname,
password:pass,
})
}, function(data,status){
console.log("Data:"+data);
answer = data;
}
);
and I wont to transform it to $.ajax. On the servlet side I am demanding request.getParamter("dataName") but I do not know how to write data: section in $.ajax so that I can get parameters like that(request.getParamter("dataName"))? Also, it seems to be problem with this type of code, I am asuming cause of async, that I cannot do this:
var answer="";
function(data,status){
console.log("Data:"+data);
answer = data;
}
And that answer is keeping empty(""), even though in console is written in deed "true" or "false" as my server answers. What is this about?
Thanks in advance.
I found out that problem is in the click() event. Ajax finishes when click() finishes, so I am not able to get data before event is done. What is bad in that is that I cannot fetch data because it is finished. Does anyone know how to solve this?
$.post("../admin-login",
{
dataName:JSON.stringify({
username:uname,
password:pass,
})
}, function(data,status){
console.log("Data:"+data);
answer = data;
}
);
becomes
function getResult(data) {
// do something with data
// you can result = data here
return data;
}
$.ajax({
url: "../admin-login",
type: 'post',
contentType: "application/x-www-form-urlencoded",
data: {
dataName:JSON.stringify({
username:uname,
password:pass,
})
},
success: function (data, status) {
getResult(data);
console.log(data);
console.log(status);
},
error: function (xhr, desc, err) {
console.log(xhr);
}
});
You need to see how the information os arriving to your servlet as query parameter or payload.
See this HttpServletRequest get JSON POST data
You could try structuring your AJAX request like the below:
var dataName = username:uname, password:pass;
$.ajax({
url: "../admin-login",
data: JSON.stringify(dataName),
type: "POST",
cache: false,
dataType: "json"
}).done(function(data, status) {
console.log("Data:"+data);
answer = data;
});

Ajax: error callback not firing

I'm having trouble getting the error callback getting called when I pass the error function as an object parameter in a function. However, when I declare it within the ajax code it works.
var ajaxSettings = new Object();
ajaxSettings.error = function(request, status, error){ console.log('bad failure');};
ajaxSettings.success = function(result) { console.log('good success');};
uploadFile(contents, ajaxSettings)
function uploadFile(contents, settings) {
$.ajax({
url: uri,
type: "PUT",
data: contents,
processData: false,
dataType: "json",
success: settings.success,
error: settings.error
});
}
In this case the error callback doesn't get fired. However if I write the error function declaration in the ajax code it works.
function uploadFile (contents, settings) {
$.ajax({
url: uri,
type: "PUT",
data: contents,
processData: false,
dataType: "json",
success: settings.success,
error: function(request, status, error) { console.log('bad failure'); },
});
}
I also tried making success: settings.error and it will call that function when it succeeds. What is the reason the error callback is not getting called?
I created a fiddle using your code check it Fiddle
You should initialize the ajaxSettings before use it
Try to declare your callbacks like below:
var ajaxSettings = {}
ajaxSettings.error = function(request, status, error){ console.log('bad failure');};
ajaxSettings.success = function(result) { console.log('good success');};
... because they are probably not visible in "uploadFile" function scope.

jQuery cross-domain request returns 'undefined'

After reading various examples on stackoverflow I wrote this function :
function showGetResult(crossDomainUrl) {
$.ajax({
url: crossDomainUrl,
type : 'GET',
crossDomain: true,
success: function (data) {
debug(data);
return data;
}
});
}
and called it using this
alert(showGetResult(crossDomainUrl));
But all I get is 'undefined', this is being used in a web-browser extension inside a content-script.
This is because the Ajax request runs asynchronously. The return data doesn't do anything. You could change it to (updated to reflect the request in the comments to be able to download a script):
function showGetResult(crossDomainUrl) {
return $.ajax({
url: crossDomainUrl,
type : 'GET',
dataType: 'script',
crossDomain: true
});
}
showGetResult('http://code.jquery.com/ui/1.10.3/jquery-ui.js')
.done(function(data) {
alert("success: " + data);
})
.fail(function(jqXHR, textStatus, ex) {
alert("failed: " + textStatus);
});
For the call actually to work cross-domain, you will need to use jsonp or script. Read this wiki for more information about Same-origin policy. Refer to this answer for more information about using jsonp.
The code above will inject the downloaded jscript in the dom and execute it.
The $.ajax() set up the query, and return immediately, so the function returns before the request is completed. Specify a function to call on completion of the query using success.
function showGetResult(crossDomainUrl) {
$.ajax({
url: crossDomainUrl,
type : 'GET',
crossDomain: true,
success: showData
});
}
function showData(data){
debug(data);
return data;
}
showGetResult(crossDomainUrl);
see http://jsfiddle.net/5J66u/8/ - (updated to specify jsonp and a better URL for it)

How to initiate a function when $ajax() is called?

In jquery that is.
I would like something that works as the success-pararameter, but that is run when the function is called, rather than once I get the response.
sample (oajax is an extension of ajax for open auth)
$.oajax({
url: url,
jso_provider: "facebook", // Will match the config identifier
jso_scopes: false, // List of scopes (OPTIONAL)
dataType: 'json',
success: function(data) {
fbposts=data.data
//a bunch of code irellevant for the question
},//success done
error: function() {
console.log("ERROR Custom callback()");
}
})
};
Are you looking for .ajaxSend() ?
Attach a function to be executed before an Ajax request is sent.
This function (and .ajaxComplete et al) allow you to register callback functions that are called for the different phases of every AJAX request.
In a normal ajax function, you pass it as beforeSend:
$.ajax({
url: url,
dataType: 'json',
beforeSend: function(jqXHR, status){
// CODE HERE
},
success: function(data) {
fbposts=data.data
},
error: function() {
console.log("ERROR Custom callback()");
}
})
};
You'll have to check if oajax have this event too, but it probably do

Categories