Forcing a JSONP call to convert text response to JSON - javascript

If I've got the following request
$.ajax({
type: "GET",
dataType: "jsonp",
jsonp: "callback",
jsonpCallback: "my_callback",
url: my_https_url,
headers:{"Content-Type":"text/html; charset=utf-8"},
success: function(data) {
eval("json="+data);
}
error: function() {
console.log("fail");
}
});
I'm getting a server response with the 200 status code. The response header says it is sending back text/html as the content-type. However, I know the content is actually formatted JSON data. The problem is the server is not configured to accept JSONP requests (and I can't change it). I am using the JSONP approach for cross-domain-related reasons. The error status I get back is a "parseerror" because it's not recognized as JSON. Is there a way to override the function responsible for parsing the data so that I can force it to be treated as JSON? Possibly using eval()?

If your server is not capable of creating a JSONP formatted response and you have to use JSONP because of same-origin restrictions, then you're just plain out of luck. A JSONP formatted response is in the form of a executable script that calls the specified callback.
You generally can't fetch JSON from a different origin. You either need JSONP or you need a modern browser with a server configured to allow cross origin requests. If you can't configure the server to allow cross origin requests, then you need the server to create JSONP. If it won't do that, then you can't get the data from it. JSONP is a work-around for cross-origin requests and it REQUIRES server cooperation to create a JSONP formatted structure for the response.
If you are getting JSONP structure from the server and jQuery is getting a parse error when trying to parse the response as JSON, then that's because whatever the server is sending is not legal JSON inside of the JSONP structure. The fact that you're getting a parse error would mean that jQuery is trying to parse it as JSON and is getting an error when trying to do so. If that's the case, then you have two choices:
Fix the data the server is sending to be 100% legal JSON.
Accept the data as text and fix it to be legal JSON or parse it yourself in some manner that accepts it the way it is.
In either case, the first step is probably to console.log() the text that is being sent and understand exactly why it's not being accepted as legal JSON. Then, you'll better know what your options are. If you want help with understanding that, then add the exact server response to your question.

Related

Cross domain AJAX called with JSONP returns plain JSON

I have encountered a problem with an API I want to use. The API returns plain JSON but its a cross domain AJAX call so I have to use jsonp.
$.ajax({
type: "GET",
url: url + query,
contentType: "application/json",
dataType: "jsonp",
success: function(data){
console.log(data);
}
});
The problem is when I change the dataType to "json" an error occurs:
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'X' is therefore not allowed access.
This is because its a cross domain ajax call. But when it is jsonp it says:
Uncaught SyntaxError: Unexpected token :
In other words it does not recognize the json format.
I am using jquery for the ajax call. Any suggestions how to solve this?
Since you dont have access to the server where the API is hosted, you use can a web service utility like CURL to access the API. AJAX calls requires CORS (Cross Origin Resource Sharing) to be enabled on the server where the API is served.
You can call a web service on your local server page via AJAX from where the CURL call will be made and appropriate response returned.
There are several methods of bypassing cross-domain restrictions (CORS, JSONP, Iframe transport, etc.) but all methods have in common that the API server needs to corporate. So if you don’t have privileges on the API server, you cannot come across the cross-domain restrictions.
The only way to make this work would be putting a proxy in front of the API that you can control (the proxy could either live on the same domain or inject the appropriate CORS headers). However, this will affect performance and might also have legal implications.
Regarding JSONP, here’s an excellent explanation of how and why this works:
What is JSONP all about?

Cross Domain Ajax (JSONP) Callback Issue

I have a code where i need to make cross domain requests to get the text/html as response. I've been using the JSONP method and was getting the results (json) before on some other program. When i run the program, console reports an error which is
Uncaught SyntaxError: Unexpected token <
?callback=jQuery17207555819984991103_1414157672145&_=1414157675836"
As you can see it has added an extra parameter value after the callback parameter which is causing an issue. When i see the response in Network tab, its pretty good and exactly what i wanted. I tested it on 4 cross domain links and that extra paramter is coming to all of them.
Following is my code:
$.ajax({
type: 'get',
url: link,
dataType: 'jsonp',
success: function(dataWeGotViaJsonp){
alert(dataWeGotViaJsonp)
var len = dataWeGotViaJsonp.length;
}
});
The links I have passed to it:
http://stackoverflow.com/questions/20944962/data-grid-view-update-edit-and-delete-in-vb-net-windows-form-that-using-multipl
http://www.espncricinfo.com/pakistan-v-australia-2014/engine/match/727927.html
http://pucit.edu.pk/
Response is good but due to that error, success callback isn't being called. Any solutions?
"Uncaught SyntaxError: Unexpected token <" is an indication that the returned data is very likely HTML mark-up and not proper JSONP. In order to return HTML from a JSONP web service, you need something on the server that is wrapping the HTML in proper procedure call syntax. E.g.,
jQuery17207555819984991103_1414157672145 ("<div>... your HTML here ...</div>")
Since the HTML will likely have quote characters in it somewhere, you will need to escape, URL encode, UUEncode, or otherwise convert the HTML text to be an appropriate Javascript string, and then convert it back in the client.
As for the "_=1414157675836", this is being added to ensure the response is not cached. Unless your server's web service is rejecting the request because the "_" parameter is not recognized, this is a red herring. The problem is the bad JSONP syntax coming from the host.

Get HTML of another page in another domain using JavaScript

Right now, I am using curl in PHP to get the HTML source code of some remote web page.
Is there any way I can get the same HTML source code of some cross-domain web page in JavaScript? Any tutorials?
I think you need to know about JSONP to access cross-domain web pages in js
https://stackoverflow.com/questions/tagged/jsonp?sort=votes
Q. How is this any different than issuing an AJAX "GET http://otherdomain.com/page.html" call?
A. The same-origin policy checks the HTTP response headers for AJAX requests to remote domains, and if they don't contain a suitable Access-Control-Allow-Origin header, the request fails.
So, there are two ways to make this work:
If you control the other domain, you can include the following header in the HTTP response:
Access-Control-Allow-Origin: *
(details at MDC)
If you don't, you're stuck implementing a server-side proxy (for example, this simple PHP proxy).
In any case, once you implement one of the two options above, you're left with a simple AJAX call:
$.ajax({
url: "http://mydomain.com/path/to/proxy.php?url="+
encodeURI("http://otherdomain.com/page.html"),
dataType: "text",
success: function(result) {
$("#result").text(result);
}
});
This solution I just found might be of use like the other workarounds...
http://www.ajax-cross-domain.com/

getJSON and invalid label

I am trying to get json data from a url. Url is working ok in FF. I am trying code like this
$.getJSON("http://testsite.com/1234/?callback=?", function(data){
//here i am getting invalid label error**
}
);
When i am trying without callback=? i am getting empty data
$.getJSON("http://testsite.com/1234/", function(data){
//here i am data = ""
}
);
Whats going wrong?
It looks like the site you're fetching from doesn't support JSONP, with this URL:
http://testsite.com/1234/?callback=?
It's trying to use JSONP, but the server is returning a plain JSON response (not wrapped in a function).
With this URL:
http://testsite.com/1234/
It's not trying JSONP at all, and being blocked by the same-origin policy.
To fetch data from a remote domain, it needs to support JSONP so it can be grabbed with a GET request, so you'll need to either add support to that domain, or proxy the request through your own.

Basic Authentication with jQuery.ajax request and jsonp

I have some local html/js files with which I'd like to invoke some remote servers via https and eventually use Basic Authentication for the request.
I am encountering two problems. First is that if I don't specify 'jsonp' for the dataType, jQuery.ajax() request returns the error:
Access to restricted URI denied code:
1012
Are my requests considered cross-domain because my main work file is stored locally, but retrieving data from a server elsewhere?
So fine, I update the call so it now looks like:
$.ajax({
url: myServerUrl,
type: "GET",
dataType: "jsonp", // considered a cross domain Ajax request if not specified
username: myUsername,
password: myPassword,
success: function(result)
{
// success handling
},
error: function(req, status, errThrown){
// error handling
}
})
Because I need to use Basic Authentication, I'm passing in the username/password but if I monitor the request, I don't see it being set and additionally, the server sends an error response since it doesn't have the expected info.
Additionally, because I have jsonp set, beforeSend won't get invoked.
How do I pass along the credentials using Basic Authentication for this request?
The short version is you can't do this. Your suspicions are correct, because you're local and these files are remote, you can't access them, you're being blocked by the same-origin policy. The work-around for that is JSONP, but that really doesn't seem to apply to your situation...
JSONP works differently, it's a GET request via a <script> tag include to get the file, so you're not sending special headers or anything.
You'll need to proxy the request through the server you're on (the domain of where this script is running) or another proxy option, but going from the client to another domain is blocked, mainly for security reasons.
Try doing http://user:password#restservice. This mimics a basic-auth request.
I think you'll have to add a server proxy of some sort. JSONP is just a particular way to use a script tag. Thus, it doesn't allow setting arbitrary headers. And of course, you can't do a cross-origin XHR.

Categories

Resources