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',
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).
So I am using ajax to post a serialised form to a php script and then on success alert the returned data.
My code works fine on my local environment, but uploaded, the eval() function mucks everything up.
here is my code:
function post_that_shit(formIdToSerialize, postUrl) {
var serializedData = $("#"+formIdToSerialize).serialize();
var post_url = postUrl+".php";
//alert(serializedData + "\n" + post_url);
$.ajax({
url: post_url,
type: "POST",
data: serializedData,
success: function(data){
data = eval('('+data+')' );
console.log(data.msg);
if(data.reload == 'yes'){
window.location.reload();
}
if(data.relocate != 'no'){
window.location.href = data.relocate;
//alert(data.relocate);
}
if(data.msg != 'no'){
$(".message").html(data.msg);
//alert(data.msg);
}
//alert('relocate: '+data.relocate);
}
});
}
So it is pretty simple.
The php echo out a json encoded array like so:
echo json_encode(array('msg' => $errors, 'relocate' => 'no'));
And depending on what is echoed, the msg is displayed or the user relocated.
Why do I get the error of SyntaxError: Unexpected token ')' when I use the code online?
Locally it works just fine :(
Thanx for your help
Chris
You don't need to use eval(). Just set the dataType option to 'json' and the data will be internally parsed to an object by jQuery
$.ajax({
url: post_url,
type: "POST",
dataType:'json',
data: serializedData,
success: function(data){
console.log(typeof data); // returns "object"
In addition setting the proper content type header for application/json at server also helps
I don't know why you need the eval() function in that place. It's a wrong coding. Your solution is put the data type to JSON and the ajax function treats automatically as a json:
$.ajax({
url: post_url,
type: "POST",
dataType: 'json',
data: serializedData,
success: function(data){
console.log(data.msg);
if(data.reload == 'yes'){
window.location.reload();
}
if(data.relocate != 'no'){
window.location.href = data.relocate;
//alert(data.relocate);
}
if(data.msg != 'no'){
$(".message").html(data.msg);
//alert(data.msg);
}
//alert('relocate: '+data.relocate);
}
});
First of all, eval is evil. Don't use it... never ever! It's like a bomb ready to detonate.
Secondly, parsing json can be done natively in Javascript. No need for eval.
You can use JSON.parse and it will return you an object parsed by the string containing the json text.
eval is used to evaluate code, in other words, it is executing javascript not json. When eval returns an object, it is simply a side effect of JSON being a subset of JavaScript. In other words, any string formatted as json can be evaluated to JavaScript. But JavaScript cannot be formatted to JSON. There is no representation of Date, Function and many more complex objects. That said, when using eval, you're actually executing JavaScript and that is the big problem here. It could execute potentially dangerous code while parsing JSON simply requires parsing data into a data structure and nothing more.
Here more about JSON: https://fr.wikipedia.org/wiki/JavaScript_Object_Notation
So it would allow anyone to add somewhat some javascript that would then get executed by your use of eval. It could allow someone to execute code on the browser of other users. It could be used to steal passwords for example or steal any kind of private information that wouldn't be accessible otherwise.
jQuery on the other hand allow you to parse json natively by using the dataType attribute as 'json'. Like this:
$.ajax({
url: post_url,
type: "POST",
dataType: 'json',
data: serializedData,
success: function(data){
console.log(data.msg);
Or using JSON.parse
$.ajax({
url: post_url,
type: "POST",
data: serializedData,
success: function(data){
data = JSON.parse(data)
console.log(data.msg);
Also as charlie pointed out, parsing by ourselves JSON means that we have to wrap it in a try catch, because parsing might fail if the json isn't valid.
But using jQuery gives us a way to handle that easily.
You could rewrite your code such as this:
var req = $.ajax({
url: post_url,
type: "POST",
dataType: 'json',
data: serializedDate
});
req.done(function (data) {
// Success
});
req.fail(function () {
// Error something went wrong
});
The advantage of using the promise form is that you can chain calls to have clean async code instead of the callback hell and infinite function nesting.
Usage of JSON.stringify() breaks page without errors in console
EDIT: I read about jquery plugin jquery-json, I tried that with the same result.
var bookmarkParams = {"id":"123456"};
$.ajax({
url: 'http://service',
cache: false,
type: "POST",
dataType: "json",
headers: {
// some headers
},
contentType: 'application/json; charset=UTF-8',
data: JSON.stringify(bookmarkParams),
success: successCallback,
error: errorCallback
});
// successCallback & errorCallback are defined functions
any ideas why this might be?
If i don't use JSON.stringify() then the page does not break but my AJAX request won't function correctly when passing my data to the server.
What is params? Don't you mean bookmark params?
try this...
var bookmarkParams = '{"id":"123456"}';
then change params to bookmarkParams
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.
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