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

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

Related

JQuery GET does not define output [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
I am working on a Javascript / JQuery project that requires that I get data from another website. I use the following JQuery code to achieve this:
var user = "Bob";
url = "https://api.example.com/api/" + user;
$.get(url, function(data){
profiles = data;
});
alert(profiles);
For some reason when I run the code I get this Error Message:
Uncaught ReferenceError: profiles is not defined
But when type "profiles" in the google chrome javascript console, I see my target data. What am I doing wrong?
Thanks- Evan
Are you in 'use strict' or an es6 module ? it sounds like it
You need to explicitly declare the variable
var user = "Bob";
// this was not really the problem
var profiles;
url = "https://api.example.com/api/" + user;
$.get(url, function(data){
profiles = data;
// run your alert here
alert(profiles);
});
//this is the problem. The above callback function runs asynchronously,
// after the data has been fetched which can take some time
// code from this point on runs synchronously, before the request to the server
// hence 'profiles is undefined'
alert(profiles);

What's wrong with my JSON.parse and why's the code not executed in order of appearance? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I'm importing some data with PHP, which gets data from an SQL database. I'm using AJAX to import the data from the PHP to Javascript. The PHP code works fine and results in "2", but something's wrong with my Javascript code:
<script>
$.getJSON("Kategorie1.php", function (data) {
window.nrFragen = JSON.parse(data);
window.alert(data)
});
window.alert(window.nrFragen);
</script>
If I run it, it first runs window.alert(window.nrFragen) which alerts undefined and then window.alert(data), which alerts "2", as it should.
Why does it first run the window.alert(window.nrFragen), even though it's written after window.alert(data)? And, why isn't window.nrFragen = JSON.parse(data); working?
$.getJSON is async.
$.getJSON("Kategorie1.php", function (data) {
//this will be called only after request completion
window.nrFragen = JSON.parse(data);
window.alert(data)
});
//this will be called immediately after $.getJSON, it won't wait for request completion
window.alert(window.nrFragen);

Having trouble saving javascript http response to a variable [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I've been messing around with this Wikipedia node module in bash and I'm having some trouble saving the response to a variable. I can use console.log(response) to see the complete response but I can't get it to stick to a variable.
I tried maybe looking at the type of response but it just returns undefined. Any ideas?
var wikipedia = require("node-wikipedia");
wikipedia.page.data("Clifford_Brown", { content: true }, function(response) {
console.log(typeof response);
});
Ideally I'd like to assign the response which has an html object to a variable and then use cheerio to get pieces of the html object with jQuery selectors, but I believe I need to at least get it in to a variable first, right?
This is part of the response.
{ title: 'Clifford Brown',
redirects: [],
text: { '*': '<div class="hatnote">For the scrutineer for the Eurovision Song Contest, see Clifford Brown (scrutineer).
Edit/Fix
I was able to get this to work based on #idbehold's comments. Everything needed to be done in the call back so instead of calling the variable after the request, I returned it in the callback like this, which gave me access to the variable outside of the function.
var wikipedia = require("node-wikipedia");
var data;
wikipedia.page.data("Clifford_Brown", { content: true }, function(response) {
data = response;
})
There are many, many questions of this sort which appear on StackOverflow, and they all stem from not understanding the asynchronous nature of AJAX. Your code does not block at the .data() call to wait for the server to respond. Any lines of code that run after that call will run immediately, whereas the code inside your callback function will runs at some point in the future, after the data is returned from the server. Anything you do in response to getting the data must happen in that callback.
var wikipedia = require("node-wikipedia");
wikipedia.page.data("Clifford_Brown", { content: true }, function(response) {
console.log(typeof response);
// do something with the response here
});
// any code here will run before the above callback is invoked.
// don't try to do anything with the response here.

responseText Field Undefined [duplicate]

This question already has answers here:
jQuery: Return data after ajax call success [duplicate]
(5 answers)
Closed 8 years ago.
I am using jQuery to pull in data from a csv. The request is successful (Success!! in the console) and I can see the data in the responseText field when I print the object but I can't print data.responseText (shows in console as "undefined").
window.onload = function(){
console.log("start");
var data = $.ajax({url:"http://localhost/bootstrap/data/930.csv",success:function(){
console.log("Success!!");
}()
});
console.log(data);
console.log(data.responseText);
How do I access responseText to transform it?
EDIT:
Updated my code per comments to force sync and modified the variables to better follow them. Still I was surprised by the result.
console.log("start");
var ajaxData = $.ajax({url:"http://localhost/bootstrap/data/930.csv",async:false,success:function(dataReturned){
console.log("Success!!"); //Success!!
console.log(dataReturned); //Returns my csv data
console.log(dataReturned.responseText); //undefined
}
});
console.log(ajaxData); //Returns a jQuery object that included my csv data
console.log(ajaxData.status); // Returns 200
console.log(ajaxData.responseText); //Returns my data (same as dataReturned in success function)
So I guess I also missed that the jQuery object isn't created and available until the complete $.ajax call finishes but the response is available sooner.
Thanks for the help.
Please learn about asynchronous methods. You need to use the callback. What you tried to do is eat a delivery pizza right after you hung up the phone. You need to wait until the guy delivers it.
$.ajax({url:"http://localhost/bootstrap/data/930.csv",success:function(data, status, xhr){
console.log("Success!!");
console.log(data);
console.log(xhr.responseText);
}
});

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