losing first data element jquery ajax call - php

I am having a problem that I cannot figure out.
I am using the tableDND jQuery add in, which allows me to drag and drop rows of a table. I want to send those rows to the server and have them uploaded to a mySQL database.
My code is below, basically when I get to the PHP the first element of the batting variable is gone. Any ideas?
So I have the following javascript:
$('#order').tableDnD({
onDrop: function(table, row) {
var batting = $.tableDnD.serialize();
var id = <?php echo $id;?>;
$.ajax({
type: 'POST',
url: 'update_batting.php',
data: '{ "batting":' + batting + ', "id":'+ id +' }',
dataType: 'json',
});
}
});
and the following php:
<?php
$batting = json_encode($_POST['order']);
$query = "INSERT INTO test (t) VALUES ('$batting')";
mysql_query($query);
?>

Ok so this is my crude guess at this one since I have to go soon...
I think since "data" is converted to a query string it is being misread.
I think your post is probably reading this:
$_POST['batting'] = 'order[]=110209';
$_POST['order'] = 'order[]=100245&order[]=100007&order[]=100296&order[]=10‌​0213&order[]=100071&order[]=100125&order[]=110206&order[]=110205&order[]=100152&o‌​rder[]=100247&order[]=100329&order[]=100299&order[]=100243';
$_POST['id'] = '662852670';
Because the first occurrence of the ampersand is terminating your variable.
It might seem silly, but you can probably escape this whole problem by surrounding "batting" with double quotes. Effectively containing it as a string.
data: '{ "batting":"' + batting + '", "id":'+ id +' }',
This would change your expected $_POST['order'] variable to "$_POST['batting']
However, your data object should be contained like I originally mentioned in the comment above.
data: {order: '"' + batting + '"', id:id},
Instead of sending it as a string with no key as in your sample code.
Try var_dump($_POST) in php to see all values you're getting... just out of curiosity.
**Sorry for all the edits. I'm being distracted constantly at work...

Have you tryed to remove the spaces on each side of ' + batting + ' ....
like '+ batting +'....

Related

php lost some path of string after submition using ajax post

I am trying to submit a comment using ajax post with php, it's working very fine as i expected it to but when i try to submit some sting that contain & it lossess path of the sting only show from beginging till where the and is.
I really don't know how to fix this, i have no idea about what is the problem please i need help.
See example
MY ajax
<script>
$('#submitcomment').on('click', function(){
try{
var message = $('.commentTextinput').val();
var key= $(this).attr('data-keyname');
$.ajax({
url: UrlExistsA('snippet/snippetcomment'),
data: 'message=' + message + '&key=' + key,
type: 'POST',
beforeSend: function(){
$('#submitcomment').html('Wait....');
},
success: function(data){
$('tr.replyList:last-child').after(data);
$('.commentTextinput').val('');
$('#submitcomment').html('Comment');
},
error: function(data){
alert('Processing Error' + '<br/>' + data);
}
});
}catch(err){alert(err.message);}
finally{}
});
</script>
Here is test php
<?php
if(isset($_POST['message'])){
$postReply = htmlentities($_POST['message'], ENT_QUOTES, "UTF-8");
echo $postReply;
}
The above will output this
tomorrow we will run faster, stretch out our arms farther... And then
one fine morning
But the original string posted was
tomorrow we will run faster, stretch out our arms farther... And then
one fine morning— So we beat on, boats against the current,
borne back ceaselessly into the past.
also when i tried to submit &&&&&&&&&&&&&&&&&&&&&&& it return empty But when i echo the above string without using ajax it was very okay
You need to call encodeURIComponent to encode special characters in the parameter string. & is the separator between parameters, so you need to encode it.
data: 'message=' + encodeURIComponent(message) + '&key=' + encodeURIComponent(key),
But a simpler way is to use an object instead of a string, then jQuery will encode it automatically.
data: { message: message, key: key },

jQuery posts error text when posting with ajax

When I'm posting via ajax I'm sometimes getting extra characters posted for example. If the text passed though ajax yo a php $_POST I end up getting:
This is my messagejQuery127638276487364873268_374632874687326487
99% of the time posts pass though fine... I'm unsure how to capture and remove this error as it only happens some of the time.
// this is the ajax that we need to post the footprint to the wall.
$('#submitbutton').click(function () {
var footPrint = $('#footPrint').val();
var goUserId = '1';
$.ajax({
type: 'POST',
url: '/scripts/ajax-ProfileObjects.php',
data: 'do=leave_footprint&footPrint=' + footPrint + '&ref=' + goUserId + '&json=1',
dataType: 'json',
success: function(data){
var textError = data.error;
var textAction = data.action;
var textList = data.list;
if (textError == 'post_twice' || textError =='footprint_empty' || textError == 'login_req') {
// display the error.
} else {
// lets fade out the item and update the page.
}
});
return false; });
Try set cache to false. From http://api.jquery.com/jQuery.ajax/
cache Boolean
Default: true, false for dataType 'script' and 'jsonp'
If set to false, it will force requested pages not to be cached by the browser. Setting cache to false also appends a query string parameter, "_=[TIMESTAMP]", to the URL.
I found out through a process of elimination that the error was being caused by invalid data being passed to the query string.
The line:
data: 'do=leave_footprint&footPrint=' + footPrint + '&ref=' + goUserId + '&json=1',
I noticed that the footPrint variable would always break the script if '??' was passed. A number of members when asking a question would use a '??' when and not a single '?'
By wrapping the footPrint var in encodeURIComponent() I can send all the text though to the PHP script without breaking the URL string.
New Line:
data: 'do=leave_footprint&footPrint=' + encodeURIComponent(footPrint) + '&ref=' + goUserId + '&json=1',
This solution has worked for me... questions comments and suggestions still welcome.

Lacking of Serializing or Encoding

function autosave()
{
setTimeout("autosave()", 15000);
var did = $("#did").val();
var content = $('.nicEdit-frame').contents().find('#nicEditContent').html();
if (content.length > 0)
{
$.ajax(
{
type: "POST",
url: "inc/autosave.class.php",
data: "did=" + did + "&content=" + content,
contentType: "application/x-www-form-urlencoded;charset=ISO-8859-15",
cache: false,
success: function(message)
{
$("#message").empty().append(message);
}
});
}
}
What this does is takes what is in a textarea and sends it over to the autosave.class.php, which sends it off to the MySQL database.
The problem is that the data ends up in the database cut off, showing only the first few sentences of it; often cutting off at the quotation mark.
I am positive that this isn't the PHP to MySQL issue (already tested that), it's the AJAX/JQuery data to PHP part.
Is it the lack of serializing/encoding? If so, how would I fix it?
Have your data properly escaped, if someone puts Me & You in a field, the field will only contain Me since & is considered a argument separator.
data: "did=" + encodeURIComponent(did)
+ "&content=" + encodeURIComponent(content),
If data is still truncated, check the size of your database fields. MySQL does not fail if the passed data is larger than the field can actually hold.
You should let jQuery build the POST string for you by passing an object:
data: { did: did, content: content },
Couldn't you use serialize? http://api.jquery.com/serialize/

Strange POST data junk being returned

I'm writing a fairly basic commenting function for a site using post method to pass input values to a php file that performs the relevant mysql query.
The $.ajax part is as follows:
// AJAX URL ENCODING
$("#add").click(function() {
// POST COMMENT FORM VALUES
var ajaxOpts = {
type: "post",
url: "includes/addComment.php",
data: "&author=" + $("#author").find("input").val() + "&email=" + $("#email").find("input").val() + "&comment=" + $("#leaveComment").find("textarea").val() + "&parent=<?php echo $vid_id; ?>",
success: function(data) {
// IMMEDIATE DISPLAY
// Not relevant to this problem.
// CLEAR TEXTAREA FOR NEXT COMMENT
$("textarea").val('');
}
};
$.ajax(ajaxOpts);
});
This is passed through to addcomment.php:
require('connection.php');
//get POST data
$name = mysql_real_escape_string($_POST["author"]);
$email = strtolower(md5(trim(mysql_real_escape_string($_POST["email"]))));
$comment = mysql_real_escape_string($_POST["comment"]);
$time = Date ('c');
$parent = trim(mysql_real_escape_string($_POST["parent"]));
//add new comment to database
mysql_query("INSERT INTO comments VALUES(' $name ',' $email ',' $comment ', ' $time ', ' $parent ')");
Everything works fine except that the mysql_query doesn't end up inserting any values into my database. After a bit of digging I found this:
So i'm assuming my query isn't going ahead because the ' : ' bit of junk(?) data is throwing everything out?
I'm trying to figure out where this errant ' : ' has come from, anyone have any ideas?
P.S - Apologies for the length of this question, I've tried to narrow down possible culprits as much as I can.
You dont have to do that URI encoding yourself. Read the documentation of jquery, the 'data' to be sent could be a map/json.
http://api.jquery.com/jQuery.post/
change
data: "&author=" + $("#author").find("input").val() + "&email=" + $("#email").find("input").val() + "&comment=" + $("#leaveComment").find("textarea").val() + "&parent=<?php echo $vid_id; ?>"
into
{ author: 'something',email:'test' }
or more professionally
$("#testform").serialize() //here #("#testform") stands for a '<form>' tag
And try not to complicate the problem, start with some simple functions, use more echo() and alert() to debug.
what happens if you remove the & from the front of &author?
normally the first data field doesn't have an &
data: "&author="
also as others have mentioned this would be a welcome addition
or die (mysql_error())
and its usually good practice to name your database columns on the insert
otherwise you risk breaking the insert statement if you ever alter the table structure
insert into (colname1, colname2) values ('value1', 'value2')
you can print_r($_POST) to see if the colon is really there.
secondly, while debugging it wouldn't hurt to throw an
or die (mysql_error())
at the end of your query.
Without those two, it's hard to debug.
2 things :
ajaxOpts variable is out of scope , you will have a error ( ajaxOpts is not defined)
In you example, you miss }); at the end , you should check your JS validate too before checking your php script is working. If you have a JS error, the ajax call will not be called.

jQuery ajax callback not firing jQuery code

I have a checkbox on a webpage that when you click it, updates the value in the database as well as the editedBy and editedDate columns in a table in the database. I am doing the update via an ajax call to a php page. I am trying to get the updated editedDate and editedBy data in the callback on success so i can update the sorresponding span tags that hold this information. I'm trying to use jQuery to accomplish this. This is what i have so far:
var updateUserDate = function(data){
var table = data.table;
var rowId = data.rowId;
var editedDate = data.editedDate;
var editedBy = data.editedBy;
//alert(table+' - '+rowId+' - '+editedDate+' - '+editedBy);
$('"#'+table+' .row'+rowId+' .newEditedDate"').html('"'+editedDate+'"');
}
var submitDataCheckbox = function(target){
var project = target.attr('project');
var tableName = target.attr('table');
var rowId = target.attr('rowId');
var checkboxValue = (target.attr('checked'))?true:false;
$.ajax({
type: 'GET',
url: '/checklistpost.php?projectId='+project+'&table='+tableName+'&rowId='+rowId+'&value='+checkboxValue,
success: function(data){
updateUserDate(data);
},
error: function(){
alert('There was an error submitting data to the database.');
},
dataType: 'json'
});
}
The checklistpost.php page takes the variables that are in the query string and posts them to the database. It also then puts the variables in an array which is then encoded in json so that i have a json object to work with. Basically, i am trying to take that json object that gets called back and use it to update the span as mentioned above. When i have used an alert() inside of the updateUserDate function before to verify that i can see the variables and they all have the right data (you can see the code i used to do this is commented out). However, whenever i try and use the variables with jQuery as you see on the 6th line of the code. It doesn't do anything. BTW, The jQuery code that should be output based on what is written above should look like this $("#tableName .row1 .newEditedDate").html("April 14, 2011 # 5:15pm") What am i missing? Thanks in advance for any help!
Your selector is broken, you've got extra quotes in there:
'"#' + table+' .row' + rowId + ' .newEditedDate"'
should be:
'#' + table + ' .row' + rowId + ' .newEditedDate'
So:
// you're surrounding editedDate with extra quotes too, or is that intentional?
$('#' + table + ' .row' + rowId + ' .newEditedDate').html(editedDate);
Why are you using single and double quotes? The command you are passing to jQuery will evaluate to this:
$('"#tableName .row1 .newEditedDate"').html('"April 14, 2011 # 5:15pm"')
instead of this:
$("#tableName .row1 .newEditedDate").html("April 14, 2011 # 5:15pm")

Categories