"Uncaught SyntaxError: Unexpected token" when parse jsonp - javascript

I have created a json webservice in ASP.NET.
URL http://mydomain:21130/JSONdata.aspx?Option=GetListRootMenus
Data return:
{"NumberOfMenu":"2", "Menus":[{"MenuKey":"menu_home", "MenuLevel":"1" },{"MenuKey":"menu_info", "MenuLevel":"1" }]}
After that, i parsed via JSONP
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery.getJSON demo</title>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p> this is a param </p>
<script>
$(document).ready(function(){
console.log("zc");
$.ajax({
dataType: "jsonp",
type: 'GET',
url: "http://mydomain:21130/JSONdata.aspx?Option=GetListRootMenus&callback=?",
success: function(data) {
console.log("123");
},
error: function(){
console.log("456");
}
});
});
</script>
</body>
</html>
but wrong. i don't know why :(

As I explained in my comment, your service returns JSON, while jQuery expects JSONP. This is an issue because the response will be evaluated as JavaScript, but you are not sending back valid JavaScript.
Since you have control over the server, you have three possible solutions:
1. Tell jQuery to expect JSON
If there are no cross-domain issues because the site itself is also served from that domain, simple let jQuery make a real Ajax request, by changing dataType to json and removing callback=? from the URL.
2. Enable CORS (and tell jQuery to expect JSON)
If there are cross-domain issues, you can still do what I said in the first solution, but in addition, enable CORS on your server. In short, this allows other sites to make Ajax requests to your server. Have a look at http://enable-cors.org/ to learn how to enable it for your server.
3. Return JSONP
JSONP is all about including JavaScript dynamically. This works across domains because <script> elements don't have the same-origin restriction that Ajax has. However, it is still something that the server has to support because it has to return valid JSON. If your JSON response was
{"foo": 42}
then the JSONP response would be
func({"foo": 42});
The name of the function (func) in this example, is taken from some GET parameter that you could choose arbitrarily, but most common is callback. jQuery will actually choose a random function name so it will send something like
callback=jQuery123135343456456
your service has to take that value and use it as function name for JSONP, i.e.
jQuery123135343456456({"foo": 42});
See also
What is JSONP all about?
What are the differences between JSON and JSONP?

Related

"Security Err: Dom Exception" thrown when nesting ajax calls

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.

Call similar to $.get in $.ajax

I have the following code:
$.get(url, {}, checkResponse)
And the following function:
function checkResponse(content) {}
The parameter "content" here is the result of the "get". I wanted to implement $.ajax to able to wait for the process to complete before it jump to the next chunk of code. I tried the following code but it didn't work.
$.ajax({
async: false,
type: 'GET',
url: url,
success: function (data) {
alert(data.toString());
checkResponse(data);
},
error: function (data) {
alert("error");
}
});
Here's what happened, the alert for the data.toString() gives empty string value while it should give me the url page content, and after it hits the alert it jumps to the error section and displays the alert "error".
According to the discussion in the comments section you are trying to send cross domain AJAX calls to arbitrary urls on the internet. Due to the same origin policy restriction that's built into the browsers this is not possible.
Possible workarounds involve using JSONP or CORS but since you will be sending requests to arbitrary urls that you have no control over they might not be an option. The only viable solution in this case is for you to write a server side script that you will host on your domain acting as a bridge. This script will receive an url as parameter and send an HTTP request to this url in order to retrieve the result. Then it will simply return the result back to the response. Finally you will send an AJAX request to your own server side script.

Why does this $.getJSON request error?

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.

Cant read a json file on my local server from my web-server

So i have a json file named array.json on my web-server i intend to read this file in my web-application locally (for now) and then on a different domain once i go live, i have created this json file myself and here is the data it contains.
{"h1": "cmPanel", "h2" : "cmAuto", "h3": 0}
When i am trying to read the file I am not getting back a response, why would this be?
Here is my code for reading the file;
$.getJSON('http://www.foobar.com/array.json', function(data){
alert(data);
});
I have also tried adding &callback=? and still i receive nothing, could you please assist !
Quoting official docs:
Due to browser security restrictions, most "Ajax" requests are
subject to the same origin policy; the request can not successfully
retrieve data from a different domain, subdomain, or protocol.
Script and JSONP requests are not subject to the same origin
policy restrictions.
More info about Same Origin Policy
To work around it, look into JSONP.
In order to do cross-domain ajax calls you will either need to use a proxy or JSONP. Since you're setup for JSON already JSONP might be the easiest alternative. In short, JSONP entails wrapping your JSON data in a function call so it can be passed back to the calling script in a way that circumvents the Same Origin Policy.
In your case, you could wrap your json data with function named "myjsoncallback" so that it looks like this:
myjsoncallback({"h1": "cmPanel", "h2" : "cmAuto", "h3": 0})
And then change your ajax call to something like the following:
$.ajax({
url: 'http://www.foobar.com/array.json',
dataType: 'jsonp',
jsonpCallback: 'myjsoncallback', // Specify our callback function name
success: function(data) { console.log(data); }
});
Have you got access to the server from your web application? (same origin policy)
To use jsonp you could not simply add callback to the URL of the json file. The server should deliver a function that return the data. This file you could include with the default html script tag and execute the returned function afterwards.
To see the returned json you need to itterate the result
$.getJSON('array.json', function(data){
var items = [];
$.each(data, function(key, val) {
items.push('Key = ' + key + '<br/>Value = ' + val + '<br/><br/>');
});
alert(items.join(''));
});
array.json shoud be served with proper Content-Type:
text/javascript; charset=utf-8 if callback is used
application/json; charset=utf-8 if it is plain json
see here Best content type to serve JSONP?
to avoid problems from 'same origin policy'

jQuery Get Request on HTTP URL

i've recently tried to get some Response from an URL using jQuery. Therefore I copied a get request sample of jQuery API Get Request Tutorial into my project and tried to run it, but my debugging messages showed me, that it can't go further. I tried the javascript Ajax Library using a simple request, but it didn't work.
So i'm asking you, if you could help me somehow.
And this is all what i do, but there is no response.
var url = "http://www.google.com";
$.get(url, function(data){
alert("Data Loaded: " + data);
});
Did i probably forgot to include a ajax or jQuery library. For a better understanding, i have c and obj-c experince, this is why i think, that a library is missing.
In each sample there is just a short url like "test.php". Is my complete HTTP url wrong?
Thanks for your answers in advanced.
Br
Nic
I have provided an example scenario to help get you started:
<!-- Include this jQuery library in your HTML somewhere: -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script
This is probably best to include inside of an external JS file:
//Listen when a button, with a class of "myButton", is clicked
//You can use any jQuery/JavaScript event that you'd like to trigger the call
$('.myButton').click(function() {
//Send the AJAX call to the server
$.ajax({
//The URL to process the request
'url' : 'page.php',
//The type of request, also known as the "method" in HTML forms
//Can be 'GET' or 'POST'
'type' : 'GET',
//Any post-data/get-data parameters
//This is optional
'data' : {
'paramater1' : 'value',
'parameter2' : 'another value'
},
//The response from the server
'success' : function(data) {
//You can use any jQuery/JavaScript here!!!
if (data == "success") {
alert('request sent!');
}
}
});
});
You're hitting the Same Origin Policy with regard to ajax requests.
In a nutshell, JS/Ajax is by default only allowed to fire requests on the same domain as where the HTML page is been served from. If you intend to fire requests on other domains, it has to support JSONP and/or to set the Access-Control headers in order to get it to work. If that is not an option, then you have to create some proxy on the server side and use it instead (be careful since you can be banned for leeching too much from other sites using a robot).
As others have said you can't access files on another server. There is a hack tho. If you are using a server side language (as i assume you are) you can simply do something like:
http://myserver.com/google.php:
<?php
echo get_file_contents('http://www.google.com');
?>
http://myserver.com/myscript.js
$.get('google.php',function(data){ console.log(data) });
That should work!
you just can access pages from your domain/server

Categories

Resources