I am trying to write some simple Javascript to load a JSON payload from a URL.
I know I have CORS issues, and for the moment I'm fine with that.
I can disable chrome's check.
The problem I have is that I get back a 200 OK response, but also an error and I don't understand why.
var urlAddress = "https://light-ratio-149809.appspot.com/ESI-OrgUnitService?jsoncallback=?";
$.getJSON(urlAddress, {
format: "json"
})
.always(function( jqXHR, textStatus, errorThrown ) {
console.log("reponse textStatus["+textStatus+"] errorThrown["+errorThrown+"] [" + jqXHR.responseText + "]");
})
.done(function(data) {
console.log("success");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Can someone please tell me where I'm going wrong?
If I use this JSON payload, it works.
https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json
The error looks to be a parse error.
reponse textStatus[parsererror] errorThrown[Error:
jQuery331004379421802427674_1551456238952 was not called] [undefined]
The parseError is because jQuery thinks you're expecting a JSONP response (i.e. some executable Javascript), not just JSON data. It thinks that because you added the jsonCallback querystring parameter to the URL.
Once you remove that, it goes back to expecting regular JSON (which is what the endpoint returns), but is then defeated by the server's CORS restrictions.
You can't get round CORS by pretending you want to receive JSONP when that's not actually what the server is returning. I suggest you find out whether this server does in fact have a JSONP endpoint, or whether your app can be added as an allowed CORS client.
Related
Problem:
Uncaught SyntaxError: Unexpected token <
What I tried
Request: Jsonp
Response: returned XML Response 200.
Cross Domain Request that's why used data type: jsonp
Script code:
$.ajax({
url: "some url",
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
type: "POST", /* or type:"GET" or type:"PUT" */
data:myusername,
crossDomain: true,
dataType: 'jsonp',
data: {
'name':myusername
},
success: function (result) {
console.log(result);
},
error: function () {
console.log("error");
}
//});
});
Here AJAX response is XML.
But can someone tell how can I solved unexpected token problem.
Response is XML.
solution i found is third party request
var urljson='cross-damin-url';
var yql = 'http://query.yahooapis.com/v1/public/yql?q=' +
encodeURIComponent('select * from xml where url="' + urljson + '"') +
'&format=xml&callback=?';
$.getJSON(yql, function (data) {
console.log(data.results[0]);
});
Any suggestion is most welcome.
the problem is the line "dataType: 'jsonp'". Setting it this way the ajax call expect the result to be a jsonp (a json object wrapped as a params in a callback...) this is useful if you're doing a cross domain call (due to CORS). You have to set a "dataType: 'xml'"
Edit
considering the you have to do a CORS call, you have to change the output of the api, at least making something like
callbackName({value:'<your><xml>...</xml></your>'})
and parsing the xml from the string
"callbackName" is the name of a function or method declared in the page which make the ajax call and which will parse the json from the api... for instance something like:
function callbackName(result) {
console.log($.parseXML(result.value));
}
JSON and XML are arbitrarily nested data-interchange formats. You take a (well-formed) string and convert it to a data structure based on the rules of the format. Their similarities stop there.
So you can't just parse XML as JSON, they have different rules for turning a string (like that returned by an HTTP request) into a data structure. Which is why you're getting an error.
Parsing XML with an XML parser (like the one built into every browser) instead of a JSON parser will not throw an error.
But your actual problem is that it's a cross-domain resource and the browser (for good reason) won't let you. If you need a cross-domain resource and you don't control it and it doesn't have a CORS header you have a few options:
Beg the entity that controls the resource to add a CORS Header
Pipe the resource through your domain.
To expand on option 2:
Your page requests the resource from your webserver, your webserver makes an http request to the cross-origin resource, and then sends the result back to the browser.
About JSONP
JSONP was a hack invented before CORS to bypass the browser's security model. It was (meant) to be used by people who understood the risks, knew what they were doing and why. It involves potentially executing arbitrary third-party code on your page. Needless to say, that's bad.
I have a little page and I need to get JSON from another domain. If make this:
$.get( "http://dev.frevend.com/json/users.json", function( data ) {
console.log(data);
alert( "Load was performed." );
});
I get an error. I understand why it throws this error, but I don`t know how to aviod it. I have not acces to the server.
XMLHttpRequest cannot load http://dev.frevend.com/json/users.json. No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:3000' is therefore not allowed
access.
I also tried to use JSONP, but as I understand in that case server should wrap response with callback function, because I got a SyntaxError.
Is it possible to make this request with JSONP?
I tried
$.ajax({
url: "http://dev.frevend.com/json/users.json",
dataType: "jsonp",
jsonpCallback: "logResults"
});
function logResults(data) {
console.log(data);
}
But got
Uncaught SyntaxError: Unexpected token :
JSON is valid, I checked.
You need to allow access in your project configuration.
Below site has more information
http://enable-cors.org/server.html
Thanks,
Use JSONP in jquery for this purpose JSONP reference
Try to add a header into your PHP file which is responsible for executing every request.
header('Access-Control-Allow-Origin', '*');
I am using a Jquery $.post request to get a JSON response that is generated by PHP. When the request is complete, a success or error message is displayed. During development however, I sometimes have PHP errors which end up being returned instead of the JSON. When this happens, I just get the error message:
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
The code I have now looks like this:
var request = $.post(url, data, null, "json");
request.fail(on_failure);
var on_failure = function(jqXHR, text_status, error_thrown)
{
$("#text_status").empty().append(error_thrown);
};
I would like to be able to show the PHP error if one is returned rather than just indicate that there is a PHP error (just to speed up debugging). Obviously, if a non-JSON parsing error such as HTTP 404 occurs, I still want to display that. I found a method here that indicates that I can detect this error with something like this
$.ajaxSetup({
error: function(jqXHR, exception) {
if (exception === 'parsererror') {
alert('Requested JSON parse failed.');
}
}
});
But it doesn't seem like that helps me because it runs for every request rather than individual requests and (as far as I know) it does not allow access to the error message in the returned data.
No sure what version of jquery are you using. Anyway, did you try to remove the json dataType?
var request = $.post(url, data, null);
Doing this jQuery will guess the dataType for you.
I hate to steal mkross1983's credit, but he has not responded to my request to turn his comment into an answer. mkross1983 said:
Have you tried using Firebug under the "Net" tab to see the results of the requests? Sometimes errors can be seen there that can give some clues to the problem
The Firebug "Net" tab has proved to be a valuable debugging tool. This way I can see exactly what request was made and the response sent to it. It even allows me to see the headers and cookies that were sent with the request.
Thank you mkross1983
Here's the issue. I'm extracting gmail contacts through an ajax call in javascript/jquery like this:
function getUserInfo() {
var xml_parse = "";
$.ajax({
url: SCOPE + '?max-results=9999&access_token=' + acToken
data: null,
success: function (resp) {
xml_parse = $.parseXML(resp);
callGmailHelperWebService(xml_parse);
},
dataType: "jsonp"
});
}
function callGmailHelperWebService(xml_parse) {
GmailHelperService.ConvertXMLToList(xml_parse, onSuccess, onFailed, null);
}
So, as you can see, if the initial ajax call is successful, i call a function which calls a web service that sits on the save server as my project (in fact, it's part of the project).
My web service (GmailHelperService) is wired up correctly, as I can definitely call it in other places (like right after this ajax call, for example). However, when I try to call it within the "success" portion of the ajax call, i get the following error:
Uncaught Error: SECURITY_ERR: DOM Exception 18
My theory is that this has something to do with cross-domain issues, but I can't understand why. And I certainly can't figure out how to fix this.
I'd appreciate any help.
JSONP is a data transfer method that involves sending your data in this format:
callback({"foo":"bar"});
As you can see, this is NOT xml. It is JSON wrapped in a callback method that will get executed when the request is done loading, thus allowing it to be cross-domain because it can be requested using a <script> tag.
You cannot simply change your dataType to JSONP and return xml, expecting it to work. XML != JSONP. You can however return XML in jsonp, for example, callback({"xml","... xml string here "}) but be mindful of quotes, all json keys and values must be wrapped in double quotes, inner-quotes need to be handled appropriately.
If your request is a same domain request (Same protocol, same subdomain, same domain, and same port,) then you can change your dataType to "XML" if you are returning XML. Otherwise, you need to either setup a proxy script to get the xml for you, or have your webservice return JSONP.
For example, the following urls are all considered cross-domain from each other.
http://example.com
http://www.example.com
https://example.com
https://www.example.com
http://example.com:8080
All of the above urls would be considered cross-domain, even if they are on the same server.
I have the following script that call a http handler. It calls the http handler, and in fiddler, I can see the JSON returned correctly, however this script always ends up in the error block. How can I determine what is wrong?
<script type="text/javascript">
function GetConfig() {
$.getJSON("http://localhost:27249/Handlers/GetServiceMenuConfiguration.ashx", function(d) {
alert("success");
}).success(function(d) {
alert("success");
}).error(function(d) {
alert("error");
}).complete(function(d) {
alert("complete");
});
}
</script>
I see that you're including the server name (localhost) and port (27249). Ajax requests are controlled by the Same Origin Policy, which forbids cross-origin requests in the normal case. (If you're not doing a cross-origin call, you don't need to include the http://localhost:27249 portion of your URL, which is what makes me think you might be doing one.)
You can do cross-origin calls if the browser supports them and if your server code handles the CORS requests properly. Alternately, you might look at using JSON-P.
JQuery's built-in JSON parser is rather picky, even well formatted JSON can sometimes fail if the headers are not set perfectly. First try to do a $.ajax request with type:text property and log the response. This will differentiate between a connection problem and parse problem.
$.ajax({
dataType:'text',
url: '/Handlers/GetServiceMenuConfiguration.ashx',
success: function(data) {
console.log(data.responseText);
}
});
If the problem is the connection, and you do need to request JSON across domains, then you could also use a library loader like LAB, yep/nope or Frame.js.