AJAX never reaches success - javascript

I have a GET API that gives me the following result:
The following code, tries to get this JSON information:
<script>
jQuery(document).ready(function ($)
{
$.ajax({
url: 'http://localhost:15840' + '/totem/GetRestaurants',
type: "GET",
dataType: "jsonp",
crossDomain: true,
complete: function (data)
{
alert (data)
for (var restaurant in data)
{
document.getElementById('restaurants').innerHTML = '<li class="gallery-image" > <img src="img/restaurante-02.jpg" alt="" /><div class="gallery-text"><span>FOOD RESTAURANT</span></div></li >'
}
},
error: function () {
alert("error");
}
});
});
</script>
The error method always get executed, and the complete alert just shows the following information:
But If I go to chrome inspector, the responce looks good:
Why is this happening?
EDIT:
With the following code, nothing happens:
<script>
jQuery(document).ready(function ($)
{
$.ajax({
url: 'http://localhost:15840' + '/totem/GetRestaurants',
type: "GET",
dataType: "jsonp",
crossDomain: true,
success: function (data)
{
alert ("hello success")
}
});
});
</script>

You said:
dataType: "jsonp",
… but the screenshot of the response shows that is JSON not JSONP.
You need to either:
Set the dataType to "json"
Change the server to respond with JSONP (see What is JSONP, and why was it created? for more information on that).
Note that JSONP is a dirty and dangerous hack to work around the Same Origin Policy and that we now have CORS (which is a well-standardised and flexible means to selectively disable the Same Origin Policy that doesn't have JSONPs drawbacks). So don't go with option 2.
You might have tried using dataType: "jsonp" because you got an error like:
XMLHttpRequest cannot load XXX No 'Access-Control-Allow-Origin' header
This error occurs because you are violating the Same Origin Policy. JSONP is one way to work around it, CORS is a better way. Both of those ways require the server to be changed to allow them to work.
See this question for more information.

As you are sending the jsonp request, you need to change how you are returning data. you need to wrap your JSON object in $_GET['callback']. if your backend was in php you can try the following code
$response['data'] = array('sdu');
$response = json_encode($response);
echo htmlspecialchars($_GET['callback']) . '(' . $response . ')';
exit;

Related

JSON issue with jQuery (JSONP)

I have a strange issue using jQuery and JSON, especially JSONP.
My goal is to simply GET JSON data, but I always end up with the following error:
Uncaught SyntaxError: Unexpected token
Here is the code:
<script type="text/javascript">
$(document).ready(function() {
var myurl = "someurl";
$.ajax({
url: myurl,
method: 'GET',
contentType: 'application/javascript',
dataType : 'jsonp',
success: function(result){
//Do something with JSON result
}
});
</script>
And of course the JSON (raw format):
{"result":[{"targetView":"powerUsage","myData":{"someItems":["9","5","8"],"someItems2":[{"text":"protoText","currentRecord":"45.38","absolute":100}]}}]}
I tried the webservice with the Advanced Rest Client App in Google Chrome and it is working perfectly. I have no clue why this simple example gets this syntax error message.
Your Ajax code looks like fine. I think you are trying to make a Cross domain call as JSONP is a hack for dealing cross domain ajax call. If you Server code if ready for dealing with JSONP request then you must have send a callback parameter like
?callback=my_callback_method
than you service will return result with a callback see below links for more details:
https://learn.jquery.com/ajax/working-with-jsonp/
http://stackoverflow.com/questions/11736431/make-cross-domain-ajax-jsonp-request-with-jquery
You missed to put ready function close, that is }); at the last before script tag close:
<script type="text/javascript">
$(document).ready(function()
{
var myurl = "someurl";
$.ajax(
{
url: myurl,
method: 'GET',
contentType: 'application/javascript',
dataType: 'jsonp',
success: function(result)
{
//Do something with JSON result
}
});
});
</script>

SyntaxError: missing ; before statement jquery jsonp

I am using below code to access rest service hosted on another domain.
$.ajax({
type: 'GET',
url: url,
async: false,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType:"jsonp",
success: function(json) {
alert(json);
},
error: function(e) {
console.log(e.message);
}
});
I am able to get the data correctly, but I get this error in firebug in mozilla:
SyntaxError: missing ; before statement
{"Hello":"World"}
Can anyone suggest me what I am doing wrong here? Even though Json data is valid. I tried all the suggestions posted in this question But still I am getting same error.
If it's really JSON you ask for, don't set "jsonp" as dataType, and don't provide a callback :
$.ajax({
type: 'GET',
url: url,
contentType: "application/json",
success: function(json) {
alert(json);
},
error: function(e) {
console.log(e.message);
}
});
the format of JSON and JSONP are slightæy different
JKSONP is a function invocation expression
callback({"hellow":"world"});
whereas JSON is simply a serialized object
{"Hello":"world"}
fromyour posting it would seem that the server is returning JSON and not JSONP
So you either need to change the server to reply correctly (The actual callback name is a get parameter to the request). You should do this if you are using the ajax call across domains
If you are not using ajax across domains stick to regular JSON

Jquery unable to get the response from WCF REST service

I have developed WCF rest service and deployed it on a link that can be accessed via the browser because its action is "GET".
I want to get that data using jQuery. I tried my best to get WCf get response using jQuery
but in vain. I also tried $.Ajax with 'jsonp' with no luck. Can any one help me?
The url is: http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation
You can check that url response by pasting url in browser.
You need to set Access-Control-Allow-Origin to value [*] in your response header.
this blog gives the more details how it can be done in WCF REST service
if you were to do this in Web API you could have just added
Response.Headers.Add("Access-Control-Allow-Origin", "*")
calling the service using a fiddle
$(function() {
$.ajax({
url: "http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation",
datatype: 'json',
type : 'get',
success: function(data) {
debugger;
var obj = data;
}
});
})​;​
I got the error
XMLHttpRequest cannot load
http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation.
Origin http://fiddle.jshell.net is not allowed by
Access-Control-Allow-Origin.
I can't make a cross domain example to show you but
$('#a').load('http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation​​​​​​​​​​​​​​​​​?callback=run');​
would work had those things been set.
Your service needs to either enable JSONP callbacks or set the Access-Control-Allow-Origin header for cross domain requests to work, or you need to run the script from the same domain. Given that your url says AndroidApp I'm thinking you want cross domain.
Sample code below:
$.ajax
(
{
type: 'GET',
url: http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation,
cache: false,
async: true,
dataType: 'json',
success: function (response, type, xhr)
{
window.alert(response);
},
error: function (xhr)
{
window.alert('error: ' + xhr.statusText);
}
}
);

Trying to trigger jQuery Mobile ajax call

I'm sure this is a basic syntax error but I'm trying to make a rest call using jQuery mobile ajax (code below) and as far as I can tell the ajax is not triggering.
function triggerCall() {
alert("function triggered");
$.ajax({
type: "GET",
dataType: "jsonp",
url: REST Url,
success: function (data) {
alert(data);
}
});
Any help would be appreciated
if you're actually writing url: REST Url, then you must change it to either a var, or a string.. that would be a problem
I believe that if you're using JSONP, you need to specify the callback in the $.ajax request and then again in your REST file return. Here is an example of what I've been using succesfuly (It's not perfect though, I'm sure).
$.ajax({
url: 'www.domain.com/string/to/your/REST/api',
data: {
dataToBeSent: variable,
dataToBeSent: sessionStorage.getItem('local/session Storage'),
dataToBeSend: "or a string"
},
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data){
alert("Huzzah!");
},
error: function(){
alert("Boohisssss");
}
}); //end ajax call
And then in the url, I'd place this code at the bottom of the file:
header("Content-type: application/json", true);
echo $_GET['jsoncallback'] . '(' . json_encode($data) . ');';
exit;
Where data is a array that is JSON encoded, using json_encode() in PHP, and then wrapped up in a callback function (the $_GET['jsoncallback'])
Like I said, it's not perfect, but it's been working for me.
Check for errors in browser console. eg. in chrome menu>tools>javascript console.
Also recommend adding an error handler to your ajax call: http://api.jquery.com/error/
Determine which method, JSONP or CORS, to use for your restful ajax calls: So, JSONP or CORS? .

Google Places API: json error Uncaught SyntaxError Unexpected token

I dont get why i get so many different errors.
I'm using Google Places API for a test, and using simply an ajax query call with callback, i receive back the json but in CHrome browser i get
"Uncaught SyntaxError: Unexpected token :"
why the hell is that?
I supposed Google does it right, and their json must be correct...so where could be the problem?
this is my code
$.ajax({
dataType: "json",
url: "https://maps.googleapis.com/maps/api/place/search/json?location=40.47,-73.58&radius=5000&sensor=false&key=MYOWN&name&callback=?",
success: function(data) {
console.log('success');
},
error: function(data) {
console.log('error');
}
});
You get this error, if a server returns plain JSON. As this is a cross-site request, jQuery has to use the JSONP-technique where the server-response is interpreted as script. This is the only way to do cross-site-requests in the browser.
The problem is that the server has to support JSONP and surround the JSON answer with a callback generated by jQuery. The response must look like that:
jQuery17101705844928510487_1324249734338({"data":"whatever"});
Server-Example with PHP:
<?php
header("Content-Type:text/javascript"); // avoid browser warnings
$request = new HttpRequest("http://programmingisart.com/json-data-source.php", HttpRequest::METH_GET);
$request->send();
$json_data = $request->getResponseBody();
// wrap the data as with the callback
$callback = isset($_GET["callback"]) ? $_GET["callback"] : "alert";
echo $callback."(".$json_data.");";
Client-Example with jQuery:
<div id="json-result"></div>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
dataType: "jsonp",
url: "jsonp-wrapper.php",
success: function(data) {
$("#json-result").html(JSON.stringify(data));
},
error: function() {
alert("error");
}
});
});
</script>
You can replace the PHP-code with any other server-platform and do the required steps.
HTTP-Request to a JSON source
Wrap the JSON as with a callback-function

Categories