Javascript ajax post, how to get variable? [duplicate] - javascript

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
How to access a variable set within an Ajax call
I am struggling a little, I have a ajax post, and I get a number returned from the call.
My question is, how do I get the result number into a variables that can be seen outside the $.post call ?
E.g:
//code here
$.post('../utility/width.php', { adress:adr } ,
function(width) {
//this width result, I want it to be used
});
// here
//code here

AJAX is asynchronous. You'll have to use a callback function that gets called when the AJAX request finishes:
$.post('../utility/width.php',
{adress:adr},
function(width) {
alert(width);
}
});
An alternative would be to make the request synchronous, but that probably isn't something you want.

Related

How to specify an asynchronous request in API JavaScript [duplicate]

This question already has answers here:
How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?
(14 answers)
Closed 6 years ago.
I want to send to server (php) a request AJAX from an api javascript:
JS File :
var commit = new Object();
commit.id= this.id;
commit.action = this.doCommit;
commit.vrp= this.vrp;
$.post(this.ajaxURL, commit);
with this code i can send a request but in mode asynchroun. I searched on internet and I found a solution :
$.ajax({
type: 'POST',
url: this.ajaxURL,
data: commit,
async:false
});
I don't know if it is the best solution, or I can precise async:false in a $.post request, if yes , how ?.
So you do or you do not want to send the request asynchronously? The question seems to be confusing for me. But by default, $.ajax({... is always async, and $.post is just a shorthand way to write a simple post ajax request, which is also async. If you use the async:false, you are telling the javascript to not continue to execute the next line of code until the request finishes.

Javascript and Jquery mixing, what happens first? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I apologize for asking such a simple question, but googling "javascript or jquery first" just keeps giving me people asking which they should learn first.
Currently I have a couple lines of javascript, followed by a bit of jquery, followed by a bit more javascript. This is the part where it breaks down...
$.get("alliances.php", function(data, status){
console.log(data);
searchIndex = data.search(allianceName);
rawAllianceLink = data.slice(searchIndex-25,searchIndex);
});
console.log(rawAllianceLink);
After I carry this code out, the JQuery goes last and my console.log prints undefined. (Note, the console.log isn't the actual statement, I have more lines that need to go after this, it is just an example that it is performed out of order.) Was wondering if someone could clarify or explain how I can alter when each of these steps is carried out.
Simple ans:
Its simply because your $.get(... is an AJAX call. You have to log your data in callback handler.
$.get("alliances.php", function(data, status){
console.log(data);
searchIndex = data.search(allianceName);
rawAllianceLink = data.slice(searchIndex-25,searchIndex);
})
.done(function() {
console.log(rawAllianceLink);
});
Let's get a few things clear here. $.get() is a wrapper for $.ajax() in jQuery. The javascript being applied happens within the jQuery library.
Next, the $.get call is asynchronous meaning that the console.log(rawAllianceLink); likely will fire prior to the $.get() request completing, which takes some time to fetch the file and read the data.
The function(data, status) is applied to the data returned from alliances.php only after the request has fully completed. Within that callback function, it would seem as if you've properly applied the javascript methods that you intend.
If you need to fire further code after the callback execution occurs, then you should place it into a function and execute the function at the end, passing the rawAllianceLink as an argument, like so:
$.get("alliances.php", function(data, status){
console.log(data);
searchIndex = data.search(allianceName);
rawAllianceLink = data.slice(searchIndex-25,searchIndex);
process_request(rawAllianceLink);
});
function process_request(RAL){
console.log(RAL);
}
Now things will be fired in the proper order. You could also look into jQuery's $.defered, but that may be another beast, entirely.
What is happening in your code, is that, the jQuery "get" function is called, which sends a request to the server to retrieve some information at "alliances.php", but it just sends the request, it doesn't wait for a response, then it carries on with the console.log. At some later point, the browser gets the response back from the server, and when the browser gets a chance, it executes the code in the callback function. This kind of programming isn't unique to jQuery, it happens with event handler, timeouts, intervals, etc. in javascript, whether you use jQuery or not.

How do I execute an action when the readystate is 4? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I have been working on this for the past 2 hours. I am getting the error, SyntaxError: Unexpected token u when I try to parse a GET request using a function. But I perform the same code one line at a time it works fine.
I noticed that as soon as I create an object its readyState is 1, but right after I save it and wait a second the readyState changes to 4 then it parses fine.
I thought that maybe the XmlHttpObject I am pulling just needs to communicate to the server after the object is already on my computer, like maybe it is not done pulling all information and once the information pull is complete it turns it to 4. As a result of this realization I tried to use the timeout function to wait a few seconds then try to parse it, but I still couldn't get it to work!
Here is my code:
function pullData(){
var obj = $.get("https://api.parse.com/1/classes/chats");
var object_array = JSON.parse(obj.responseText);
return object_array
}
function pullData(callbackFunction)
$.get( "https://api.parse.com/1/classes/chats", function( data ) {
var object_array = JSON.parse(data);
callbackFunction(object_array);
});
}
JavaScript ajax calls are asynchronous, so u can't get the result at next line code after you perform get request, because get request is executed in background.
JQuery has a great documentation to look how to write ajax requests. http://api.jquery.com/jquery.get/
Why don't you try
function pullData(){
$.get("YOUR_URL")
.done(function(data) {
var object_array = JSON.parse(data);
return object_array
})
}

How to make a function return data retrieved via AJAX [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
In my javascript file, I use the function above to get asynchronously a value calculated by the server:
function function2(userid)
{
$.ajax({
type: "POST",
url: "http://localhost/bghitn/web/app_dev.php/get_number_of_articles",
data:{id:userid},
cache: false,
success: function(data){
return data;
}
});
}
In fact, I call the function2 inside a set of functions:
function1();
var userid=.....
var x= function2(userid);
function3(x);
The problem:
as you see, function3 uses the data returned by function2. But it seems that function3 starts executing before the AJAX call is successfully finished. I tried to use the when function but in vain.
$.when(function2(userid)).done(function(){
function3();
});
How to make the next javascript code executes after the preceding AJAX request is successfully performed? Your advices are highly appreciates.
Option 1: You can always set your AJAX call to be synchronius, but be ready that the whole page stucks while waiting for response. just add parameter async: false to your set of parameters.
Option 2: Provide callbacks or put your future code inside success handler
Option 3: You can use defer/promise described here http://blog.mediumequalsmessage.com/promise-deferred-objects-in-javascript-pt1-theory-and-semantics

How to get data out of $.post [duplicate]

This question already has answers here:
getting a response from $.post
(2 answers)
Closed 9 years ago.
I want geting data out of jQuery podt, How can do it?
nat="";
$.post("random_unique", function(data){
nat = data;
});
alert(nat); //--> Nothing.
jQuery calls are asynchronous, in that you can execute the remainder if your script while the data is still loading. Perform your tasks in the callback of your $.post().
nat="";
$.post("random_unique", function(data){
nat = data;
alert(nat); //--> Something!
});
P.S. don't use alert() to debug code; use console.log(). If you receive a JSON response (or when you get into error handling) often times you'll be working with objects, which don't alert out.

Categories

Resources