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);
}
});
Related
This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 5 years ago.
I'm writing a jquery code and calling a JavaScript function through it on a jsp page.
This is the jquery function
$(function () {
$('#defaultCountdown').countdown({until: $.countdown('//SomeTime'),onExpiry: liftOff});
});
liftOff is a javascript method which is called after the specified time expires.
This is the JavaScript function
<script>
function liftOff() {
alert("Before Delete");
<% DAO_Object.deleteRecord(ID);%>
alert("After Delete");
}
</script>
Now here the problem is, the line <% DAO_Object.deleteRecord(ID);%> is getting executed before the function call and the record from database is getting deleted. The alert statements are executing correctly AFTER the function call.
Am i calling the deleteRecord method incorrectly?
You are mixing your server-side JSP logic with your client-side JavaScript logic.
Everything between <% %> runs on your servlet when it's processing the request, so the record is already deleted by the time you get the response in the browser. If you look at the HTML/JS you are receiving in the browser using Chrome DevTools or similar tool, you will see that there is nothing between those alert(...) calls.
Your solution here is to setup a route that handles the deleteRecord() on the server-side, and call it via AJAX in your liftOff() method. So liftOff() would look something like this:
// assuming `id` is a string here
function liftOff(id) {
alert("Before Delete");
// You'll have to setup this endpoint to run
// your `DAO_Object.deleteRecord(ID);` code
// in your JSP code.
$.get("/delete/my/record/" + id, {
error: function(e){
// some kind of error occurred in making the request
},
success: function(resp){
// `resp` is the response from the server
alert("After Delete");
}
});
}
I am trying to read in a JSON file from my directory using the jQuery.getJSON method and it returns the object shown in the picture. I want to get the responseText from the object but cannot figure out how.
var jsonData = jQuery.getJSON('relationalData.json');
Ive tried to use the following to extract the responseText but they all failed.
var response = jsonData.responseText;
var response = jsonData['responseText'];
I also tried using without any luck, as the method doesn't even get called with a json file. It worked when I used an xml though.
$.get(filename, function(data){
var responseText = data;
});
A similar solution to guest271314 but, maybe, still instructive for someone ...
$.getJSON('http://ws.spotify.com/search/1/artist.json?q=foo')
.done(function(obj,status,xhdr){$('#out').append(xhdr.responseText);});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="out"><div>
The important part is to look for the .responseText property in the xhdr object, which can be accessed though the third parameter of the callback function.
Came across this question which has been longed asked, but for future visitors where is my solution:
$.getJSON method fetches data from a server using HTTP GET request, the response on successful call returns in a responseText property as you see in your console.
Therefore to get the data of the responseText you have to use the JSON.parse() method to retrieve data to javaSrcipt object like this:
var jsonData = JSON.parse(jsonCall.responseText);
But $.getJSON() method is asynchronous so this must be done inside the callback function if not the response may not exist.
Final solution:
var jsonCall = $.getJSON('URL',function(){
var jsonData = JSON.parse(jsonCall.responseText);
console.log(jsonData);
});
Try utilizing .then() , substituting responseJSON for responseText
var jsonData = jQuery.getJSON("https://gist.githubusercontent.com/guest271314/23e61e522a14d45a35e1/raw/a5ac6cffdc1ffab39f9db425844721b528751654/a.json");
jsonData.then(function(data, textStatus, jqxhr) {
alert(jqxhr.responseJSON)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
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
})
}
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I have a simple script to get a PHP session user id into a javascript file. Yet when I try to simply alert the user id it says undefined?
As shown in code I have tried with simple alert to check the data coming back from the script and it is correct.
var user_id;
$.get( "/ajax/actions/getUserId.php", function( data ) {
// alert(data); <-- this works correctly
var user_id = data;
});
alert(user_id);
Is there a better way to do this?
The PHP file accessed (getUserId.php) is simply:
session_start();
echo $_SESSION[user_id];
Ajax is asynchronous, so the last alert will be executed before the callback function of ajax is called.
You should use:
$.get( "/ajax/actions/getUserId.php", function( data ) {
var user_id = data;
alert(user_id);
});
Ajax is asynchronous by default.
In your snippet the code goes through the following steps:
Define variable called user_id in the global lexical scope
Make GET ajax request to /ajax/actions/getUserId.php
Alert the value of the variable user_id which is undefined (by default, you haven't set it any value).
At given point the ajax request is successfully completed, your callback gets invoked so:
You define new variable called user_id, in the lexical scope of your callback
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.