Jquery Ajax returns 400 BAD request - javascript

I'm trying to send data to my local DB server but I keep getting 400 Bad request error when I try to send it.
var studentEmail = "ali#gmail.com";
var dataString = '&questionNumber='+ temp + '&answer='+ value + '&email='+ studentEmail;
$.ajax({
type: "POST",
dataType:'json',
url: "js/dbcon.php",
data: JSON.stringify(dataString),
processData: false,
contentType: "application/json; charset=utf-8"
});
and this is the php file
<?php
$connection = mysql_connect("127.0.0.1", "root", "root"); // Establishing Connection with Server..
$db = mysql_select_db("db", $connection); // Selecting Database
//Fetching Values from URL
$questionNumber=$_POST['questionNumber'];
$answer=$_POST['answer'];
$email=$_POST['email'];
//Insert query
$query = mysql_query("INSERT INTO answers (questionNumber,studentAnswer,studentEmail) VALUES ($questionNumber,$answer,$email)");
echo "succesfully posted";
mysql_close($connection); // Connection Closed
?>
can anyone see what I'm doing wrong?
Thanks in advance!

JSON.stringify() method is used to turn a javascript object into json string.
So dataString variable must be a javascript object:
var data ={questionNumber:temp ,answer: value ,email:studentEmail};
AJAX
$.ajax({
type: "POST",
dataType:'json',
url: "js/dbcon.php",
data: JSON.stringify(data),
processData: false,
contentType: "application/json; charset=utf-8"
});

if you change the post to get you have to replace $_POST with $_GET into your php file.

There is an easier way to pass data that will work correctly for both POST and GET requests
var studentEmail = "ali#gmail.com";
$.ajax({
type: "POST",
dataType:'json',
url: "js/dbcon.php",
data: {questionNumber:temp, answer:value, email: studentEmail},
processData: false,
});
Now jQuery does all the hard work and converts the object full of data to whatever format is required for a POST or GET request

You can send the ajax request this way:
var studentEmail = "ali#gmail.com";
$.ajax({
type: "POST",
dataType:'json',
url: "js/dbcon.php",
data: ({'questionNumber':temp,'answer':value, 'email':studentEmail }),
processData: false,
contentType: "application/json; charset=utf-8"
});
Also the PHP file needs to return a json string as well.
echo "succesfully posted";
is no valid json answer.
Return something like this:
$arr = array('success' => true, 'answer' => "succesfully posted");
echo json_encode($arr);
See also here: http://php.net/manual/de/function.json-encode.php
You should validate the input data, before inserting into the database.

Related

send data to php using ajax post method

I am trying to pass data to php code using ajax. but I cant get is success.
<?php
$message = $_POST["message"];
$buyer_name = $_POST["buyer_name"];
$order_number = $_POST["order_number"];
$account = $_POST["account"];
$designer = $_POST["designer"];
echo $message; ?>
this is my js code.
var formdata = {buyer_name:byrName,order_number:orderNum.trim(),account:account,designer:'admin',message:'testing'}
if(autoMode){
$.ajax({
type:'POST',
url: 'msgHandle.php',
data: formdata,
contentType: false,
cache: false,
processData: false,
beforeSend: function() {
},
success: function(data) {
alert(data);
},
error: function() {
alert('failed');
}
});
I have set a button to click and when clicked in runs this ajax code. the output is a alert with empty message. that means it success but seems like variables does not pass correctly to the php code. what is wrong in my code, I can't find.
I tried your code and found that by removing all the three parameters
contentType: false,
cache: false,
processData: false,
From the code posts your data onto another page.
Tried for just a sample array.

Why is my JQuery variable not sending to php?

I have a variable which contains data, i'm then using a ajax function to send this variable data to this php file. I'm slightly unsure I can store this variable into php and echo it out. This is the code that I currently have...
var data = 1
// Sending this data via ajax to php file/
$.ajax({
type: 'post',
cache: false ,
url: 'function.php',
data: data,
success: function(data) {
alert ( data );
}
});
This is my php code
$noteone = $_POST['data'];
echo $noteone;
Any help would greatly be appreciated
data of your ajax call should be like below. Hope it will solve your problem.
data: { "data": data }
You also need to set the data type:
var data = 1
// Sending this data via ajax to php file/
$.ajax({
type: 'post',
cache: false ,
url: 'function.php',
data: { "data": data },
dataType: "json", // <---- THIS ONE
success: function(data) {
alert ( data );
}
});
Try this :
var data = 1
// Sending this data via ajax to php file/
$.ajax({
type: 'post',
cache: false ,
url: 'function.php',
data: JSON.stringify(data),
contentType: "application/json",
success: function(data) {
alert ( data );
}
});
PHP requires data to be submitted in key=value format when building $_POST/$_GET. You didn't do that. You only submitted value, so PHP has no key to populate $_POST with. You need to have:
data: { "whatever_you_want": data }
which becomes
$_POST['whatever_you_want']

JS array send to php is returning as empty [duplicate]

Im submitting Data to a php file via AJAX using POST.
It worked fine with just submitting strings, but now I wanted to submit my JS Object with JSON and decode it on PHP side.
In the console I can see, that my data is submitted correctly but on PHP side json_decode returns NULL.
I've tried the following:
this.getAbsence = function()
{
alert(JSON.stringify(this));
jQuery.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "ajax/selectSingle.php?m=getAbsence",
data: JSON.stringify(this),
success : function(data){
alert(data);
}
});
}
PHP:
echo $_POST['data'];
echo json_decode($_POST['data']);
echo var_dump(json_decode($_POST['data']));
And:
this.getAbsence = function()
{
alert(JSON.stringify(this));
jQuery.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "ajax/selectSingle.php?m=getAbsence",
data: {'Absence' : JSON.stringify(this)},
success : function(data){
alert(data);
}
});
}
PHP:
echo $_POST['Absence'];
echo json_decode($_POST['Absence']);
echo var_dump(json_decode($_POST['Absence']));
The alert was just to check everything is alright...
And yea usual string were echoed correctly :-)
Where you went wrong in your code in the first code is that you must have used this:
var_dump(json_decode(file_get_contents("php://input"))); //and not $_POST['data']
Quoting from PHP Manual
php://input is a read-only stream that allows you to read raw data from the request body.
Since in your case, you are submitting a JSON in the body, you have to read it from this stream. Usual method of $_POST['field_name'] wont work, because the post body is not in an URLencoded format.
In the second part, you must have used this:
contentType: "application/json; charset=utf-8",
url: "ajax/selectSingle.php?m=getAbsence",
data: JSON.stringify({'Absence' : JSON.stringify(this)}),
UPDATE:
When request has a content type application/json, PHP wont parse the request and give you the JSON object in $_POST, you must parse it yourself from the raw HTTP body. The JSON string is retrieved using file_get_contents("php://input");.
If you must get that using $_POSTyou would make it:
data: {"data":JSON.stringify({'Absence' : JSON.stringify(this)})},
And then in PHP do:
$json = json_decode($_POST['data']);
Single quotes are not valid for php's json_encode, use the double quotes for both field names and values.
To me, it looks like you should reformat your AJAX object. The url-property should only be the URL for the target php-file and any data that needs to be posted should be in the form of a query-string in the data-property.
The following should work as you expected:
this.getAbsence = function() {
var strJSONData = JSON.stringify(this);
alert(strJSONData);
jQuery.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: 'ajax/selectSingle.php',
data: 'm=getAbsence&Absence=' + strJSONData,
success: function(data) {
alert(data);
}
});
}
try this
var vThis = this;
this.getAbsence = function()
{
alert(JSON.stringify(vThis));
jQuery.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "ajax/selectSingle.php?m=getAbsence",
data: JSON.stringify(vThis),
success : function(data){
alert(data);
}
});
}
EDIT
I think we can also do this!
var vThis = this;
this.getAbsence = function()
{
alert(JSON.stringify(vThis));
jQuery.ajax({
type: "POST",
dataType: "json",
url: "ajax/selectSingle.php?m=getAbsence",
data: vThis,
success : function(data){
alert(data);
}
});
}
and in PHP
print_r($_POST);
On PHP side try this:
$sectionValue = htmlspecialchars($_POST['sectionValue'], ENT_QUOTES);
$dataToWrite = json_decode(html_entity_decode($sectionValue, ENT_QUOTES, "utf-8" ), true);

Sending Multidimentional array data, with ajax, to a php script

I have two simple scripts. One client-side jquery that has multidim array & a server-side php script. in php $data stays empty.
jquery
console.log("IN JQUERY");
console.log(inps);
$.ajax({
type: 'post',
cache: false,
url: './gen.php',
data: inps,
success: function(response){
console.log("RESPONSE");
console.log(response);
}
});
gen.php
<?php
$data = file_get_contents('php://input');
$data = json_decode($data, true);
print_r($data);
?>
firefox console output
>POST ..././gen.php [HTTP/1.1 200 OK 1ms]
>"IN JQUERY"
>{isbranch: "1", ismanager: "0", isdept: "1"}
>"RESPONSE"
>""
Is there a way to send Multi Dimensional array to the php with ajax without spliting array?
You should use JSON.stringify to encode your data before send it, also better to add correct contentType to it:
$.ajax({
type: 'post',
cache: false,
url: '/gen.php',
data: JSON.stringify(inps),
contentType: 'application/json',
success: function(response){
console.log("RESPONSE");
console.log(response);
}
});
The key-value pairs should already exist in your $_POST
$isbranch = $_POST['isbranch'];
$ismanager = $_POST['ismanager'];
$isdept = $_POST['isdept'];

Issue with decoding json array in php

Okay now i am having a weird issue here, sometime back i learned how to encode and decode a json array properly here on stackoverflow but now i am having a weird issue on my godaddy server that i cannot comprehend, maybe i may have made i typo or something somewhere in code but i honestly cannot tell what is wrong here. The code works okay on my localhost but not when i upload it too my godaddy server.
The code here is basically supposed to pass an id as a json to the php server which is then supposed to execute a query using the id as a parameter.
Here is the jquery code:
<script text="text/javascript">
$(document).ready(function() {
$('#download').click(function(e) {
// e.preventDefault();
var tid = $('#id').val().trim();
var data = {
ID:tid
};
$.ajax({
type: "POST",
url: "xxxxx-xxxxxxx.php",
data: {
data: JSON.stringify(data)
},
dataType: "json",
success: function(response) {
}
});
});
});
</script>
and this is the php code:
<?php
if (isset($_POST['data']))
{
$Data = $_POST["data"];
$arr = json_decode($Data);
$id = $arr->ID;
$sql = $pdo->prepare("update ********** set ******** = ******** + 1 where id=:id");
$sql->bindValue("id", $id, PDO::PARAM_INT);
$sql->execute();
unset($_POST['data']);
}
?>
Now i checked if the value was being sent to the server using my browser console and it was. I also checked if the $_POST['data'] on the server contained any data using var_dump and it did in fact have the data i wanted.
in the ajax set the content type to contentType: "application/json",
so:
$.ajax({
type: "POST",
url: "xxxxx-xxxxxxx.php",
data: {
data: JSON.stringify(data)
},
contentType: "application/json",
success: function(response) {
}
});
and in the php use:
$json = file_get_contents('php://input');
$data = json_decode($json);

Categories

Resources