zip = 12345
url = "http://zip.elevenbasetwo.com/v2/US/"+zip;
res = $.get(url)
When I run above code in the browser console then I can access res.responseJSON but
When I run this code in my application.js then I can't access res.responseJSON I am getting undefine.
Does anybody know what's the issue or how can I access in my application.js ?
$.get is asynchronous. The response isn't immediatement available in the jqXHR object.
Pass a success callback to $.get :
$.get(url, function(data){
// use data
});
The reason why it seems to work in the console is because you don't instantly open the object which is logged : the server answers before. That's not the case in your normal code : while the request is sent, the following line in your code is immediately executed, without waiting for the answer.
Related
After refering this stack link Ajax response not calling success:function() when using jQuery 1.8.3 am wondering why if I uncomment the datatype line the success function is not invoked.I can understand that dataType =JSON is not calling success function.Could some one help me out ?
function doAjaxCall(methodType,Url,params,requestType,callBackFunction)
{
if(validate.variable(Url) && validate.variable(params))
{
$.ajax({
type : methodType,
url : Url,
// dataType : 'JSON', //if i uncomment i am not getting the response under success
data : params,
success : function(data)
{
console.log(data);
callBackFunction(data);
}
});
}
}
function callBackFunctiontest(data)
{
console.log('callBackFunctiontest : ' +data);
}
doAjaxCall('GET','/getData?accountNumber=9840100672&oid=d11c9f66-4c55-4855-a99e-580ba8ef8d61','noparams','application/JSON',callBackFunctiontest);
If it's not passing in success function, put an error function. This way you'll be able to see the error and understand what's going on.
You can also open the developer console and have a look at the 'network' panel.
Assuming you're calling callBackFunctiontest which should then be calling doAjaxCall.
You're trying to use data when there is no variable named data in scope. It will throw an undefined exception and doAjaxCall will not get executed. So your AJAX request will never get sent.
Try getting rid of the console.log('callBackFunctionTest : ' +data);, or pass it a value for data.
I am using Express JS web framework and NodeJS, both latest versions - 4.x.x.
Issue #1 - Not all of my POST ajax calls were being sent to my NodeJS server code.
How I found this is by trying to POST using Postman. All POSTMAN call requests were received by the server code but not the Express client requests. I checked by printing the console.log server debug statements to compare the findings between POSTMAN & Express Client.
Issue #2 - I was never receiving any response message from the server even though the server responded with a status 200 OK.
For both the issues, I made a few changes, which I believe will help others.
In the ajax call, I added e.preventDefault(); where 'e' is the event which is triggered via #click/#onclick.
Within ajax function call, I added the parameter dataType: 'json'.
In the NodeJS server code, index.js, I replaced res.send(req.body.search_data); with res.json(req.body.search_data);
P.S. - e.preventDefault() was actually built for a different purpose but it helped because it prevents a link from following the URL which is what solved the above issues.
I am trying to get a JSON object from a .jsp page. But I dont know what to do with it. I've googeled this for some time now, but I can't find out what this getJSON functions does.
Does it return a string representation of a JSON object?
Or is the parameter 'json' that is passed into the function the JSON Object?
Is the function (the second parameter) equivalent to the function that one write when using XMLHttpRequests? In other words; is this function the asynchronous part?
The alert with "JSON stuff" doesnt print.
<script type="text/javascript" src="jquery-1.7.2.js"></script>
<script type="text/javascript">
function checkUni() {
var URL = "http://localhost:8080/GradSchoolApp/test.jsp";
var jso = $.getJSON(URL, function(json) {
alert("JSON stuff " + json.name);
});
alert(jso);
//alert(jso.name);
}
A few things to check:
Is the webapp also running at localhost:8080? If not, you might be running afoul of the same origin policy, in which case you would need to encode to jsonp.
You should also check in firebug/inspect element/whatever to make sure you are actually getting something returned from your request. You can do this in the network or resources tab depending on which browser you are using. Also stick a breakpoint in your script before the alert and inspect the json object to see if anything was returned.
The second alert isn't firing because the json object doesn't exist yet when you call it.
The relevant docs for getJSON is here. The callback parameter (that you named json) is the already decoded data (i.e. it's a JavaScript object, not a string).
As for why your alert isn't doing anything, see Charles Bandes's answer. To better debug your code you can also use console.log (will work on Firebug or on Chrome), and/or set a handler to ajaxError - so if the problem is with your request you can be notified of the error (instead of the browser ignoring it by default).
Does it return a string representation of a JSON object?
The respone will come as JSON format. getJSON method is a short form of jQuery ajax with datatype as json . The datatype decides what is the format to receive the result from the ajax call.
is the parameter 'json' that is passed into the function the JSON
Object?
The variable json in your callback function will get the response from your ajax call. The data should in a valid JSON Document( if your server pages returns like that properly)
is this function the asynchronous part?
As i told you earlier, getJSON is a shortform of jquery ajax with datatype as Json. It is asynchronous.
I have following ajax call in my JavaScript code
url = 'http://news.ycombinator.com/?callback=?';
$.ajax({url:url ,async:!1,dataType:'script', complete:function(result)
{alert(JSON.stringify(result));}
});
Following is printed out in alert.
{'readyState':4, status:200, statusText:'success'}
It doesn't have responseText.But still, in the chrome console I can see all of the return HTML data of ycombinator page.How can I access this text?
On the other hand if I change the url variable to a url which returns a valid json object like following,
urll = 'http://gdata.youtube.com/feeds/api/videos?q=basshunter&format=5&max-results=5&v=2&alt=jsonc';
$.ajax({url:urll ,async:!1, complete:function(result)
{alert(JSON.stringify(result));}
});
this returns all of the responseText as expected.
One thing to note is if I don't point the url to a valid JSON returning url as in first case, I have to provide option dataType:'script'(or JSON).Otherwise it will throw a cross-domain request error.In second case it didn't throw any cross-domain error even if I didn't specify dataType.
Replace your complete callback with success. Success callback executed when ajax request completed successfully.
Also in your dataType use "json" instead of "script"
if you use "script" in dataType it will return like "{\"key\":\"value\"}".
if you use "json" in dataType it will return like {"key":"value"}.
I'm trying to read a html file using jQuery.get() without success.
I've put a breakpoint on 'var x = 1' but the execution does not reach that point.
The javascript function is:
function do_about()
{
$.get('mytest/index.html', function(data) {
var x = 1;
}).error(function() { alert("error"); });
};
The alert("error") is raised, however (as I am "dummy" in javascript) I don't know how to catch the error message correctly. The jQuery.get() documentation says:
If a request with jQuery.get() returns an error code, it will fail silently unless the script has also called the global .ajaxError() method or. As of jQuery 1.5, the .error() method of the jqXHR object returned by jQuery.get() is also available for error handling.
There is no remote web server, it is local.My Apache (on Ubuntu 11.04) is running and the file /etc/apache2/sites-available/default there is the following entry for the desired file:
Alias /mytest /home/miro/mytest
<Directory "/home/miro/mytest">
AllowOverride All
Allow from all
</Directory>
In Firefox if I call the url http://localhost/mytest/index.html the page will be displayed without problem.
The mytest/index.html is:
<html><body><h1>Test page</h1></body></html>
I tried $.get('http://localhost/mytest/index.html', function(data) {....
and it did not work.
Does anyone have any idea how to solve this?
Is there any other way to read a html using just javascript (no jQuery)? I just want to get some tag values from that html ?
Looks like it could be a path issue try setting your path relative to the domain root like so:
$.get('/mytest/index.html', function(data) {
var x = 1;
});
Can you console log the errors you receive? so we know if its a server issue or some redirects.
error(jqXHR, textStatus, errorThrown)
http://api.jquery.com/jQuery.ajax/
In jQuery, parsing a bunch of points to draw on a HTML5 canvas. Encountered a strange bug -- but my knowledge of this area is pretty limited so perhaps there's a good explanation.
This works every time:
var json = $.getJSON( "../models/" + id + ".json");
alert("fjkld");
paths = JSON.parse(json.responseText);
This fails every time:
var json = $.getJSON( "../models/" + id + ".json");
paths = JSON.parse(json.responseText);
Anyone have any idea why? Is it because the alert pauses something while the parser 'catches up'? That doesn't make intuitive sense to me but it's the only explanation.
Actually I know this is correct because if I hit "OK" on the alert really fast it fails again.
Can someone please explain to me why this is happening?
getJSON is asynchronous. This means that it returns immediately, before the XMLHTTPRequest has completed. Because alert is a blocking function, all code is halted until you press OK. If you take a while, the request has completed, so responseText is available; if alert isn't present, or you press OK very quickly, the HTTP request has not completed, so the text has not completed.
You need to use a callback function instead: this is a function that will be executed when the AJAX request is complete:
$.getJSON( "../models/" + id + ".json", function(paths) {
// access paths here
});
See the documentation for $.getJSON.
This happens because the getJSON call is asynchronous. Once the call to getJSON is complete all you know is that the browser has kicked off the request for the file. You do not know if the request has been completed or not. Sure, the call to the alert function gives the browser enough time (usually) to get the full file, but as you discovered sometimes that's not true.
Far better is to supply a callback that will be called once the file has been downloaded:
$.getJSON(fileName, function(data) {
paths = JSON.parse(data);
..do something with paths..
});
Although note that paths won't be available until the callback executes.
You need to set up a callback function in the getJSON call to ensure that the response has had time to complete. In the flow of the ajax call the function that generates the getJSON call continues while the getJSON happens. There is no guarantee that the json request has completed when teh JSON.parse() is being called. The proper syntax for the call is :
jQuery.getJSON( "../models/" + id + ".json", function(data, status, xhr){ JSON.parse(data);} )
Check out the api for the getJson call here: http://api.jquery.com/jQuery.getJSON/
Put your logic inside the callback.
$.getJson("../models/" + id + ".json", function(response) {
paths = JSON.pars(response.responseText);
});
Or something like that. As a request API call is an asynchronous call, you have to wait for the server response before you can move forward. That's where callbacks come in. They're called by the asynchronous API when the request is complete. They usually also have success status flags to tell you if your request was successful.
http://api.jquery.com/jQuery.getJSON/