jQuery ajax return value [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
How can I return the value "pinNumber" from jquery ajax so I can append it outside of the ajax. Here is my code
var x = pinLast + 1;
for(i=x;i<=pinMany;i++) {
var i = x++;
var cardNumber = i.toPrecision(8).split('.').reverse().join('');
var pinNumber = '';
jQuery.ajax({
type: "POST",
url: "data.php",
data: "request_type=generator",
async: false,
success: function(msg){
var pinNumber = msg;
return pinNumber;
//pin number should return
}
});
jQuery('.pin_generated_table').append(cardNumber+' = '+pinNumber+'');
// the variable pinNumber should be able to go here
}
Please ask me if you don't understand.. ^^ thanks

AJAX is asynchronous by default, you cannot return a value from the callback without making a synchronous call, which you almost certainly don't want to do.
You should supply a real callback function to the success: handler, and put your program logic there.

var pinNumber = $.ajax({
type: "POST",
url: "data.php",
data: "request_type=generator",
async: false
}).responseText;
jQuery('.pin_generated_table').append(cardNumber+' = '+pinNumber+' ');

It has to do with variable scope. The local variable pinNumber you create is not accessible outside its wrapping function.
Perhaps declare pinNumber globally or if it'll do the trick, simply stick your .append() inside your success function.

var _successEvent = function(response){
$('.pin_generated_table').append(cardNumber + ' = ' + response);
};
$.ajax({
type: "POST",
url: "data.php",
data: "request_type=generator"
}).done(_successEvent);

You can use this example:
window.variable = 'some data';
This make you variable global and you can access to this from anywhere

Here is the simple solution.
//---------------------------Ajax class ------------------------------//
function AjaxUtil()
{
this.postAjax = function(Data,url,callback)
{
$.ajax({
url: url,
async: true, //must be syncronous request! or not return ajax results
type: 'POST',
data: Data,
dataType: 'json',
success: function(json)
{
callback(json);
}
});
}//--end postAjax
}
//--------------------------------End class--------------------//
var ajaxutil = new AjaxUtil();
function callback(response)
{
alert(response); //response data from ajax call
}
var data={};
data.yourdata = 'anydata';
var url = 'data.php';
ajaxutil.postAJax(data,url,callback);

Related

JS Function including AJAX returning undefined [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
function idToUnitNum(id){
$.ajax({
type: "POST",
url: "ajax_officerFromId.php",
data: {'id': id},
success: function(dataString) {
ofd = JSON.parse(dataString);
var result = ofd.data;
console.log(result);
return result;
}
});
}
This is the function. It's called from another function. I tried testing it's output by logging result before it returns, and it displays the appropriate result.
Result (JSON):
{"success":"true","time":1524462577,"data":"ADMIN"}
However, when I try catching the variable (a string), it does shows as "undefined".
It's probably a stupid mistake.
Calling the function:
var unitnum = idToUnitNum(adata.arresting_officer);
console.log(unitnum);
Thank you for your assistance!
pass callback function to idToUnitNum. something like below
function idToUnitNum(id,callback){
$.ajax({
type: "POST",
url: "ajax_officerFromId.php",
data: {'id': id},
success: function(dataString) {
ofd = JSON.parse(dataString);
var result = ofd.data;
console.log(result);
callback(result);
}
});
}
Hi Please change the AJAX function like this :
function idToUnitNum(id){
var dfd = $.Deferred();
$.ajax({
type: "POST",
url: "ajax_officerFromId.php",
data: {'id': id},
success: function(dataString) {
ofd = JSON.parse(dataString);
var result = ofd.data;
dfd.resolve(result);
// return result;
}
});
return dfd.promise();
}
And you can use this function like this
idToUnitNum(adata.arresting_officer).done(function(response){
console.log(response);
});
FYI : not tested code
function idToUnitNum(id){
var result = '';
$.ajax({
type: "POST",
url: "ajax_officerFromId.php",
async: false,
data: {'id': id},
success: function(dataString) {
ofd = JSON.parse(dataString);
result = ofd.data;
}
});
return result;
}
Thank you to whoever suggested I turn off async and call it outside fo the AJAX request. Solved the issue.
You should either use a callback function as a parameter or, even better, use promises. Simply put return in front of your ajax call and call .then() on the return value to read the result when it is available.
This has been asked many times, so you shouldn’t have any trouble finding more information about these solutions

Ajax global variables or synchronous AJAX [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I want to get data from another page using AJAX. I also want to wrap this AJAX call into my "user defined function".
But I can not write like this:
function func(){
var tmp;
$.ajax({
url: 'url',
type: "POST",
dataType: "json",
success: function (data) {
tmp=data;
}
});
return tmp;
}
because AJAX is asynchronous and this code returns - "undefined".
When AJAX async param set to false
var tmp=$.ajax({...});
possible do the trick.
I also can create some global variables and write like this:
function setMyVariable(){
$.ajax({
...
success: function (data) {
myGlobalVariable=data;
}
});
}
The question is - Is it good practice to use global variables in this case?
Or it is completely wrong and I need search something else
The best practice would be to return the promise from $.ajax:
function func(){
var tmp;
return $.ajax({
url: 'url',
type: "POST",
dataType: "json",
});
}
Then you can do function().done(function(result) { ... } );

Javascript, create a global variable with window[]

So, i'm in an ajax request, in the success callback :
var just_id = $(this).attr('id');
$.ajax({
type: "GET",
url: "/tw/www/search/",
data: {search:tw_search, type:'tw_search'},
success: function (html) {
window[just_id] = $(this).attr('tw_username');
}
});
With this code, after i call with ajax my script, i need to create a variable with the name of a specific element.
So, if i'm on a <div id="test"></div>, in var just_id i have test and then, i create a variable test with window[just_id].
But i need to retrieve this variable in an other function on my page.. How can i do that ? I need to create a global variable with windows[]... Thanks !
Use window to declare global variable:
window.globalVar[];// i have not give window as varible name this may cause error it must be reserved
var just_id = $(this).attr('id');
$.ajax({
type: "GET",
url: "/tw/www/search/",
data: {search:tw_search, type:'tw_search'},
success: function (html) {
globalVar[just_id] = $(this).attr('tw_username');
}
});
NB! First of all, if you are using this in success callback in ajax, this would have different context, not what you are expecting.
Answer: you can define some variable in top of function declaration
var just_id = $(this).attr('id'),
attrUsername;
$.ajax({
type: "GET",
url: "/tw/www/search/",
data: {
search: tw_search,
type: 'tw_search'
},
success: function (html) {
attrUsername = $(this).attr('tw_username');
}
});
Then, you can access to this variable. Avoid to use global variable for your purpose
Can't directly assign indexed value to window object. But you can do in this way:
window.x = new Array();
window.x[4] = 'value here';
// And can read from any function like here
;(function(){
alert(window.x[4]);
})();
For your script above:
window.global = new Array();
window.global[just_id] = $(this).attr('id');
$.ajax({
type: "GET",
url: "/tw/www/search/",
data: {search:tw_search, type:'tw_search'},
success: function (html) {
window.global[just_id] = $(this).attr('tw_username');
}
});

Accessing JSONP data outside of ajax call in jQuery

Now that every google link in the first 5 pages of results is :visited in my browser, I needed to ask...
How can I get the JSON data working so that I can access it/manipulate it in other methods?
_otherMethod: function() {
// END GOAL OF WHERE I WANT THIS TO BE AVAILABLE
var text = this._requestText();
},
_requestText: function() {
var url = 'http://api.flickr.com/services/feeds/photos_public.gne?format=json';
$.ajax({
type: 'GET',
url: url,
async: false,
dataType: 'jsonp',
success: function(data) {
// works here
console.log(data);
// works here as well & fires local function
testing(data);
// doesnt store
var testvar_1 = data;
}
});
// undefined
console.log(testvar_1);
function testing(data) {
// logs when called from above
console.log(data);
// doesnt store
var testvar_2 = data;
}
// undefined
console.log(testvar_2);
// havent found this yet...
return magicVariableThatLetsMeAccessJSON
}, ...
any ideas? i know theres a lot of other similar questions on stack overflow, but i have found nothing that solves this.
thanks
UPDATE
var storage;
var yourobj = {
_otherMethod: function() {
// END GOAL OF WHERE I WANT THIS TO BE AVAILABLE
var text = this._requestText();
},
_requestText: function() {
var url = 'http://api.flickr.com/services/feeds/photos_public.gne?format=json';
$.ajax({
type: 'GET',
url: url,
async: false,
dataType: 'jsonp',
success: function(data) {
storage = data;
// logs correctly
console.log(storage);
}
});
}
}
//undefined
console.log(storage);
yourobj._requestText();
//undefined
console.log(storage);
Firstly as noted elsewhere, you need a variable that's in scope, secondly you need to make sure it's not evaluated before the callback is called.
The only way to ensure that is to make the call to _otherMethod inside the success call back method
_otherMethod: function(text) {
//...do what ever you need to do with text
},
_requestText: function() {
var url = 'http://api.flickr.com/services/feeds/photos_public.gne?format=json';
$.ajax({
type: 'GET',
url: url,
async: false,
dataType: 'jsonp',
success: function(data) {
_otherMethod(data);
},
}
});
}
callbacks are asyncronous meaning they are called at some point in time that's not determined by the sequence of code lines.
If you know the code using the returned data is never going to be call before the success call back has executed and you need to hold on to the data you can change the code to
_otherMethod: null, //not strictly needed
_requestText: function() {
self = this;
var url = 'http://api.flickr.com/services/feeds/photos_public.gne?format=json';
$.ajax({
type: 'GET',
url: url,
async: false,
dataType: 'jsonp',
success: function(data) {
self._otherMethod = function(data){
return function(){
//do what you need to with data. Data will be stored
//every execution of _otherMethod will use the same data
console.log(data);
}
}
},
}
});
}
Very simple. You need a storage variable outside of the context of the callback function.
var storage;
var yourobj = {
_otherMethod: function() {
// END GOAL OF WHERE I WANT THIS TO BE AVAILABLE
var text = this._requestText();
},
_requestText: function() {
var url = 'http://api.flickr.com/services/feeds/photos_public.gne?format=json';
$.ajax({
type: 'GET',
url: url,
async: false,
dataType: 'jsonp',
success: function(data) {
storage = data;
}
});
}
}
Alternatively, storage can be a property on the same object.
By adding var before your variable name, you create a local variable in the current scope.
This doesn't work:
var a = 2;
(function() {
var a = 3;
})();
console.log(a); // 2
While this does:
var a = 2;
(function() {
a = 3;
})();
console.log(a); // 3
Since the variable that you're trying to set is in an outer scope, get rid of var when working with it in an inner scope.
might be this way:
_requestText: function() {
var url = 'http://api.flickr.com/services/feeds/photos_public.gne?format=json';
var testvar_1;
$.ajax({
type: 'GET',
url: url,
async: false,
dataType: 'jsonp',
success: function(data) {
console.log(data);
testing(data);
testvar_1 = data;
}
});
// should work here
console.log(testvar_1);
Actually you were creating a new instance of that var there.

How can I return a variable from a $.getJSON function

I want to return StudentId to use elsewhere outside of the scope of the $.getJSON()
j.getJSON(url, data, function(result)
{
var studentId = result.Something;
});
//use studentId here
I would imagine this has to do with scoping, but it doesn't seem to work the same way c# does
it doesn't seem to work the same way
c# does
To accomplish scoping similar to C#, disable async operations and set dataType to json:
var mydata = [];
$.ajax({
url: 'data.php',
async: false,
dataType: 'json',
success: function (json) {
mydata = json.whatever;
}
});
alert(mydata); // has value of json.whatever
Yeah, my previous answer does not work because I didn't pay any attention to your code. :)
The problem is that the anonymous function is a callback function - i.e. getJSON is an async operation that will return at some indeterminate point in time, so even if the scope of the variable were outside of that anonymous function (i.e. a closure), it would not have the value you would think it should:
var studentId = null;
j.getJSON(url, data, function(result)
{
studentId = result.Something;
});
// studentId is still null right here, because this line
// executes before the line that sets its value to result.Something
Any code that you want to execute with the value of studentId set by the getJSON call needs to happen either within that callback function or after the callback executes.
Even simpler than all the above. As explained earlier $.getJSON executes async which causes the problem. Instead of refactoring all your code to the $.ajax method just insert the following in the top of your main .js file to disable the async behaviour:
$.ajaxSetup({
async: false
});
good luck!
If you wish delegate to other functions you can also extend jquery with the $.fn. notation like so:
var this.studentId = null;
$.getJSON(url, data,
function(result){
$.fn.delegateJSONResult(result.Something);
}
);
$.fn.delegateJSONResult = function(something){
this.studentId = something;
}
var context;
$.ajax({
url: 'file.json',
async: false,
dataType: 'json',
success: function (json) {
assignVariable(json);
}
});
function assignVariable(data) {
context = data;
}
alert(context);
hmm, if you've serialized an object with the StudentId property then I think that it will be:
var studentId;
function(json) {
if (json.length > 0)
studentId = json[0].StudentId;
}
But if you're just returning the StudentId itself maybe it's:
var studentId;
function(json) {
if (json.length > 0)
studentId = json[0];
}
Edit: Or maybe .length isn't even required (I've only returned generic collections in JSON).
Edit #2, this works, I just tested:
var studentId;
jQuery.getJSON(url, data, function(json) {
if (json)
studentId = json;
});
Edit #3, here's the actual JS I used:
$.ajax({
type: "POST",
url: pageName + "/GetStudentTest",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{id: '" + someId + "'}",
success: function(json) {
alert(json);
}
});
And in the aspx.vb:
<System.Web.Services.WebMethod()> _
<System.Web.Script.Services.ScriptMethod()> _
Public Shared Function GetStudentTest(ByVal id As String) As Integer
Return 42
End Function

Categories

Resources