$_POST not being set with AJAX Post value - php

I'm trying to send a JSON object to a .php file. What troubles me is that my POST value doesn't seem to get into PHP's $_POST array. Here is my code:
jQuery:
$("#submit").click(function(){
var obj = { //create json object to be sent
"name": $("#name").val(),
"email": $("#email").val(),
"r1": $("#r1").val(),
"r2": $("#r2").val(),
"r3": $("#r3").val(),
"intr1": $("#q1").val(),
"intr2": $("#q2").val(),
"intr3": $("#q3").val(),
"set": "set1"
};
var jsonObj = JSON.stringify(obj);
$.post(
"updateAnswers.php",
jsonObj,
function() {
//location.href = 'set2.php';
}
);
})
PHP:
if (isset($_POST["jsonObj"])) { // value is empty
$obj = json_decode($_POST['jsonObj'], true);
$name = $obj['name'];
$email = $obj['email'];
$db = mysqli_connect("localhost", "root", "", "concurs");
$sql="INSERT into players values ('$name', '$email', '0', '0', '0')";
mysqli_query($db, $sql);
}
Thanks in advance!

I dont think you need to stringify obj - try passing obj straight to the $.post function.
$.post("updateAnswers.php", obj, function() {
//location.href = 'set2.php';
});
On the PHP side, the values name, email, r1, etc.. will be directly in the $_POST array.. so you will need to access $_POST['name'] and so on.
echo "Name: ". $_POST['name']; //Show name value
var_dump($_POST); //Show all passed values
Your $sql string does not check for SQL injection. You must (at the very least) replace single quotes with two single quotes like:
$sql = "INSERT into players values ('".str_replace("'","''", $name). "', '".str_replace("'","''", $email). "', '0', '0', '0')";

You are using stringify on your obj and then you pass it to the ajax-function.
But the ajax-function expects the object as objetct not as string.
So just remove var jsonObj = JSON.stringify(obj); and just use obj
Furtermore you have to check for
name
email
r1
...
in your php-script instead of jsonObj because thats what the php actually gets from your script

This with AJAX() send:
$.ajax({
type: 'POST',
url: 'updateAnswers.php',
data: {'jsonObj': jsonObj},
success: function(msg) {
alert(msg);
}
});

Related

Ajax + PHP: null instead of an array

Ajax call is made in the background
var signupValidate = function(elementID){
var value = $('#' + elementID).val();
if (value !== ''){
$('#'+elementID+'-status').css("background-image", "url(img/signup/spinner.gif)");
var data = {elementID: value};
var json = JSON.stringify(data);
$.ajax({
url: 'php/validator_signup.php',
dataType: 'json',
type: 'post',
data: json,
success: function(data){
var parsedResponse = JSON.parse(data);
console.log(parsedResponse);
/*
if(data.response === 1){
$('#'+elementID+'-status').css("background-image", "url(img/signup/no.png)");
}else if(data.response === 0){
$('#'+elementID+'-status').css("background-image", "url(img/signup/yes.png)"); }
*/
}
});
}
}
validator_signup.php received the call. So far in test mode PHP will receive the string, parse it and encode again to return to JS:
$post = $_POST['data'];
$data = json_decode($post, true); //decode as associative array
$details = $data[0];
echo json_encode($details);
JS then needs to print this in console.
I get this:
null
instead of the value which I expect back.
Result is same whether I parse returned data or not.
If I understand it correctly, the problem is on PHP side?
There does not appear to be any value in converting to json when your data is so simple, you can just use a regular js object that jquery will convert to form data.
Also, as both the key and value you send are unknown, i would suggest sending the data in a different structure so its easy to retrieve:
var signupValidate = function(elementID){
var value = $('#' + elementID).val();
if (value !== ''){
$('#'+elementID+'-status').css("background-image", "url(img/signup/spinner.gif)");
$.ajax({
url: 'php/validator_signup.php',
type: 'post',
// ▼key ▼value ▼key ▼value
data: { id: elementID, val: value},
success: function(response){
console.log(response.message);
}
});
}
}
In php you can access the data via $_POST, and as you know the keys, its simple:
<?php
$id = $_POST['id'];
$val = $_POST['val'];
//set correct header, jquery will parse the json for you
header('Content-Type: application/json');
echo json_encode([
'message'=>'Request received with the id of: ' . $id . 'and the value of: ' . $val,
]);
die();
Change:
data: json,
To:
data: { data: json},
This is because you aren't giving the sent data a POST parameter to then be used server side to retrieve it.
Then, you can simply fetch the code server-side like this:
$data = json_decode($_POST['data']);
Hope this helps!
Here, since you are checking whether data is being post, if you see in Network, no data is being posted. To fix it, change this part:
var data = {elementID: value};
To this:
var data = {data: {elementID: value}};
Consider removing conversion of Data
PHP automatically handles the $_POST as an array! So you don't need to use the reconversion. Please eliminate this part:
var json = JSON.stringify(data); // Remove this.
And in the server side:
$data = json_decode($post, true); // Remove this
$data = $_POST['data']; // Change this
Update
OP said data[elementID]:gh is sent to the PHP file.
If this is the case, then if the data needs to be "gh" in JSON, then:
$res = $_POST["elementID"];
die(json_encode(array("response" => $res)));
This will send:
{
"response": "gh"
}
And in the client side, you don't need anything other than this:
$.post('php/validator_signup.php', function (data) {
var parsedResponse = JSON.parse(data);
console.log(data);
});
JSON data is sent to the server as a raw http input it is not associated with query name like $_POST['data'] or anything like that which means you must access the input string not a data post value to do so you need to use
$rawInput = json_decode(file_get_contents('php://input'), true);
$elementValue = $rawInput['elementId'];
thats it
$_POST = json_decode(file_get_contents('php://input'), true);
$data = $_POST['data'];

how to pass AJAX response value to PHP variables?

I want to use the result value and pass it to php variable,
here is my code...
billingCoffee.php
$("#linkAddSize").click(function(e){
e.preventDefault();
var txtCoffeeName = document.getElementById("txtCoffeeName").value;
var cmbSizes = document.getElementById("cmbSizes").value;
var txtPrice = document.getElementById("txtPrice").value;
$.ajax({
url: "addSizeandPrice.php",
type: "POST",
data: {coffeename: txtCoffeeName, sizes: cmbSizes, price: txtPrice},
datatype: "json",
success: function (result){
//set it php variable
}
});
});
addSizeandPrice.php
if($tableresult){
$query = "INSERT INTO tbl$CoffeeName (CoffeeSize, Price) VALUES ('$Size', '$Price');";
$insertresult = mysqli_query($con, $query);
if($insertresult){
SESSION_START();
$_SESSION['nameCoffee'] = $CoffeeName;
echo $_SESSION['nameCoffee'];
}
else{
echo "Something went wrong!";
}
}
I want to use the variable without refreshing the page... and I got this idea to use AJAX but don't know how to set it in php variable.
You are using POST as the method to send variables to your PHP script. So in PHP, they will be in the superglobal named $_POST
For example,
$coffeename = $_POST['coffeename'];
Further reading: http://php.net/manual/en/reserved.variables.post.php
Please also do some research about preventing SQL injection.

Phonegap, AJAX - PHP Array Issue

I am in trouble while pass user's input value via array from HTML (Using AJAX) To php page (In fetching Array) .
Is method I use is correct ? I didn't get value in my PHP page.
First I assign user's value to variable
var first_name = $("[name='first_name']").val();
var last_name = $("[name='last_name']").val();
Then Create Its array.
var MyArray = {"firstname": first_name, "lastname": last_name};
And Here How I pass value to external server's php file
$.ajax({
type: "POST",
url: GolbalURL+"updategeneralinformation.php",
data: "userarray="+ MyArray,
dataType:'json',
success: function(response){
if(response.success) {
navigator.notification.alert(
'Ok',
// No need for Callback function
'Ok',
'Ok'
)
}
else {
navigator.notification.alert(
'Something went wrong while attempting update',
// No need for Callback function
'Atempt Fail',
'Try Again'
)
}
},
error: function(error){
navigator.notification.alert(
error,
// No need for Callback function
'Something wrong',
'Try Again'
)
}
});
return false;
Now PHP File code for retrieve Requested array from HTML page and run PHP-MySQL Update Query
$get_array = $_REQUEST['userarray'];
$query = mysql_query("UPDATE ".$db.".users SET first_name='$get_array["firstname"]', last_name='$get_array["lastname"]' ");
mysql_query($query);
if (!mysql_query($query, $con)) {
//die('Error: ' . mysql_error());
$response['success'] = false;
} else {
$response['success'] = true;
}
Use
data: MyArray,
or
data: {firstname: first_name, lastname: last_name},
instead of
data: "userarray="+ MyArray,
at server side
$get_array = $_POST;
and
$query = mysql_query("UPDATE ".$db.".users SET first_name='" . $get_array["firstname"] . "', last_name='" . $get_array["lastname"] . "'");
Note: the mysql_query is deprecated, use pdo or mysqli, and its unsecure in this form (mysql_real_escape_string() missing)
You've convert your javascript array into a string when you do this:
data: "userarray="+ MyArray,
So basically, php just gets a string.
You may want to do this in your javascript:
var MyArray = {"firstname": first_name, "lastname": last_name};
data: MyArray,
Or
data: {"firstname": first_name, "lastname": last_name},
And in your php script:
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
var MyArray = {"firstname": first_name, "lastname": last_name};
data: MyArray,

Insert query in php not working with ajax

I am having some problems with insert query which is called from ajax. The ajax call comes back with success and I am able to see it with the changed html as noted below in the code under success:function(). I am not sure why the insert query in process.php is not working. dataString has the arguments correct (alert for dataString shows the right arguments) and my fields in database can take null values.
js code
var dataString=$('#testimonials').serialize();
alert (dataString);
$.ajax(
{
type: "POST",
url: "process.php",
data: dataString,
success:function() {
$('#testimonials').html("<div id='message'></div>");
$('#message').html("<h2>Your information has been submitted!</h2>")
.append("<p>Thank you for your help and support.</p>")
.hide()
.fadeIn(1500, function()
{
$('#message').append("<img id='checkmark' src='images/check.png' height='30' width='30'/>");
});
});
process.php file
$company =mysql_escape_string($_POST('company'));
$jobfunc = mysql_escape_string($_POST('jobfunc'));
$location = mysql_escape_string($_POST('location'));
$overall = mysql_escape_string($_POST('overall'));
$detail = mysql_escape_string($_POST('detail'));
$pros = mysql_escape_string($_POST('pros'));
$cons = mysql_escape_string($_POST('cons'));
$sr_mgmt = mysql_escape_string($_POST('sr_mgmt'));
$submitted_by = mysql_escape_string($_POST('submitted_by'));
$class = mysql_escape_string($_POST('classof'));
$school = mysql_escape_string($_POST('school'));
$anonymous = mysql_escape_string($_POST('anonymous'));
mysql_select_db($database_connTest, $connTest);
$query_AddTestimonial = "INSERT into testimonials (company,job_function,location,overall,project_details,pros,cons,sr_mgmt,submitted_by,class,school,anonymous) VALUES ('$company','$jobfunc','$location','$overall','$detail','$pros','$cons','$sr_mgmt','$submitted_by','$class','$school','$anonymous')";
$result_AddTestimonial = mysql_query($query_AddTestimonial) or die(mysql_error());
In the penultimate line when you create $query_AddTestimonial, the string you're creating isn't putting the php variables in because you're not telling it that they're variables. You can use the php variables like this:
$query_AddTestimonial = "INSERT into testimonials (company,job_function,location,overall,project_details,pros,cons,sr_mgmt,submitted_by,class,school,anonymous) VALUES ('{$company}','{$jobfunc}','{$location}','{$overall}','{$detail}','{$pros}','{$cons}','{$sr_mgmt}','{$submitted_by}','{$class}','{$school}','{$anonymous}')";
The problem was with the way I was calling the variables. It should have been $_POST['company'] rather than $_POST('company'). Completely missed it (the square brackets for $_POST since its an array)

method to move multiple variables (array?) from jquery to PHP

I was chasing after JSON as a method to do this, but I'm wondering if I should have been looking in a different direction. I'll tackle this as simply as possible.
Jquery from "page1.php"
$(".button").click(function() {
var name = "Jeremy";
var car = "Saturn";
var color = "blue";
var state = "Mississippi";
// I need all four of these to get passed over to PHP in the following ajax
$.ajax({
url: "page2.php",
//dataType: '???????',
type: 'POST',
data: 'mydata=' + ????????,
success: function(result) {
alert(result);
}
});
});
So there are four jquery variables that I've fudged. Now I need to hand them over to page2.php for my backend PHP. Here is page2.php
if (filter_has_var(INPUT_POST, "mydata")) {
$mydata = mysql_real_escape_string(filter_input(INPUT_POST,'mydata'));
// Here I need to turn these into variables, or just an array and then throw them into my SQL
mysql_query("INSERT INTO mysqldata (namefield, carfield, colorfield, statefield)
VALUES ($name, $car, $color, $state)");
$sqlresult = mysql_insert_id;
if ($sqlresult != '') {
echo "SQL successfully updated.";
}
}
Thus, my question is: What is the most effective method to pass the data to PHP, in this case?
There's probably a simple answer here that I just don't know. Can I turn those jquery variables into an array and hand them to PHP that way? Is JSON still the best way to go, and I just need to know how to convert it on the back end?
As an array
var mydata = [name, car, color, state];
Or as an object
var mydata = { 'name' : name, 'car' : car, 'color' : color, 'state' : state };
-
$.ajax({
...
data: mydata
...
JavaScript/jQuery
$(".button").click(function() {
// create the data object
var myData = {
name : 'Jeremy',
car : 'Saturn',
color: 'blue',
state: 'Mississippi'
};
$.ajax({
url: "page2.php",
//dataType: '???????',
type: 'POST',
data: myData,
success: function(result) {
alert(result);
}
});
});
PHP
// check if the name has been posted, which means we have a submission to process
if(isset($_POST['name'])){
$query = sprintf("INSERT INTO mysqldata (namefield, carfield, colorfield, statefield) VALUES ('%s', '%s', '%s', '%s')",
mysql_real_escape_string($_POST['name']), // clean malicious code
mysql_real_escape_string($_POST['car']), // from user input
mysql_real_escape_string($_POST['color']), // to protect against
mysql_real_escape_string($_POST['state'])); // SQL injection
// run the query
$result = mysql_query($query);
// check if the insert was done successfully
if($result){
echo 'SQL successfully updated.';
}
}
If you notice, based on the id we used on the javascript object to assign the data, we are accessing it in the $_POST array. E.g.
The name
var myData = {
name : 'Jeremy',
...
}
Will be access on PHP side with
$_POST['name']
Hope this blog posts helps you..
http://www.factsandpeople.com/facts-mainmenu-5/26-html-and-javascript/89-jquery-ajax-json-and-php
It focuses on using json_decode method to decode the json

Categories