I am trying to fetch JSON data/file from other server/domain.
My understanding is that from below code i should be able to see success alert but i see error alert
$.ajax({
url: "http://xxxx.com/zzzz",
dataType: 'jsonp',
success: function (json) {
alert("Success");
},
error: function () {
alert("Error");
}
});
In firebug console i see this error
SyntaxError: missing ; before statement
"responseHeader":{
If i open the URL in browser i can see JSON data but not able to fetch it and parse.
This is the starting part of the JSON data if i hit the URL in browser for reference
{
"responseHeader":{
"status":0,
"QTime":4576,
"params":{
"q":"*:*",
"facet.limit":"10",
"facet.field":["DataSet",
"Site",
"Year",
"Product"],
"indent":"true",
"wt":"json",
"facet":"true"}},
"response":{"numFound":260682,"start":0,"docs":[
{
Am i doing anything wrong here OR should i try differently to access JSON data from other domain.
Please suggest. Thanks in advance
Try this:
$.ajax({
url: "http://xxxx.com/zzzz",
dataType: 'json',
success: function (json) {
alert("Success");
},
error: function () {
alert("Error");
}
});
Try to change the datatype from 'jsonp' to 'json'
I think your response is a valid JSON string, but not valid JSONp. The p in JSONp stands for "padding". That means the response must be wrapped within a JavaScript function and returned with the content type text/javascript Please see the example below:
myCalllbackFunc({ my: "data" });
When you use jQuery, the library will pass a callback variable as a query parameter to your back-end. The value defines the name of your callback function.
http://your.host/json?callback=fooBarFunc
should result into this
fooBarFunc({ my: "data" });
Cheers,
Peter
BTW: beside JSONp, you could use CORS for cross origin resource sharing :) http://www.html5rocks.com/en/tutorials/cors/
Related
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.
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
Following is my code :
function jsonpCallback(response){
//JSON.stringify(response)
alert(response);
}
$.ajax({
url: url,
dataType: 'jsonp',
error: function(xhr, status, error) {
alert(error);
},
success: function(data) {
alert(data);
jsonpCallback(data);
}
});
Here my url variable is the link which contain the following data and as per I know it is in the JSON format:
[{"destination":"United States","destinationId":"46EA10FA8E00","city":"LosAngeles","state":"California","country":"United States"}] etc..
I want to call jsonpCallback function after passing successive data to it. But success argument of $.ajax is not calling the function thats why I am not getting any data into it. But my debugger window showing response there, so why its not coming $.ajax function?
Any help...thanks in advance.
Try to pass type of ajax call GET/POST.
$.ajax({
type: "GET",
url: url,
dataType: 'jsonp',
error: function(xhr, status, error) { alert(error); },
success: function(data) {
alert(data);
jsonpCallback(data);
}
});
function jsonpCallback(response){
//JSON.stringify(response)
alert(response);
}
The URL you are trying to load data from doesn't support JSONP, which is why the callback isn't being called.
If you own the endpoint, make sure you handle the callback GET parameter. In PHP, your output would look like this:
<?php
echo $_GET['callback'].'('.json_encode($x).')';
This will transform the result to look like this:
jsonp2891037589102([{"destination":"United States","destinationId":"46EA10FA8E00","city":"LosAngeles","state":"California","country":"United States"}])
Of course the callback name will change depending on what jQuery generates automatically.
This is required as JSONP works by creating a new <script> tag in the <head> to force the browser to load the data. If the callback GET parameter isn't handled (and the URL returns a JSON response instead of a JSONP response), the data gets loaded yes, but isn't assigned to anything nor transferred (via a callback) to anything. Essentially, the data gets lost.
Without modifying the endpoint, you will not be able to load the data from that URL.
One weird thing I've noticed about $.ajax is that if the content-type doesn't match exactly it's not considered a success. Try playing around with that. If you change success to complete (and fix the arguments) does it alert?
It's not working because your server does not render a JSONP response. It renders a JSON response.
For JSONP to work, the server must call a javascript function sent by the ajax request. The function is generated by jQuery so you don't have to worry about it.
The server has to worry about it, though. By default, this function's name is passed in the callback argument. For example, the URL to the server will be http://some.domain/ajax.php?callback=functionName (notice callback=functionName).
So you need to implement something like the following on the server side (here in PHP):
$callback = $_GET['callback'];
// Process the datas, bla bla bla
// And display the function that will be called
echo $callback, '(', $datas, ');';
The page returned will be executed in javascript, so the function will be called, so jQuery will call the success function.
First check in which event you are calling $.ajax function...
<script type='text/javascript'>
jQuery('#EnrollmentRoleId').change(function(){
alert("ajax is fired");
$.ajax({
type: "GET",
url: url,
dataType: 'jsonp',
error: function(xhr, status, error) { alert(error); },
success: function(data) {
alert(data);
jsonpCallback(data);
}
});
});
function jsonpCallback(response){
//JSON.stringify(response)
alert(response);
}
</script>
second try to replace $ with jQuery.
Try to give no conflict if you thinking any conflict error..
jQuery ajax error callback not firing
function doJsonp()
{
alert("come to ajax");
$.ajax({
url: url,
dataType: "jsonp",
crossDomain: true,
jsonpCallback:'blah',
success: function() { console.log("success"); },
error: function() { console.log("error"); }
});
}
Then check your json data if it is coming it is valid or not..
Thanks
Essentially, if I'm in Firebug and look at the net objects I see the status 200
If I click on the JSON tab I can see my access_token, but how do I extract it from there so I can use for API calls?
Here's the latest code tried.
var jsonUrl = url +"&callback=?";
var access_token;
$("#getJSON").click(function() {
$.getJSON(jsonUrl, { dataType: "JSONP" }, function(json){
...
access_token = json.access_token;
...
});
});
also tried:
$.ajax({
dataType: 'jsonp',
jsonp: 'callback',
url: url,
success: function (json) {
console.log(json.access_token);
},
});
But when I try and alert(access_token); or run a foursquare api call I get the following errors
Resource interpreted as Script but transferred with MIME type application/json.
Uncaught SyntaxError: Unexpected token : checkinsGET https://api.foursquare.com/v2/users/self/checkins?oauth_token=undefined&format=json 401 (Unauthorized)
I feel like its ready and waiting for me to call it, but how on earth do I print it from the Dom into a var that I can use? Been fighting for hours and been trying all my research techniques for some reason this one's elluding me. Thanks for everyone's help so far, I'm really hoping to get passed this!
Browsers natively implement a global function JSON.parse(), and if for some reason that doesn't work you can use jQuery's parseJSON() function.
Here's how it works. Let's say your JSON object has the following format:
{
Status: "Success",
Resource: {
Name: "Person's Name",
URL: "http://blahblahblah.com/extrastuffhere?querystuff=here"}}
Then you can access the "URL" element by using JSON.parse() like so:
var url = JSON.parse(json).Resource.URL;
(I'm unfamiliar with Foursquare but it should look similar, and you can do console.log(json) to see its structure.)
So your code might look something like this:
$("#getJSON").click(function() {
$.getJSON(jsonUrl, { dataType: "JSONP" }, function(json){
var parsed = JSON.parse(json);
console.log(parsed);
access_token = parsed.access_token;
});
});
Hope that helps!
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