eval function not working in ajax post - javascript

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.

Related

Jquery response load

A jQuery function receives a string from a database using GET, after that I would like to inject that string into HTML in place of a div. Pretty standard stuff so it seems.
However I am not quite managing it.
Here is what I have going on:
<h1>Whatever</h1>
<div id="replace_me">
</div>
<a id="click_me" href="#">Click Me</a>
<script>
//AJAX
var brand_id = 8
var dataX = {'brand': brand_id, 'csrfmiddlewaretoken': ""};
$(function(){
$("#click_me").click(function(){
$.ajax({
type: 'GET',
url: '/ajax_request/',
data: dataX,
datatype: "json",
success: function(data) {
alert(data);
$("#replace_me").load(data);
},
error: function() {
alert("Nope...");
}
});
});
});
</script>
When the alert is set off I receive my string which shows everything is working fine, but how can I input that string I just received into the div "replace_me" without having to load from another url?
You have an error in your success function. Check documentation on jQuery load(). Instead, you should do
success: function(data) {
//alert(data);
$("#replace_me").html(data);
},
or, slightly better style
success: function(data) {
//alert(data);
$("#replace_me").empty().append($(data));
},
Also note, that you specified "json" in your datatype option. As a consequence, if your server responds in proper JSON, your data will be a JavaScript object, as jQuery will parse the JSON format for you. If you really want to see the object, you will need to use, e.g. JSON.stringify():
$("#replace_me").empty().append($(JSON.stringify(data)));
If your server does not produce valid JSON, your success method will not be called in most cases.
load() is a convenience method to do the two steps of calling the ajax url, then putting the data into the element all in a single function. Instead of calling .ajax(), just call .load()
i.e.
var brand_id = 8
var data = {'brand': brand_id, 'csrfmiddlewaretoken': ""};
$("#replace_me").load('/ajax_request/', data);

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

Posting JSON string to PHP page

Okay, I'm having some suicidal issues posting a JSON string to a PHP page. I have literally been through the top ten results on Google and plenty of SO questions related to my problem, but still can't work out what I'm doing wrong.
I have multiple forms on a page and want to collect all form fields, turn them into a JSON string and post them to a PHP page, where a script iterates each item and updates the relevant database tables.
This is my jQuery/JS script to collect the data from all the forms:
var photo_annotations = {};
$('form').each(function(i) {
var id = $(this).attr('id');
photo_annotations[id] = {
caption: $('#'+id+'_caption').val(),
keywords: $('#'+id+'_keywords').val(),
credit: $('#'+id+'_credit').val(),
credit_url: $('#'+id+'_credit_url').val()
};
});
If I console.log my photo_annotations object, this is what is produced, based on a two form example:
({11:{caption:"Caption for first photo.", keywords:"Keyword1,
Keyword2, Keyword3", credit:"Joe Bloggs",
credit_url:"www.a-domain.com"}, 12:{caption:"Caption for Lady Gaga.",
keywords:"Keyword3, Keyword4", credit:"John Doe",
credit_url:"www.another-domain.com"}})
I then need to POST this as a string/JSON to a PHP page, so I've done this:
$.ajax({
type: 'POST',
dataType: 'html',
url: 'ajax/save-annotations.php',
data: { data: JSON.stringify(photo_annotations) },
contentType: "application/json; charset=utf-8",
success: function(data) {
if (data) {
$('#form_results').html(data);
} else {
alert("No data");
}
}
});
And on my PHP page, I've got this:
<?php
//print_r($_POST['data']);
$decoded = json_decode($_POST['data'],true);
print_r($decoded);
?>
Now, this isn't the only thing I've tried. I've tried to remove all the JSON settings from the AJAX script, in a bid to just send a pure string. I've tried removing contentType and JSON.stringify but still won't go. My PHP page just can't get the data that I'm sending.
Please help push me in the right direction. I've got to the point where I can't remember all the variations I've tried and this little script is now on day 2!
MANAGED TO FIX IT
I rewrote my AJAX function and it worked. I have no idea what was going wrong but decided to test my AJAX function with a very basic data string test=hello world and found that no POST data could be read from the PHP page, even though Firebug says that the page did in fact receive post data matching what I sent. Very strange. Anyway, this is the revised AJAX script:
var the_obj = JSON.stringify(photo_annotations);
var post_data = "annotations="+the_obj;
$.ajax({
url: 'ajax/save-annotations',
type: 'POST',
data: post_data,
dataType: 'html',
success: function(data) {
$('#form_results').html(data);
}
});
Try:
$.ajax({
// ...
data: { data: JSON.stringify(photo_annotations) },
// ...
});
If you just set the "data" property to a string, then jQuery thinks you want to use it as the actual query string, and that clearly won't work when it's a blob of JSON. When you pass jQuery an object, as above, then it'll do the appropriate URL-encoding of the property names and values (your JSON blob) and create the query string for you. You should get a single "data" parameter at the server, and it's value will be the JSON string.
Try urldecode or rawurldecode as follows:
<?php
$decoded = json_decode(urldecode($_POST['data']), true);
print_r($decoded);
?>
I rewrote my AJAX function and it now works. I have no idea what was going wrong but decided to test my AJAX function with a very basic data string test=hello world and found that no POST data could be read from the PHP page, even though Firebug says that the page did in fact receive post data matching what I sent. Very strange. Anyway, this is the revised AJAX script:
var the_obj = JSON.stringify(photo_annotations);
var post_data = "annotations="+the_obj;
$.ajax({
url: 'ajax/save-annotations',
type: 'POST',
data: post_data,
dataType: 'html',
success: function(data) {
$('#form_results').html(data);
}
});
The only thing I can think of is that the order of AJAX settings needed to be in a particular order. This is my old AJAX script which does not send POST data successfully - well it does send, but cannot be read!!
var the_obj = JSON.stringify(photo_annotations);
var data_str = "annotations="+the_obj;
$.ajax({
type: 'POST',
dataType: 'html',
data: data_str,
url: 'ajax/save-annotations.php',
success: function(data) {
$('#form_results').html(data);
}
});
in your ajax call try resetting the dataType to json
dataType: "json",
You wouldn't have to use the JSON.stringify() either. On your php script you won't have to decode [json_decode()] the data from the $_POST variable. The data will be easy readable by your php script.

Trying to set variable as part of URL in jquery ajax post

So I am trying to do a post using jQuery.ajax instead of an html form. Here is my code:
$.ajax({
type: 'POST', // GET is available if we prefer
url: '/groups/dissolve/$org_ID',
data: data,
success: function(data){
$('#data_box').html(data);
}
});
Here is my problem:
When this was in an html form, the $org_ID that was part of the URL would actually pull the variable and send it as part of the URL. Now that this is in jquery, its just sending $org_ID as text. How can I get this to figure out what the variable, $org_ID is? I tried declaring it in the javascript but I am brand new to jquery/javascript and don't really know what i'm doing.
Thanks!
Are you rendering this in PHP? In that case you need to do:
url: '/groups/dissolve/<?php print $org_ID; ?>'
Otherwise, you need to do something like
var org_id = 'foo';
// or
var org_id = '<?php print $org_id ?>';
$.ajax({
type: 'POST', // GET is available if we prefer
url: '/groups/dissolve/'+org_ID,
data: data,
success: function(data){
$('#data_box').html(data);
}
});
Unlike PHP, you can't interpolate variables in javascript, you have to concatenate them with the string.
If you're trying to POST a variable (org_id) then you should put it in data:
data['org_id'] = org_id;
$.ajax({
type: 'POST', // GET is available if we prefer
url: '/groups/dissolve/',
data: data,
success: function(data){
$('#data_box').html(data);
}
});
While you can concatenate params onto your url to send them in an HTTP request, putting them in a data object not only lets jQuery do more work for you & escape HTML entities etc (and keep your code cleaner), but also allows you to easily debug and play around with ajax() settings.
It's not clear in the question where your data comes from, but you can use something like:
url: '/groups/dissolve/'+orgId,
or:
url: '/groups/dissolve/?orgId='+orgId,
Short answer, concatinate
url: '/groups/dissolve/' + $org_ID

jQuery.post is not sending data to the specified URL

I have a mobile application and I have a lot of data that I am putting in to a JSON object to store in localStorage. I need to get this data to PHP to process it. I have chosen to use jQuery.ajax to send the data as a JSON object to PHP. However, when I run the function, it gives a success message, but does not go to the url specified. I have a lot of PHP experience but this is my first JS intensive project.
Here is my JS code:
function sendToPHP() {
jQuery.ajax({
type: "POST",
url: "email.php",
data: { "json" : ATRdataJSON},
success: function(data){
console.log("Data Sent!");
},
});
};
ATRdataJSON is a JSON object that has several JSON objects nested inside.
The URL may not be pointing where you think it's pointing. Try:
function sendToPHP() {
jQuery.ajax({
type: "POST",
url: "/email.php",
data: { "json" : ATRdataJSON},
success: function(data){
console.log("Data Sent!");
},
});
};
i'm afraid you cannot send the json object without stringifying it, it may be sent but as a string [object] try to check it first then you may make sure of the url is absolute to make sure it goes to the right controller.

Categories