Cross domain request using jquery JSONP bult in - javascript

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

Related

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

How do I exchange data via JSONP using jQuery with Safari?

I use jQuery to exchange data using JSONP with a python server, which works very fine, e.g. in Chrome.
But in Safari it does not work. Looking in the Safari console I get the error "[Error] Failed to load resource: Die Netzwerkverbindung wurde unterbrochen. (here, line 0)". So there seems to be a network error in Safari. Looking at the server side I can see, that the request reaches the server. There it is processed in a right way and a reply is generated. But the server's reply then can't be processed in Safari.
<script src="jquery.js"></script>
<script src="jquery.mobile-1.4.5.js"></script>
$.ajax({
url : "http://127.0.0.1:8888/url/here?callback=?",
data: {request: "get_text", value: " "},
dataType: 'jsonp',
beforeSend: setHeader,
success: function(data){
console.log(data)
$("#page_content").html(data.reply);
},
error: function (request, status, error) {
console.log(error );
}
});
function setHeader(xhr) {
xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
xhr.setRequestHeader("Access-Control-Allow-Headers", "X-Requested-With");
}
I googled a lot and tried several implementations. I also tried to change the IP with the hostname. I also added the setHeader function, but that did not solve the problem, either.
How can I exchange data with JSONP (with jQuery or even with Java Script in general) in Safari? Does anybody know a working implementation?

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

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.

Jquery cross site Ajax call with 302 success data undefined with datatype script otherwise return error

I'm using JQuery 1.7.2, trying to do a cross site Ajax request which should return a html page via 4 redirects.
Not my ideal world with all those redirects, but it's part of the specification.
Now, using the following code:
$.ajax({
type: "GET",
url: myUrl,
dataType: "script",
success: function(data) {
alert("success :"+ data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert("revoke: "+textStatus + ' / ' + errorThrown+"/"+jqXHR.status);
},
complete: function(jqXHR, textStatus){
alert("complete : "+jqXHR.statusText + ": "+jqXHR.readyState);
}
});
I can see in Firebug/Safari Developer Tools, that all the redirects work (e.g. returns a 302 status with a Location header).
Then the strange thing happens: At the last page, which returns a 200 status, my script ends and I try to view the data coming back. But the output is just "Undefined".
I agree on that I should not expect a script datatype when trying to get a html page, but when I tried with all the other datatypes (as defined in the jquery ajax page), the error handler is envoked and the status code is 0. All the while, in Safari DT, the status after the first redirect is just set as "(canceled)" (all the while the request just for the second redirect page just hangs in Firebug - but I'm just guessing that it has to do with their different implementation).
When I receive a 200 status, I can see in the debuggers that the last page has a size of some 18kb, which means that there should be some sort of data in it.
what to do?
You can't redirect with AJAX, you can only send and get data to and from the server.
For a redirection you have to use a "regular" HTTP request.
It can also be done with javascript window.location = myUrl

how to get error message of failed ajax

I want to consume a webService which I get JSON Data from
$.ajax({
type: 'GET',
contentType: 'application/json',
dataType: 'JSON-P',
//the url shows the correct JSON Data when I copy the URL in my browser
url: 'http://url.com',
success: function(data){
console.log(data);
alert(data);
},
error: function(xhr, testStatus, error){console.log("Error occured: "+error+" "+xhr+" "+testStatus)}
})
In Firefox, It calls back with the error function, but I dont know what the problem is, it would be great to know the error message but my approach doesnt work.
thanks in advance
edit: In Chrome I get the following error:
Origin null is not allowed by Access-Control-Allow-Origin.
edit: It´s solved, the problem was indeed that json doesnt work cross site, and the data was not "jsonp-conform" (it had to set a function(json data...))arround the json data. This could be done by changing the url at the end "_&jsonp=successCallback. Sorry for bothering you
I think there was a JSON object syntax error. Check your JSON object syntax error with jsonlint.com.
Are you getting this error locally?
Try it on a server and if it doesn't work: XmlHttpRequest error: Origin null is not allowed by Access-Control-Allow-Origin

Categories

Resources