I'm trying to get a JSONP AJAX request to go through, but I'm having problems figuring out why it's not working. Right now I have this call
$.getJSON(server_path+"formproxy.php?"+$(form).serialize()+"&action="+form.action+"&callback=?", function(data, status, xhr) {
alert(data);
});
but when I run the script nothing seems to happen. The best I can figure is that the jsonp request is running into an error, but because it's a jsonp request it's not actually reporting the error, which is greatly hindering my debugging.
I've played around with
$.ajaxSetup({
"error":function() {
alert("error");
}
});
and
$(document).ajaxError(function(e, xhr, settings, exception) {
alert('failed');
});
but I can't get either of them to trigger.
I've output the target url to the console, namely
server_path+"formproxy.php?"+$(form).serialize()+"&action="+form.action+"&callback=?"
I can visit the outputted url and see that it is working and outputs ?({"result":"success"}) which seems right to me.
Looking at the console in Chrome, it doesn't even show the XHR, but I'm at least sure the $.getJSON() code is being reached thanks to breakpoints.
I should finally note that I'm not even concerned with getting data back from the AJAX call. I just need to send form data cross domain and let the formproxy.php script process it.
Any thoughts on why this may not be working or techniques to help me see what's happening inside would be much appreciated.
Have you tried looking at the Network Panel in Chrome developer tools? It will show you all the http requests/responses that are being made on your page. That way you can tell for sure whether the the getJSON call is making a request to the server, and what the server response is (if any).
You can also use the Net panel in Firebug for this.
Related
I am new in javascript and I have some trouble to complete an activity...
I need working, in the client side, with the information uploaded in a "special" server like this:
http://www.uninorte.edu.co/documents/71051/11558879/ExampleData.json/0a635cdd-ccdd-4a1c-8c88-b53bea431458
I want load it in main memory, without the browser show the explicit download.
I try to use some solutions, but really I have no idea how to proceed to achieve it.
... Beforehand thank you very much
(I am not a native english speaker, I apologize if I do not write well)
[Solved]
I decided, for the moment, use the Whatever Origin services, that returns me something I can read with $.getJSON "Without download" the file.
Resulted:
<script type="text/javascript">
$.getJSON('http://whateverorigin.org/get?url=' + "http://www.uninorte.edu.co/documents/71051/11558879/ExampleData.json/0a635cdd-ccdd-4a1c-8c88-b53bea431458" + '&callback=?', function(data){
alert(data.contents);
});
</script>
Thank you for yours responses, really you gave me lights in order to solve it
Regarding silent part
Your browser is always aware of the network requests which are made from JS. Therefore, the user can always see all the requests and responses by opening developer tools.
Now coming to loading a remote json to the memory in the client
Since you mentioned you are relatively a newbie in JS, I am going to cover the very basic, so please bear with me if you already know it
You need to make an ajax call using an XMLHttpRequest as shown here
However, most people use some library like jQuery while working to abstract checking state of the request and other trivial tasks. This results in making an ajax call as simple as calling a method and providing a callback method to process the response.
$.ajax({
url: '/path/to/file',
type: 'default GET (Other values: POST)',
dataType: 'default: Intelligent Guess (Other values: xml, json, script, or html)',
data: {param1: 'value1'},
})
.done(function() {
console.log("success");
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
You may find the example at below link.
http://api.jquery.com/jquery.getjson/
P.S.: Due the less reputation points, I can neither post any supporting images nor more than two links.
So basically I want to be able to tell the difference between when an ajax call failed naturally (eg 404, server down, etc etc) and when it has been canceled by the browser, eg when a user closes a tab or hits f5.
I listen for failed ajax attempts and display an error dialogue, describing the error when ajax fails. However when someone presses f5 (especially noticeable in firefox), the error callback of not yet complete ajax calls occur, then displays errors and while the page loads the user is stuck looking at the error dialogue until the whole page is torn down by the browser (which is not nice to look at, when in reality it doesn't matter that the ajax call failed because the whole web app is being reloaded).
I have examined the xmlHttp request object, and nothing stands out to me as a way to tell the two situations apart. I have also tried adding a delay, but this hasn't really worked so well either. So I am just wondering if it is possible, and if so how?
I found a work-around. If you set a window.onbeforeunload handler, that will get called before the ajax error. So, if you set a flag that the document is unloading, you can check that flag before showing your ajax error and skip the error if the document is in the process of unloading.
Works for me with jQuery 1.11 in Firefox, Chrome and IE.
You can see it work here: http://jsfiddle.net/jfriend00/G3wat/
var unloading = false;
$(window).on("beforeunload", function() {
unloading = true;
});
Then, in your ajax calls:
error: function(jqXHR, status, err) {
if (!unloading) {
alert("Error status " + status);
}
And, as you found, it appears that jQuery 2.x does this for you.
I can't seem to get a CSV stock file from yahoo finance to "success"-fully load. I've tested different callbacks and suggestions from other questions, but none of them seem to be working - most of them don't output anything.
$(document).ready(function(){
$.ajax({
url:"http://finance.yahoo.com/d/quotes.csv?s=XOM&f=sn",
dataType: 'jsonp',
success: function(data) {
alert('good');
},
error: function(data) {
alert(data);
}
});
});
This code alerts [object Object] (the "error" callback), however the CSV file can be seen in the network panel successfully. The data in the network panel reads "XOM, Exxon Mobile Corpo" as expected (so it did load).
I guess the real question is how can I get that data which I know is loaded. I just want to alert it for now... just want to see it on the page. I've spent a countless number of hours fiddling with this and it just doesn't work.
Here's a jsfiddle:
http://jsfiddle.net/V94sQ/3/
You can not request CSV files from another domain unless they support CORS. Since you do not control yahoo you are out of luck there. You would need to use a proxy [request it from your own server, backend makes the get request] or a service that can make it into a jsonp request.
I want to get some google search results in my website,I know I can get with curl,php but its limited daily for same ip adress. and I dont want to use google search api because its also has limit. So I think I can get with jquery ajax but I m a bit new on that,I am fed up with this problem.
here is my code, its will be always error because of jsonp format, but maybe still there is a way for catch html source code. I see source code comes to my browser but I cant take it like object.I tryed xhr.responseText etc but its gives also SyntaxError, still I cant get.
if you can suggest to me any other ways or if you have any idea with below code please share with me.
Thanks before now
$.ajax({
url:"http://www.google.com.tr/search?q=ercan",
dataType: 'jsonp',
success:function(json){
// I know its wont never succes, because google gives source in html format
alert("Success");
},
error:function(xhr){
//I want to get source code html here, but its giving always parse end syntax error I cant get it
console.log(xhr);
},
});
I am afraid that your only choices are to use the API or server side bridge script. You cannot do cross domain AJAX calls if the server doesn't support JSONP or CORS. There's also a commercial version of the API which allows you to increase the limit of requests you could send.
Recently I started facing issue with one of my scripts that loads a json response from the server. I am using jquery.ajax() to make an ajax call. The code snippet is so -
var request = $.ajax({
url: "script.jsp",
type: "POST",
dataType: "json",
success: function(response) {
console.log(response);
},
error: function(response, error) {
console.log(response, error);
}
});
As I mentioned this script worked as recent as yesterday. I have not made any changes to either the server-side code or the front-end code. The json response is a bit large ~1 MB in size. But I validated the json output using -
python -mjson.tool < output.json
It prints out properly. Curious thing is FF & Chrome handle it differently.
In FF, I open firebug and see the ajax request being made. I see that the request is served in around 300ms but the loading wheel next to the link in the console is still animating for aorund 20 seconds. And after that the json response is properly processed and the result can be seen on the page. In IE also similar behavior, proper processing of the json after 20 seconds.
In Chrome, nothing happens for around 20 seconds after which I see an error in the console saying either "error": undefined or Failed to load resource. Alternatively it also prints the below stacktrace -
POST script.jsp
f.support.ajax.f.ajaxTransport.sendjquery.min.js:4
f.extend.ajaxjquery.min.js:4
DataTableWidget.extend._fetchBuildingBlockItemsPermissionBBItemsWidget.js:91
(anonymous function)PermissionBBItemsWidget.js:83
e.extend.eachjquery.min.js:2
DataTableWidget.extend._loadDataPermissionBBItemsWidget.js:82
DataTableWidget.extend.showPermissionBBItemsWidget.js:15
(anonymous function)permission-building-blocks.html:451
xLAB.min.js:5
ULAB.min.js:5
jLAB.min.js:5
ILAB.min.js:5
eLAB.min.js:5
a.onload.a.onreadystatechange
I dont understand this weird behavior in different browsers.
So in essence I made sure that -
Server side code returns the response fast. I put in some debug statements and saw the server log. None of the response form server take more than 500ms.
Made sure than json is properly validated. The fact that after 20 secs it is processed in both IE & FF without any issues is a proof of that. In addition to use of python's json.tool.
Set the dataType to json
So any pointers on the issue will be a great help. Thanks.
UPDATE
One more curious thing I noticed. While the request is being processed and I hit the refresh button even within 3 seconds of the original request, the process immediately completes. As in I see changes in the view of course fraction of a second later the page is wiped out due to refresh event.
UPDATE 2
I have noticed that after I slice up my big response by alphabets. The issue of looong response happens in only certain responses. I ran this split long response files through http://jsonformatter.curiousconcept.com/#jsonformatter and although it immediately returns saying that the josn is valid, it takes 20+ seconds to actually pretty print the response. I think the problem is happening due to certain characters like \u0026 so with this added info, how to resolve the problem? Here is the snipet of the problematic json.
I figured out the problem. The issue was with how the server-side code provided the client-side code JavaScript with the json string.
I was using a legacy method in our code base which actually rendered the already json string in a jsp page before passing it to the client. This was somehow screwing up the response. Also response type was text/html because of this.
As soon as I switched the response to be of actual application/json MIME type stream, everything was fine.
does your JSON have line feeds? Do you have Firebug or something line that open? The browser may be loading the JSON just fine, it might be your debugging tools crapping out. I Recall having issues before with inspecting certain JSON strings with certain tools just because it didn't have line feeds (or line feeds as understood in Windows). I'm wondering if the fact your logging the whole thing to the console doesn't have something to do with it.