Google Places API: json error Uncaught SyntaxError Unexpected token - javascript

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

Related

jQuery AJAX - Not receiving JSON data when on localhost using XAMPP

I'm using this code:
$.ajax({
type: 'post',
url: "http://www.localhost/do_getmemes.php",
dataType: 'json',
data: {userid: userid, lastid: lastID},
success: function(data) {
console.log('bla');
console.log(data);
}
});
inside do_getmemes.php the post parameters are received successfully and the json is getting generated but I don't get it on success?? Console isn't showing anything. It works fine on the website but not when on localhost using XAMPP
It all works inside the php file, this is at the end:
file_put_contents('test.json', json_encode($array)); // file generated and not empty
echo json_encode($array);
What's the problem here?
EDIT:
AJAX usually works, I tested by getting simple string:
$.ajax({
url: "http://www.localhost/contact/text.php",
success: function(data) {
console.log(data) // got it
}
});
The problem were irrelevant warnings which were also sent through the API back and causing parsererror SyntaxError: Unexpected token < in JSON at position 0 error.
Besides fixing them this is the way to ensure the APIs wills till work:
Disable the warnings inside the PHP file:
error_reporting(0);
ini_set('display_errors', 0);

AJAX never reaches success

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;

Uncaught Syntax Error Unexpected token : , but the server received a valid json object from the server

I am trying to do a GET request to solr search engine using $.ajax() from jQuery. This is the code I am using for doing an ajax call:
$.ajax({
url : 'http://xxx.xxx.xxx.xxx:port#/solr/mycore/select?indent=on&q=myparam:value&wt=json',
type: "GET",
dataType: "jsonp",
jsonp : "callback",
success: function(data) {
console.log("Success", data);
},
error: function(data) { alert("Error"); }
});
So I am getting a valid json object in the response but somehow the browser throws an Uncaught Syntax Error. The actual error is:
Uncaught SyntaxError: Unexpected token :
select?indent=on&q=myparam:value&wt=json&callback=…....somevalue...
The tricky part is that the response header is text/plain when I checked in the browser. How can I solve this? Please help me...
Colons require encoding in query strings.
Your url should look like this:
http://xxx.xxx.xxx.xxx:port#/solr/mycore/select?indent=on&q=myparam%3Avalue&wt=json
If you're generating the query string dynamically, use encodeURIComponent() to correctly encode special characters.
I got this solved. Actually I had to use jsonpCallback:"mysuccesscallbackfunction" in the ajax call and json.wrf=mysuccesscallbackfunction in the URL. It looks like this now:
$.ajax({
url : 'http://xxx.xxx.xxx.xxx:port#/solr/mycore/select?indent=on&q=myparam:value&wt=json&json.wrf=mysuccesscallbackfunction',
type: "GET",
dataType: "jsonp",
jsonp : "callback",
jsonpCallback:"mysuccesscallbackfunction",
success: function(data) {
console.log("Success", data);
},
error: function(data) { alert("Error"); }
});
and my mysuccesscallbackfunction is:
function mysuccesscallbackfunction(resp) {
console.log('inside mysuccesscallbackfunction: ', resp );
}
Now, first it executes whatever is inside mysuccesscallbackfunction and then goes to default success callback. I found it somewhere on web. I would still like to know why it worked now.

Cross Domain Ajax get Request

I'd like to ask a question for cross-domain Get request via Ajax.
My ajax request is Like that
var currency_path="http://forex.cbm.gov.mm/api/latest";
$.ajax({
url: currency_path,
crossDomain:true,
type:"GET",
dataType:'jsonp',
async:false,
success: function(data){
console.log(data);
},
error: function(){
alert('failure');
}
}).done(function(msg) {
console.log(msg);
});
I got the response but i can't trace that
Any Suggestion ?
Look in your JavaScript error console:
Uncaught SyntaxError: Unexpected token :
You have dataType:'jsonp', but the URL is returning JSON.
You can't parse JSON as JSONP, there are different data formats.
Use some other technique to access the data.

Ajax success event not working

I have a registration form and am using $.ajax to submit it.
This is my AJAX request:
$(document).ready(function() {
$("form#regist").submit(function() {
var str = $("#regist").serialize();
$.ajax({
type: 'POST',
url: 'submit1.php',
data: $("#regist").serialize(),
dataType: 'json',
success: function() {
$("#loading").append("<h2>you are here</h2>");
}
});
return false;
});
});
In my submit1.php file I check for the existence of fields email address and username in the database.
I wish to display an error message if those value exist without a page refresh.
How can I add this to the success callback of my AJAX request?
The result is probably not in JSON format, so when jQuery tries to parse it as such, it fails. You can catch the error with error: callback function.
You don't seem to need JSON in that function anyways, so you can also take out the dataType: 'json' row.
Although the problem is already solved i add this in the hope it will help others.
I made the mistake an tried to use a function directly like this (success: OnSuccess(productID)). But you have to pass an anonymous function first:
function callWebService(cartObject) {
$.ajax({
type: "POST",
url: "http://localhost/AspNetWebService.asmx/YourMethodName",
data: cartObject,
contentType: "application/x-www-form-urlencoded",
dataType: "html",
success: function () {
OnSuccess(cartObject.productID)
},
error: function () {
OnError(cartObject.productID)
},
complete: function () {
// Handle the complete event
alert("ajax completed " + cartObject.productID);
}
}); // end Ajax
return false;
}
If you do not use an anonymous function as a wrapper OnSuccess is called even if the webservice returns an exception.
I tried removing the dataType row and it didn't work for me. I got around the issue by using "complete" instead of "success" as the callback. The success callback still fails in IE, but since my script runs and completes anyway that's all I care about.
$.ajax({
type: 'POST',
url: 'somescript.php',
data: someData,
complete: function(jqXHR) {
if(jqXHR.readyState === 4) {
... run some code ...
}
}
});
in jQuery 1.5 you can also do it like this.
var ajax = $.ajax({
type: 'POST',
url: 'somescript.php',
data: 'someData'
});
ajax.complete(function(jqXHR){
if(jqXHR.readyState === 4) {
... run some code ...
}
});
Make sure you're not printing (echo or print) any text/data prior to generate your JSON formated data in your PHP file. That could explain that you get a -sucessfull 200 OK- but your sucess event still fails in your javascript. You can verify what your script is receiving by checking the section "Network - Answer" in firebug for the POST submit1.php.
Put an alert() in your success callback to make sure it's being called at all.
If it's not, that's simply because the request wasn't successful at all, even though you manage to hit the server. Reasonable causes could be that a timeout expires, or something in your php code throws an exception.
Install the firebug addon for firefox, if you haven't already, and inspect the AJAX callback. You'll be able to see the response, and whether or not it receives a successful (200 OK) response. You can also put another alert() in the complete callback, which should definitely be invoked.
I was returning valid JSON, getting a response of 200 in my "complete" callback, and could see it in the chrome network console... BUT I hadn't specified
dataType: "json"
once I did, unlike the "accepted answer", that actually fixed the problem.
I had same problem. it happen because javascript expect json data type in returning data. but if you use echo or print in your php this situation occur. if you use echo function in php to return data, Simply remove dataType : "json" working pretty well.
You must declare both Success AND Error callback. Adding
error: function(err) {...}
should fix the problem
I'm using XML to carry the result back from the php on the server to the webpage and I have had the same behaviour.
In my case the reason was , that the closing tag did not match the opening tag.
<?php
....
header("Content-Type: text/xml");
echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>
<result>
<status>$status</status>
<OPENING_TAG>$message</CLOSING_TAG>
</result>";
?>
I had this problem using an ajax function to recover the user password from Magento. The success event was not being fired, then I realized there were two errors:
The result was not being returned in JSON format
I was trying to convert an array to JSON format, but this array had non-utf characters
So every time I tried to use json_eoncde() to encode the returning array, the function was not working because one of its indexes had non-utf characters, most of them accentuation in brazilian portuguese words.
I tried to return string from controller but why control returning to error block not in success of ajax
var sownum="aa";
$.ajax({
type : "POST",
contentType : 'application/json; charset=utf-8',
dataType : "JSON",
url : 'updateSowDetails.html?sownum=' + sownum,
success : function() {
alert("Wrong username");
},
error : function(request, status, error) {
var val = request.responseText;
alert("error"+val);
}
});
I faced the same problem when querying controller which does not return success response, when modified my controller to return success message problem was solved.
note using Lavalite framework.
before:
public function Activity($id)
{
$data=getData();
return
$this->response->title('title')
->layout('layout')
->data(compact('data'))
->view('view')
->output();
}
after code looks like:
try {
$attributes = $request->all();
//do something
return $this->response->message('')
->code(204)
->status('success')
->url('url'. $data->id)
->redirect();
} catch (Exception $e) {
return $this->response->message($e->getMessage())
->code(400)
->status('error')
->url('nothing Wrong')
->redirect()
}
this worked for me
I had the same problem i solved it in that way:
My ajax:
event.preventDefault();
$.ajax('file.php', {
method: 'POST',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify({tab}),
success: function(php_response){
if (php_response == 'item')
{
console.log('it works');
}
}
})
Ok. The problem is not with json but only php response.
Before: my php response was:
echo 'item';
Now:
$variable = 'item';
echo json.encode($variable);
Now my success working.
PS. Sorry if something is wrong but it is my first comment on this forum :)
in my case the error was this was in the server side and for that reason it was returning a html
wp_nonce_field(basename(__FILE__), "mu-meta-box-nonce");
Add 'error' callback (just like 'success') this way:
$.ajax({
type: 'POST',
url: 'submit1.php',
data: $("#regist").serialize(),
dataType: 'json',
success: function() {
$("#loading").append("<h2>you are here</h2>");
},
error: function(jqXhr, textStatus, errorMessage){
console.log("Error: ", errorMessage);
}
});
So, in my case I saw in console:
Error: SyntaxError: Unexpected end of JSON input
at parse (<anonymous>), ..., etc.
The success callback takes two arguments:
success: function (data, textStatus) { }
Also make sure that the submit1.php sets the proper content-type header: application/json

Categories