Strange POST data junk being returned - php

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.

Related

Passing multiple parameters via json.stringify/ajax not working

I have tried searching through SO for an answer to my issue, but all the posts I find still aren't helping me resolve my issue. I don't know if I am overlooking something or if it's just my lack of knowledge that is preventing my code from working.
I have two JS prompts that ask for an ID and then an amount to adjust my stock level. I want it to pass that along to my php file to run a mysql update query.
My script:
<script type="text/javascript">
function sendArray()
{
var ourObj = {};
ourObj.itemId = prompt("Scan ID:");
ourObj.adjAmt = prompt("Enter amount:");
alert(ourObj.itemId);
alert(ourObj.adjAmt);
$.ajax({
url: "save.php",
type: "POST",
data: { invAdj : JSON.stringify(ourObj)},
success: function(response)
{
alert("data sent response is "+response);
},
error: function(e)
{
alert("data not sent"+e);
}
});
}
</script>
<button onclick="sendArray();">Send Array</button>
My php:
if(isset($_POST['invAdj'])) {
$invAdj = json_decode($_POST['invAdj']);
$itemId = $invAdj->itemId;
$amtAdj = $invAdj->amtAdj;
}
mysqli_query($link, "UPDATE stock_levels SET stocklevel = stocklevel + " . $amtAdj . " WHERE id = " . $itemId);
?>
Presently, I get a successful alert, but the level does not change in the db. I know that the db info works and the sql query works because if comment out the post block an add solid variables, it runs perfectly. I have something screwed up in the POST block.
Any help would be greatly appreciated! Again, sorry if this has been answered, but I couldn't find a post that worked...
Also, I know that I shouldn't put the SQL directly into my query. I am just trying to get this working first.
Thanks

losing first data element jquery ajax call

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 +'....

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")

PHP MySQL string showing up as an integer

I have a field called 'score' in a database table that an ajax call is adding values to.
The query below causes it to add values of 1 and 2 under 'score'. It should be looking for "$usrscore1" and "$usrscore2" in my ajax call but it seems to just see the integers (1 and 2) in $us and incorrectly post them as the values under 'score'.
for ( $counter4 = 1; $counter4 <= 2; $counter4 += 1) {
$mess4 = $messages + $counter4;
$us = $usrscore + $counter4;
mysql_query("INSERT INTO messages" . $counter4 . " (`score`)
VALUES ($us)",$dbconn);
}
If I change:
$us = $usrscore + $counter4;
to
$us = $usrscore1;
it correctly looks for $usrscore1 in my ajax call and puts the correct value in the database field under 'score'. But I need it to work in the for loop so just writing it out as $usrscore1 won't work, even though it reads it correctly that way.
Just in case it helps to see it, here's what the ajax call looks like:
$('#rateplugin' + instance).raty({
half: true,
start: totalavgRounded,
click: function(score){
$.ajax({
type: 'POST',
url: 'backend.php',
data: "usrscore"+instance+"="+score+"&action=postmsg",
success: function(xml) {
$.fn.raty.readOnly(true,'#rateplugin' + instance);
}
});
return false;
} // end click
}); // rat
Update:
I may have not been very clear. I set the loop up to only make 2 database tables, but I did that really just for testing purposes. In reality, once this is live, there could be thousands of these to create which is why I'm doing it with a loop. Would the URL variable still be a good solution here? I'm not exactly sure how I would implement it.
My main point of absolute confusion here is that that no matter how I broke up the variable integer from $usrscore it would always ignore the $usrscore part and only see the integer and then just use that as the final value which will always be wrong. Is there something weird about the VALUE MySQL bit that does this? Does anyone have any ideas as to why it is doing that and how to get around it? If that URL variable idea might work, could you please give me some direction into its application here?
from what i can see, you only have limited $usrscore1 and $usrscore2. i suggest you put a single variable $usrscore and populate it based on the parameter in the url.

The most strange error in the world (PHP $_GET, $_POST, $_REQUEST and ajax)

I hope you'll able to help me. I'm fed up of trying things without any solution and php it's just driving me crazy. I'm looking for help because I have a html document where I use ajax thanks to jquery api. Inside this file, in a js function I have:
$.ajax({
type: "GET",
url: "c.php",
data: "dia="+matriz[0]+"&mes="+matriz[1]+"&ano="+matriz[2]+"&diaa="+matriz2[0]+"&mess="+matriz2[1]+"&anoo="+matriz2[2]+"&modo=0&semana=0",
success: Mundo,
error: function(e){
alert('Error: ' + e);
}
});
This code allows me to send the information that I want to the file c.php where I have:
include('funciones.php');
include('config.php');
$mierda = array();
$mierda[0] = $_GET['modo'];
$mierda[1] = $_GET['dia'];
$mierda[2] = $_GET['mes'];
$mierda[3] = $_GET['ano'];
$mierda[4] = $_GET['diaa'];
$mierda[5] = $_GET['mess'];
$mierda[6] = $_GET['anoo'];
$mierda[7] = $_GET['semana'];
As you see it's very simple. My crazy problem is that with firebug I've seen that the data is sent well but for some reason I can't use it. I have tried with $_Get, $_post and $_request and always is the same problem. But this can be stranger... If I put:
echo json_encode($mierda);
then miraculously, the php returns the data that I have passed so in conclusion I have:
I can send the data to the php file well
I can print all the data that I have sent well just accessing yo $_GET, $_POST, $_REQUEST
I can't use any value separatly like $_GET['dia']
What's going wrong there?
PS. The include php files are functions that access to my database so there's no interaction with them.
Your data is not URL-encoded. Try do something like this,
$.ajax({ type: "GET",
url: "c.php",
data: {"dia":matriz[0], "mes":matriz[1] ....},
success: Mundo,
error: function(e){ alert('Error: ' + e); }
});
If you are returning a json value use json to read that.
See
http://api.jquery.com/jQuery.getJSON/
http://pinoytech.org/blog/post/How-to-Use-JSON-with-jQuery-AJAX
Here is an example to read json value
$('document').ready(function(){
$('#submit).click(function(){
$.post('your_php_page.php', {employee_id: '456'},
function(data){
console.log(data.first_name);
console.log(data.last_name);
}, 'json');
})
});
Hope it helps
You have a crazy problem. According to your question:
$mierda = array();
$mierda[0] = $_GET['dia']; //... and so on
echo json_encode($mierda);
works while:
echo $_GET['dia'];
doesnt. Try:
$mierda = array();
$mierda[0] = $_GET['dia'];
echo $mierda[0];
echo $_GET['dia'];
It will show you whether the problem is in the PHP, or the javascript.
I have encoded the data as ZZColer said and the error is still.
Starx, it's not a question of the returning.
digitalFresh, in fact the error is from PHP because I can copy $_POST, $_GET array to a new array and print all this information but if I put after all things like:
If( mierda[0] == 0) {... The element is empty! and if I try directly $_GET['dia'] it says that this element doesn't exist in the array. Also I have tried $_GET[dia] or $_GET[0] without a solution.
PD:
I don't know how but PROBLEM SOLUTIONED!
Thanks to all!

Categories