I have getJson like this:
$.getJSON(userUrl+'scanp?callback=?', { 'someparametar': 100 }, function(data){
console.log(data);
});
and I do get a response from my url, and it looks like this:
'"jQuery1110010384737118147314_1401820556204({'hasWon':'false','code':'120580e9fce67a4921f31af7ffa358cc10c83b10','defaultReward':'{\"secure_url\":\"https://res.cloudinary.com/deh0vdgzd/image/upload/v1401318096/k6jrm2pehwycmehrkicz.png\",\"url\":\"http://res.cloudinary.com/deh0vdgzd/image/upload/v1401318096/k6jrm2pehwycmehrkicz.png\",\"resource_type\":\"image\",\"format\":\"png\",\"height\":960,\"width\":640,\"signature\":\"a8ca9bb867e0a3d99e1666b7891e8f918d81e627\",\"version\":1401318096,\"public_id\":\"k6jrm2pehwycmehrkicz\"}''}"'
Any idea why I don't get any response when I console.log it?
With 'callback' in your querystring, JQuery wraps the response with a randomly generated method name. To get JSON (without method name), remove 'callback=?' from querystring.
If your server supports JSONP, you can make a call like this :
$.ajax({
type: 'GET',
url: url,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
console.log(JSON.stringify(json));
},
error: function(e) {
console.log(e.message);
}
});
Hope this helps.
Well I figured it out, the request I wrote was perfectly fine. The thing that was causing the the problem was response I was getting from server.
It was JSON stringified before return.
Related
I have this encode in JSON format as returned data:
{
"error": {
"msg":"Concurrent verifications to the same number are not allowed",
"code":10
}
}
and I want to access msg so I wrote the javascript as:
$("#buttonPhoneSubmit").click(function(e) {
$("#verifyForm").show();
e.preventDefault();
$.ajax({
type: 'post',
url: './process.php',
data: $('form').serialize(),
datatype:'json',
success: function (data) {
$('#error_message').html(data.error.msg);
}
});
but it said the data is undefined. Can someone tell me what's wrong with the code?
Thanks!
As Roy said, you have datatype: 'json' instead of dataType: 'json'. So I suspect jQuery isn't parsing the JSON for you.
While you could change it to dataType: 'json' instead, the better approach is to update the PHP file to send the Content-Type: application/json header with the response:
// In the PHP, prior to sending the body of the response
header('Content-Type: application/json');
...and remove datatype: 'json' from your ajax call. jQuery will see the content type and parse it for you, at which point your code should work (assuming the page return returns the JSON you've quoted).
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>
The http request sent to some 'request_url' returns json response in format {'succes': 1, 'html': 'thestuff'}
so when
jQuery.ajax({
url: 'request_url',
success: function(response){
alert(response.html); //'thestuff' is here as expected
}
});
'thestuff' can be found in response.html as expected. But if this ajax is called inside the 'success' callback of another one ajax request then the response.html is coming empty and 'thestuff' is going to 'response'.
jQuery.ajax({
url: 'some_other_url',
success: function(some_other_response){
jQuery.ajax({
url: 'request_url',
success: function(respose){
alert(response.html); //there is nothing
alert(response); //I see 'thestuff' which is expected in 'html'
}
})
}
});
Why does it happen?
Update: 'thestuff' contains some js code with {} I can suppose something can get confused but why it works well with single (not nested) ajax request.
Not enough reputation to comment so adding as an answer
Here is expanding on charlietfl comment of using dataType.
I made it work using dataType="json". Json has to be strictly formatted though as per jQuery documentation.
jQuery.ajax({
url: 'some_other_url',
success: function(some_other_response){
jQuery.ajax({
url: 'request_url',
dataType:"json",
success: function(response){
alert(response.status); //there is nothing
alert(response); //I see 'thestuff' which is expected in 'html'
}
})
}
});
request_url should return something like this (note, quotes should be used instead of apostrophes)
{"status":"s","html":"some stuff"}
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
I have the following from the server response:
{"invalid_emails":["adsasdasd"],"result":"success","valid_emails":["jobs#apple.com"]}
But this errors?
$.ajax({
type: 'POST',
url: '/users/invitation',
data: $('#user_invitation_new').serialize(),
success: function(e) {
jsonObject = jQuery.parseJSON(e);
jsonObject.valid_emails
jsonObject.invalid_emails
I get the following error: Uncaught TypeError: Cannot read property 'valid_emails' of null
As Jason and Jonathon mentioned, you should not manually deserialize the JSON. Depending on what version of jQuery you're using, jQuery will automatically deserialize JSON based on the response's content-type header. So, you're probably trying to $.parseJSON() something that's already an object, not a JSON string.
To be sure that jQuery does this automatic deserialization for you, add a dataType parameter to the $.ajax() call:
$.ajax({
type: 'POST',
dataType: 'json',
url: '/users/invitation',
data: $('#user_invitation_new').serialize(),
success: function(response) {
console.log(response.valid_emails);
console.log(response.invalid_emails);
}
});
You may not have to parse that JSON, as it is already a JSON object. try doing
var emails = e.valid_emails;
If this still does not work, include dataType: 'json' in your .ajax() declaration.
If your server responds with the JSON then you should have to run jQuery.parseJSON(e);. The e parameter might already be the about so try this for your success handler:
success: function(e)
var valEmails = e.valid_emails,
invalEmails = e.invalid_emails;
};
Just try including
dataType: 'json',