assigning a value from a ajax request in jquery - javascript

I have the following piece of jquery code
var test = "test";
$.ajax({
url: root + "/servletPath",
type: "GET",
success: function (text) {
alert(text); // returns the right value
test = text;
},
error: function () {
}
});
// prints "test" and not the value that should be assigned in the success function
alert(test)

You're alerting the variable test before the value has been assigned. $.ajax is asynchronous by default.
Possible Solution:
var test = "test";
$.ajax({
url: root + "/servletPath",
type: "GET",
success: function (text) {
test = text;
alertTest();
},
error: function () {
}
});
function alertTest(){
alert(test);
};
You could also set the async property to false on the $.ajax method, to run the code synchronously.

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

Javascript JQuery On Select Change Get Result and pass to outside

I have the following code which works on the event that a select box is changed.
When it changes, the ajax call will pass the results to the variable result.
My problem is that I cannot get that data outside this function.
The code:
$('#myselect').on('change', function() {
$.ajax({
url: 'myurl'+this.value,
method: 'GET',
success: function(result) {
console.log(result); //Just checking it's there
external = result;
}
});
});
console.log(external); //Returning Undefined
I need external to be available here outside the function above.
How do I do this?
You can create the variable outside of the event and than access it outside. But as ajax is ascychron, the variable would still be undefined:
var external;
$('#myselect').on('change', function() {
$.ajax({
url: 'myurl' + this.value,
method: 'GET',
success: function(result) {
external = result;
}
});
});
// this would be still undefined
console.log(external);
You can write the console.log inside your success, or create your own callback function. Then you can log or handle the data otherwise after the ajax request.
$('#myselect').on('change', function() {
$.ajax({
url: 'myurl' + this.value,
method: 'GET',
success: function(result) {
myCallback(result);
}
});
});
function myCallback(external) {
console.log(external);
}
Even shorter would it be possible in this example, if you directly use your callback function as success callback without wrapper. And because GET is the default request type, we could remove it too:
$('#myselect').on('change', function() {
$.ajax({
url: 'myurl' + this.value,
success: myCallback
});
});
function myCallback(external) {
console.log(external);
}
I'm sorry if I'm misunderstanding the question:
What it sounds like is that you are trying to get the data from external but the ajax call hasn't called the callback yet, so the data hasn't been set.
If I can recommend how to fix it, call the code that references external from the callback itself so you can guarantee that you have the data when you need it.
You are not able to access variable because it comes in picture after ajax completion and you are trying to access it directly, since you don't have any idea how exact time this ajax takes each time so you need to define a function like this
$('#myselect').on('change', function() {
$.ajax({
url: 'myurl'+this.value,
method: 'GET',
success: function(result) {
console.log(result); //Just checking it's there
saySomething(result); //result will be injected in this function after ajax completion
});
});
function saySomething(msg) {
console.log(msg); //use variable like this
}
I hope my code is help to you.
$('#myselect').on('change', function() {
$.ajax({
url: 'myurl'+this.value,
method: 'GET',
async: false, // stop execution until response not come.
success: function(result) {
console.log(result); //Just checking it's there
external = result;
}
});
});
console.log(external); //now it should return value
Define the variable external above your first function like so:
var external;
$('#myselect').on('change', function() {
$.ajax({
url: 'myurl'+this.value,
method: 'GET',
success: function(result) {
console.log(result); //Just checking it's there
external = result;
}
});
});
console.log(external);

return ajax.done data gives error on jquery

I have data in my ajax.done and it bugs on jquery.
i googled on it and cant find anything.
what to do?
function select_aragement(arragament){
var arrst = arragament;
var arrsplit = arrst.split("|");
var periode = arrsplit[0];
var id = arrsplit[1];
var postsjson;
var test= $.ajax({
type: 'POST',
async: true,
url: 'ajax/prijzen.php',
data: { id: id, periode: periode },
dataType: 'json'
}).done(function (vis) {
console.log(vis);
postsjson = $.parseJSON(vis);
});
return postsjson;
}
You shouldn't be attempting to return anything from a callback function because the returned value doesn't go anywhere meaningful. Instead you simply use the response from the AJAX request inside that callback function.
Let's say you have this code:
function bar() {
var myObject = foo();
// do something with myObject
}
function foo() {
var bar; // 1
var xhr = $.ajax({
url: yourUrl,
dataType: 'json',
type: 'post',
data: {
some: 'data'
}
}); // 2
xhr.done(function(yourObject) {
bar = yourObject; // 5
}); // 3
return bar; // 4
}
bar();
The comments inside the foo function indicate the order in which those statements execute. So you declare a variable bar, declare a variable xhr that has a Deferred object, attach a done handler to it with a callback function, return the value of bar, then the value of bar is set (too late - you've already tried to return it).
Inside of your execution of the bar function myObject is going to be undefined, because the value of bar inside the foo function wasn't set before the return statement. What you need to do is simply move the // do something with myObject code to the callback function, and use bar there:
function foo() {
var xhr = $.ajax({
url: yourUrl,
dataType: 'json',
type: 'post',
data: {
some: 'data'
}
}); // 1
xhr.done(function(yourObject) {
var bar = yourObject; // 4
// do something with bar
}); // 2
// 3 - function execution has finished
}
You might want to move the return line inside the done section
}).done(function (vis) {
console.log(vis);
postsjson = $.parseJSON(vis);
return postsjson;
});
but keep in mind that, being an asynchonous call, so will be your return. My advise would be to pass in a callback.
function select_aragement(arragament, callback){
var arrst = arragament;
var arrsplit = arrst.split("|");
var periode = arrsplit[0];
var id = arrsplit[1];
var postsjson;
var test= $.ajax({
type: 'POST',
async: true,
url: 'ajax/prijzen.php',
data: { id: id, periode: periode },
dataType: 'json'
});
test.done(function (vis) {
console.log(vis);
postsjson = $.parseJSON(vis);
callback && callback(postjson);
});
}
And modify your code to use the callback instead of the returned value.
before
var postjson=select_aragement(arragament);
...stuff with postjson...
after
select_aragement(arragament, function(postjson) {
...stuff with postjson...
});
You are trying to make the ajax call fire synchronously, for that you need to make the async property false.
async: false,
The problem :
Look at the following code :
function getValue(){
var value = 0;
setTimeout(function(){
value = 42;
}, 1000);
return value;
}
What is the returned value ?
fiddle
This is your exact same problem with
function select_aragement(arragament){
var postjson;
$.ajax(...).done(function(vis){
postjson = vis;
});
return postjson;
}
A solution :
I imagine you use your function in the following way :
var data = select_aragement(arragament);
// do something with data :
$.each(data, function(){
....
});
You can change select_aragement's code like this :
function select_aragement(arragament){
var arrst = arragament;
var arrsplit = arrst.split("|");
var periode = arrsplit[0];
var id = arrsplit[1];
var test = $.ajax({
type: 'POST',
async: true,
url: 'ajax/prijzen.php',
data: { id: id, periode: periode },
dataType: 'json'
});
// return the promise which wraps the ajax call
return test;
}
and the calling code like this :
// "p" stands for "promise"
var p = function select_aragement(arragament);
p.done(function(data){
// do something with data :
$.each(data, function(){
....
});
});
or without the local variable :
select_aragement(arragament).done(function(data){
// do something with data :
$.each(data, function(){
....
});
});
In this case you can use async/await mixed to .done from jQuery like this:
async function myasyncfunction(myArgs){
var response = [];
var req = $.ajax({
method: "GET",
url: resquestURL,
dataType: "json",
})
await req.done( res => {
//DO some stuff with your data
for (let index = 0; index < res.length; index++) {
const element = res[index];
response .push( "some stuff" + element );
}
})
return response;
}

Retrieve JS function value

I'm currently trying to retrieve a JS return value and I don't really know the reson why it doesn't work...
Hi hoper my code is the most easiest to read as possible, thanks in advance :
<script type="text/javascript">
function getValLocalSto(key, URL){
console.log(key);
console.log(URL);
var myKey = localStorage.getItem(key);
if(myKey == null){
// getting back JSON data
$.ajax({
url: URL,
dataType: 'json',
async: false,
success: function (json) {
var test;
console.log(JSON.stringify(json)); // the result is a well formed JSON string
localStorage.setItem(key,JSON.stringify(json));
myKey = localStorage.getItem(key);
test =jQuery.parseJSON(myKey);
console.log("My function result : "+test); // the result is a [object Object]
return test;
}
});
}else {
// Other work whatever
}
}
//call my function
console.log("sortie fonction : "+getValLocalSto("testJson", "do/profil")); // the result is "undefined"
var myuResult = getValLocalSto("testJson", "do/profil")); // the result is "undefined"
console.log(ff.prenom);
document.getElementById("myDiv").innerHTML="<div><input disabled='disabled' name='text-basic' id='text-basic' type= 'text' value='Votre nom "+ff.nom+"'/></div>";
document.getElementById("myDiv").innerHTML+="<div> <input disabled='disabled' name='text-basic' id='text-basic' type= 'text' value= 'Votre prenom "+ff.prenom+"'/></div>";
</script>
The solution :
function getValLocalSto(key, URL){
// do my stuff
});
}else {
// Other work whatever
}
return test;
}
Just declare test variable outside the ajax success function in the getValLocalSto outer function taking advantage of the variable scope. Else you would need a callback to return the variable from the ajax success function. Try this:
<script type="text/javascript">
function getValLocalSto(key, URL){
...
if(myKey == null){
// getting back JSON data
var test;
$.ajax({
url: URL,
dataType: 'json',
async: false,
success: function (json) {
console.log(JSON.stringify(json)); // the result is a well formed JSON string
localStorage.setItem(key,JSON.stringify(json));
myKey = localStorage.getItem(key);
test =jQuery.parseJSON(myKey);
console.log("My function result : "+test); // the result is a [object Object]
}
});
return test;
}else {
// Other work whatever
}
}
//call my function
console.log("sortie fonction : "+getValLocalSto("testJson", "do/profil")); // the result is "undefined"
...
</script>
You can pass a callback to AJAX.
Change function definition to:
function getValLocalSto(key, URL, callback){
...
$.ajax({
url: URL,
dataType: 'json',
async: false,
success: callback
});
...
in the code:
getValLocalSto("testJson", "do/profil", function(data) {
localStorage.setItem(key,JSON.stringify(data));
myKey = localStorage.getItem(key);
test = jQuery.parseJSON(myKey);
// here you work with test as you want as a result of getValLocalSto
});

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