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

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'];

Related

jQuery Ajax PHP POST method with response array[] instad sent data. How to get send values in response?

I am creating simple application which will insert log data into database table.
Going with jQuery Ajax POST method and JSON format for data.
My index.php has HTML and this code:
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery.ajax({
type: "POST",
url: "http://www.example.com/ajax_model.php",
data: {
"log_session": "27738d7552b75ae395ae1138adf4fa60",
"log_ip": "1.2.3.4",
"log_vrijeme": "2018-11-23 01:22:47",
"log_model": "12345"
},
dataType: "json",
contentType: 'application/json; charset=utf-8',
success: function(response) {
console.log(response);
alert(response);
},
error: function(error) {
console.log(error);
}
});
});
</script>
My ajax_model.php - which gives me response Array[] instad the data which is sent:
<?php
if(isset($_POST)){
header('Content-Type: application/json');
echo json_encode($_POST);
exit;
}
?>
I am getting result in my console.log() and alert() - Array[].
How can I output my sent response to check if the data was correctly sent over Ajax?
Am I missing some brackets like [] or {}?
Or do I need to add something to my ajax_model.php file?
Thank you for suggestion and provided information.
You aren't sending JSON so get rid of:
contentType: 'application/json; charset=utf-8',
That will cause $_POST to be empty as the default contentType is:
application/x-www-form-urlencoded; charset=UTF-8

Jquery Ajax returns 400 BAD request

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.

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

Retrieving objects from JSON using PHP

I need to send some data stored in IndexedDB to server for some back-end manipulation. The needed data is fetched to a variable payLoad in javascript using JSON.stringify().
payLoad = "[{"synch":0,"id":-1,"name":"Tester","email":"test#example.com","created":"2014-08-20T07:56:44.201Z"}]";
$.ajax({
type: "POST",
url: "process.php",
data: payLoad, // NOTE CHANGE HERE
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg);
},
error: function(msg) {
alert('error');
}
});
Can I parse this JSON data to a PHP class?
This way, you're just sending JSON raw in the body. Try this:
$data = json_decode(file_get_contents('php://input'));
If, on the other hand, you send data with this:
data: { data: payLoad },
Then you can simply do
$data = json_decode($_POST['data']);

How to access return data of jQuery.ajax() sent to php script

I am using the following jquery ajax call:
$(document).ready(function () {
submitAct();
function submitAct(){
var alldata = [];
alldata.push( {
"pid": 'd2a7d886-6821-3eaa-079f-fbe278c6a16a',
"title": 'Fun with Gophers',
});
$.ajax({
dataType: "jsonp",
type: 'POST',
url: '//[server path]/act',
data: "data=" + JSON.stringify(alldata),
});
}
});
On the server, the result of $_POST[data] is showing as:
[{"pid":"d2a7d886-6821-3eaa-079f-fbe278c6a16a","title":"Fun with Gophers"}]
I am having trouble accessing the keys and related values of 'pid' and 'title'. Would someone please provide some insight? I've tried things like below but haven't had any success:
$_POST['title']
$data = json_decode( $_POST['data']);
$data->title
Thanks!
Several suggestions:
First you are enclosing the data object in an array, needlessly. To access it now:
$data = json_decode( $_POST['data']);
$data=$data[0];/* access object in array*/
$data->title;
The default content type for $.ajax is application/x-www-form-urlencoded; charset=UTF-8...exactly the same as sending a regular form. Think of each key in your data object as you would name of a form control.
There is no need to JSON.stringify to send. jQuery will serialize objects and arrays for you
You can simply send it like this:
var alldata = {
"pid": 'd2a7d886-6821-3eaa-079f-fbe278c6a16a',
"title": 'Fun with Gophers',
};
$.ajax({
dataType: "jsonp",
type: 'POST',
url: '//[server path]/act',
data: alldata
});
Then in php:
$title=$_POST['title'];
$a = json_decode($_POST['data']);
print_r($a[0]->pid);
Change the data part of the ajax request to the following:
$.ajax({
dataType: "jsonp",
type: 'POST',
url: '//[server path]/act',
data: {"data": JSON.stringify(alldata)},
});
Now you can access the sent content via $_POST["data"] in the appropriate php file.
Example:
$json = json_decode($_POST["data"]);
var_dump($json[0]->{"title"}); // [0] because of the array

Categories

Resources