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

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?

Related

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

How to get a json response from yaler

I create an account with yaler, to comunicate with my arduino yun. It works fine, and i'm able to switch on and off my leds.
Then i created a web page, with a button that calls an ajax function with GET method to yaler (yaler web server accept REST style on the URL)
$.ajax({
url: "http://RELAY_DOMAIN.try.yaler.net/arduino/digital/13/1",
dataType: "json",
success: function(msg){
var jsonStr = msg;
},
error: function(err){
alert(err.responseText);
}
});
This code seem to work fine, infact the led switches off and on, but i expect a json response in success function (msg) like this:
{
"command":"digital",
"pin":13,
"value":1,
"action":"write"
}
But i get an error (error function). I also tried to alert the err.responseText, but it is undefined....
How could i solve the issue? Any suggestions???
Thanks in advance....
If the Web page containing the above Ajax request is served from a different origin, you'll have to work around the same origin policy of your Web browser.
There are two ways to do this (based on http://forum.arduino.cc/index.php?topic=304804):
CORS, i.e. adding the header Access-Control-Allow-Origin: * to the Yun Web service
JSONP, i.e. getting the Yun to serve an additional JS function if requested by the Ajax call with a query parameter ?callback=?
CORS can probably be configured in the OpenWRT part of the Yun, while JSONP could be added to the Brige.ino code (which you seem to be using).
I had the same problem. I used JSONP to solve it. JSONP is JSON with padding. Basically means you send the JSON data with a sort of wrapper.
Instead of just the data you have to send a Java Script function and this is allowed by the internet.
So instead of your response being :
{"command":"digital","pin":13,"value":0,"action":"write"}
It should be:
showResult({command:"analog",pin:13,value:0,action:"write"});
I changed the yunYaler.ino to do this.
So for the html :
var url = 'http://try.yaler.net/realy-domain/analog/13/210';
$.ajax({
type: 'GET',
url: url,
async: false,
jsonpCallback: 'showResult',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
console.dir(json.action);
},
error: function(e) {
console.log(e.message);
}
});
};
function showResult(show)
{
var str = "command = "+show.command;// you can do the others the same way.
alert (str);
}
My JSON is wrapped with a showResult() so its made JSONP and its the function I called in the callback.
Hope this helps. If CORS worked for you. Could you please put up how it worked here.

JQuery ajax GET request to URL fails although HTTP status is 200 OK

I apologize if this question has already been answered.
I am trying to retrieve data from a REST web service that exposes a JSON interface using jQuery .ajax call.
When I call the service using the URL, the jQuery call fails although I get a HTTP status code 200 OK.
When I copy the response into a file on the filesystem and retrieve this, the same call works.
Both the file I am accessing and the web service I am calling are on the same machine.
Some notes on the url used in the code below:
Using:
url: "http://localhost:9090/app/user/861",
the call fails, goes into .fail on all browsers.
The URL itself returns the json on all browsers:
{
"userid": 861,
"employeeno": "123",
"jobdesc": "Developer",
"firstname": "Jasper",
"lastname": "Fitussi"
}
when using "test.json" in the local filesystem following is the behavior:
url: "ajax/test.json",
On Firefox, the call executes, goes into .done and displays the result on page.
On Chrome, the call fails with status 404 and the following message -
"No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access."
I tried different combinations changing dataType:"jsonp", adding a ?callback=? to the end of the URL, and enclosing the data in the test.json with a '(' and a ')' without luck.
Please understand I am new to UI programming, javascript and jQuery.
Please help with what I am doing wrong. Here's the javascript:
<script src="http://code.jquery.com/jquery-1.10.2.js" type="text/javascript">
</script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "GET",
url:"ajax/test.json",
// the following commented call fails, goes into .fail
// url:"http://localhost:9090/app/user/861",
contentType: "application/json",
accepts: "application/json",
dataType: "json"
})
.done(function(data) {
alert("Success");
console.log(data);
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>");
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
})
.fail(function(data) {
console.log(data);
alert("Failed");
})
.always(function() {
alert("In Always");
});
});
</script>
The following is the output when I paste the url into the browser (also the contents of ajax/test.json):
{
"userid": 861,
"employeeno": "123",
"jobdesc": "Developer",
"firstname": "Jasper",
"lastname": "Fitussi"
}
Your problem is not about UI programming, it's about the security model of modern browsers :p
Access-Control-Allow-Origin errors occurs when you call a webservice (ie: load a JSON file) from a domain that is different from the one hosting your HTML page.
In your case, you are opening the html file from your hard drive (file:///) and calling a webservice on localhost.
This is a security feature in all modern browsers that forbid getting data from a foreign webservice without the webservice owners authorizing you (or everyone, wildcards are allowed) to call it.
I recommend reading the following guide from MDN, so that you understand WHY you are having this problem.
It will then be easy to resolve
https://developer.mozilla.org/en/docs/HTTP/Access_control_CORS
If you control the source code of the webservice, or the webserver hosting it, you need to add Access-Control-Allow-Origin HTTP headers.
Do you make your ajax call using Apache on wamp, lamp, xampp or mamp or not? I think you work directly using some files lets say on your desktop and not from the www file of wamp. If the browser sends a correct url then the backend responds great, your frontend code seems fine so i think chrome complains about your not using localhost. Am i right? Whats your local development setup?
If it's a local file on the client-side, use file:/// to prefix the URL:
url: 'file:///ajax/test.json'
The third / in file:/// indicates:
As a special case, can be the string "localhost" or the empty
string; this is interpreted as `the machine from which the URL is
being interpreted'.
3.10
Reference here
Download a tool called fiddler, from http://fiddler2.com/ great way to debug web requests and to see why they are failing.
This will help you narrow down the issue you are experiencing and we can help you further because currently its all guess work.
I had the same issue, all worked fine in I.E and FireFox, a had one ajax call to a rest service using jsonp and it worked fine in chrome, however when I tried to load a file using jsonp I got the cross domain error. In short i had to add "file:" to my file path in the url
$.ajax({
type : 'GET',
url : 'file:jsondata/rain_acc_data.json',
dataType : 'jsonp',
jsonpCallback : "jsoncallback",
success : function(data) {
aler('ok');
},
error : function(jqXHR, status) {
alert("Failed to load list" + status + jqXHR);
}
});
this worked for me, make sure to wrap your json in the file with jsoncallback("your jason here");

jsonp and REST GET call

I have two projects, an older one, which works, and a newer one. Both projects have to make a cross-domain call.
On the older project, I use jsonp to talk to the server and get a response, such as:
var myUrl = "http://www.myserver.whatever/somepage.php";
jsonp(myUrl, "ajaxResponse");
function ajaxResponse(data) { alert(data.response); }
In my new totally unrelated project, I have to talk to a service. The web page is a local file on the client talking to a CentOS daemon written by a software vendor. I can communicate to the daemon through REST GET calls. An example of a call would be, which works, as I entered the following in a Mozilla Firefox browser window:
localhost:8080/mfds/info
I thought that the easiest way to communicate to the daemon would be through jsonp, like I did previously, so:
var myUrl = "http://localhost:8080/mfds/info";
jsonp(myUrl, "ajaxResponse2");
function ajaxResponse2(data) { alert(data.response); }
Sadly, I never get to the ajaxResponse2() function. What am I doing wrong? Is jsonp() not a REST GET call? How do I fix the code?
I am using:
<script type="text/javascript" src="js/jsonpCrossDomain.js"></script>
to load the jsonp script. As mentioned earlier, if I use the URL associated with my old project, the code works, just not with localhost:8080:/mfds/info, which works nicely in a browser. The daemon service returns html code.
UPDATE:
Based on the comment below, I did not realize that jsonp has to be on both sides. I originally tried the following code, but this code threw a cross domain error (or so I think, actual error below), which led me to try the JSONP call, but I cannot use that either.
$.ajax({
url: 'localhost:8080/mfds/info',
type: "GET",
dataType: "html",
error: function (error)
{
alert(JSON.stringify(error));
},
complete: function (data_response)
{
alert(data_response.responseText);
},
success: function (data)
{
alert(data);
}
});
Error message from the $.ajax call:
{"readyState":0,"status":0,"statusText":"[Exception... \"\" nsresult: \"0x805e0006 ()\" location:\"js frame ::file:///home/user/Documents/myproejct/js/jquery-2.0.3.min.js :: :: line 6\" data: no]"}

Ajax Webapi Post request for crossdomain in IE8

I am trying to access a WebAPI (in the same server but different IP). It works like a charm in IE 10 . But in IE 8 it goes worse. I have included $.support.cors=true and also included the jQuery.XDomainRequest.js which I got from
https://github.com/MoonScript/jQuery-ajaxTransport-DomainRequest/blob/master/jQuery.XDomainRequest.js
For the GET request it is working, but for the post its throwing out error. I learned that for POSt content type should be text/plain.
I tried to send my data as a plain text, probably the server is not parsing it properly.
I also tried jsonp as well, but didn't work
I am putting down my webapi call . Please suggest on how can I get this working. Thanks a lot .
function Authenticate() {
var UserInfoRequest = {
Email: $("#txtEmail").val(), SubDomain: subDomainName
};
//UserInfoRequest ="Email="+$("#txtEmail").val()+"&SubDomain="+subDomainName;
$.ajax({
url: defaultAPIurl + "Login/UserExistOrDualRole" ,
type: "POST",
dataType: 'json',
data: UserInfoRequest ,
success: function (data) {
//do something
},
error: function (data) {
Showerror();
return;
}
});
return false;
}
ASP.NET WEB API support CROS need extra library. Check this post:CORS support for ASP.NET Web API
Modified your project as this post written,it's will be working.
tips:The two library at their NightBuild Nuget server when I used it.

Categories

Resources