Download JSON file via JavaScript/JQuery - HTTP-Status Ok - JQuery Error - javascript

I've got the following problem: I need to download a JSON file from an API via JQuery / JavaScript. In theory this should be quite basic.
I tried $.ajax and all of its siblings like $.get or $.getJSON. I alway get an 200 OK but my Firebug reports an error. Printing the error just says: "error" - so not that helful.
I read that maybe the JSON file is corrupt. So I tried it with a plain text file (*.txt). Same result.
The JSON file is valid, I check it against a validator.
I also tried ContentType and dateType and experimented with json and jsonp...
I basically used something like this (with a million variations for testing purposes):
$.ajax({
url: 'http://www.myurl.com/api/v1/myfile.json',
...
success: function(data) {
console.log(data);
},
error: function(error) {
console.log(error.statusText);
}
});
Am I missing something important here? It's really odd that nothing seems to change the behavior of the AJAX-call.
In fact I don't really need AJAX because I need to grab the JSON file when loading the page...
And the JSON file is not on the same domain as the AJAX caller.

Is that URL located on the same server you're trying to get the data from?
If not, you ran into a cross-domain request, which can only be handled using JSONP. So, the JSON file itself must be compatible with JSONP format, otherwise jQuery won't be able to process it (even if you provide a 'jsonp' dataType).
P.S.: Firebug will always show response code 200 but give an empty response body for such requests

Try in this way by disabling security
$.ajax( {
type : 'GET',
contentType : "application/json; charset=utf-8",
url : surl, \\specify your url
async : false,
dataType : 'json',
headers : {
Accept : "application/json",
"Access-Control-Allow-Origin" : "*"
},
crossDomain : true,
success : SucceedFunc,
error : function(data, textStatus, errorThrown) {
console.log("error" + ' ' + JSON.stringify(data) + ' ' + textStatus + ' ' + errorThrown);
}
});
function SucceedFunc(data) {
alert("success");
}
}

Did you try to catch the error the correct way?
$.ajax({
url: 'http://www.myurl.com/api/v1/myfile.json',
success: function(data) {
console.log(data);
},
error: function(error) {
console.log(error.message);
}
});

If you are using chrome go to cmd prompt and run the chrome by disabling the security. You can disable security using pathwhere_chrome_is_located\chrome.exe --disable-web-security
and run the html page. I think this may help you.

Related

Can AJAX read files with custom extension?

I have files with extensions .cst in my localhost server. I was thinking if AJAX can load them. So my question is can AJAX load files with custom extension ? If yes, how ? If no, any alternative such that we shall get the content of the file on page load ?
My ajax call for loading the file load.cst :
$.get("load.cst", function(data) {
console.log(data)
});
If the file is plain text then you can easily fetch it with jQuery. Setting data type to text will ensure jQuery does not try to process it as something else. Adding an error handler will help catch errors.
var request = $.ajax({
url: "load.cst",
method: "GET",
dataType: "text"
});
request.done(function( msg ) {
console.log(msg);
});
request.fail(function( jqXHR, textStatus ) {
console.error( "Request failed: ", textStatus );
});

Cross domain request using jquery JSONP bult in

I have to implement a click button that downloads library (zip file) from non-local server. The task is simple: if you hit the URL you will have the zip file downloaded. I read in the internet that there is a restriction about cross-domain request, but there is also a workaround for that. So in the code below I applied one of the workarounds using jquery.
I tried ti simulate that click via this code:
$.ajax({
type: "GET",
url: "http://www.touchwand.com/wp-content/uploads/2018/04/Icons-and-backgrounds.zip",
dataType: 'jsonp',
success: function(data){
console.log(data);
},
error: function(xhr, status, err) {
console.log(xhr);
console.log(status);
console.log(err);
}
});
});
Gues what. Doesnt work. The file is not downloaded.
I get this error in the console:
Uncaught SyntaxError: Invalid or unexpected token
It is may be due to the returned response format is not JSON. But please tell me hot make it work?
* EDIT *
Changed the code to report errors.
The result is:
The request status is 200

JSONP Parse Error with valid JSON Output

I am calling a Cross Domain AJAX Request using JSONP. Now, i am able to make it work using CORS. But, i want to know why it is not happening with JSONP. I looked at other threads with similar problem but couldnt figure out why it is not working in my case.
Here is the code:
$.ajax({
type: "GET",
url: http://XXXX:8000/sap/bc/test_rest/jsonp_test?mode=S&ticket=123,
dataType: "jsonp",
jsonp: false,
jsonpCallback: "myJsonMethod",
success: function (data) {
alert(data);
},
error: function (httpReq, status, exception) {
alert(status + " " + exception);
}
});
Now, this calls my server, the data is populated and then i get an alert "parse error myJSONMethod was not called" on a callback URL http://xxxx:8000/sap/bc/test_rest/jsonp_test?mode=S&ticket=123&_=1470322282936
Additionally, in the console i get the error as Uncaught SyntaxError: Unexpected token :
The response structure is:
{"ROOT":{"CONTRACT":"40002356","ITEM":"000010","KUNNR":"0000004676","NAME":"REALTY EXECUTIVES","NET_PRICE":19.95,"GROSS_PRICE":19.95,"MATNR":"144","SQFEET":""}}
When i run this JSON Output on jsonlint it says it is a valid JSON. I don't know where the JSON is getting messed up.
Your data must be like this to be valid for JSONP:
myJsonMethod({"ROOT":{"CONTRACT":"40002356","ITEM":"000010","KUNNR":"0000004676","NAME":"REALTY EXECUTIVES","NET_PRICE":19.95,"GROSS_PRICE":19.95,"MATNR":"144","SQFEET":""}});
the responsetext must be valid js code and it will run immediately when the response is over.So if you write your code
{"ROOT":{"CONTRACT":"40002356","ITEM":"000010","KUNNR":"0000004676","NAME":"REALTY
EXECUTIVES","NET_PRICE":19.95,"GROSS_PRICE":19.95,"MATNR":"144","SQFEET":""}}
in a <script> tag,the console will throw an err like that

Ajax call fails in Chrome, but works in Firefox

Any idea why the following Ajax call fails in Chrome, but not Firefox?
$.ajax({
type: "GET",
contentType: "text/csv; charset=utf-8",
dataType: "text",
cache: false,
url: "http://127.0.0.1:8080/param1/param2?param3=csv&otherParams=type1,type2,type3"
})
.done(function(data) {
console.debug("Data received from ajax call: " + data);
})
.fail(function(jqXHR, textStatus, errorThrown) {
console.error("Data request failed (" + textStatus + "): " + errorThrown);
console.debug(jqXHR.responseText);
});
The URL that I am calling should return the data in csv format. I'm using jQuery 1.8.2. This works in Firefox, but not Chrome for some reason. The error message that I print out is:
Data request failed (text/csv): text/csv
Interestingly, in Chrome I can see the data returned in the jqXHR.responseText, so I can't figure out why it's throwing an error. I assume it has something to do with my not specifying the csv format properly, but I thought setting the dataType or contentType would fix that. What am I missing?
I realize this is a common problem, but in spite of my Googling and searching around Stack Overflow, I have been unable to find a solution that fixes this problem for me. All the suggestions I've found have said to set the contentType, the dataType, or the cache to false. As you can see, none of these solutions has worked for me. Your help is greatly appreciated!

Dojo xhrGet only returning null

The following Dojo code's load callback returns null. There shouldn't be any problem because jQuery's ajax works fine. What am I missing here?
Dojo version - doesn't work
dojo.xhrGet({
url:"http://localhost:11039/",
handleAs:"json",
load: function(data){
console.log(data); // Prints null
},
error: function(err){
console.log('Error: ' + err);
}
});
jQuery version - works
$.ajax({
url:"http://localhost:11039/",
type: 'GET',
dataType: 'json',
success: function(res){
console.log(res) // Prints some JSON
},
error: function(err){
console.log('ERROR: ' + err);
}
});
Looking at Firebugs net tab I notice that the jQuery version is in fact sending a GET request:
GET localhost:11039 200OK localhost:11039 62.8KB
while the Dojo version... "OPTIONS"?
OPTIONS localhost:11039 200OK localhost:11039 62.8KB
Additional Details:
I get the same result in Ffox, Chrome and Safari.
Dojo sending an OPTIONS request usually means dojo considers it a cross-domain request.
The OPTIONS request is checking for the Access-Control-Allow-Origin header to see if the request should be performed, even though it is considered cross-domain.
See https://developer.mozilla.org/En/HTTP_Access_Control for more details

Categories

Resources