How to send JSON in php via jquery correctly - javascript

I'm sending JSON to backend server, but I'm confuse about how I can process it correctly,
i'm reading around that echo (json_decode($_POST)); is not going to work but
echo (json_decode(file_get_contents("php://input")));, but actually I tried to output the response on the client side alert(respon); but nothing show
0_12_e2_contentType_JSON.html
<html>
<head>
<script type="text/javascript" src="jquery-2.0.3.min.js"></script>
</head>
<body>
<script >
$(function(){
$.ajax({
url: "fragment/0_12_e2_contentType_JSON.php",
type: "POST",
contentType:"application/json; charset=utf-8",
data: {
"name":"hans" ,
"id":10
},
success: function (respon)
{
alert(respon);
},
error:function(e){
alert('Ajaxnya error');
}
});
});
</script>
</body>
</html>
0_12_e2_contentType_JSON.php
<?php
echo (json_decode(file_get_contents("php://input")));
?>
My question is that is it already correct? but why does it output nothing? Thanks

If you want to send contentType:'application/json' you need to stringify the data yourself
$.ajax({
url: "fragment/0_12_e2_contentType_JSON.php",
type: "POST",
contentType:"application/json; charset=utf-8",
data: JSON.stringify({ "name":"hans" ,"id":10}),
success: function (respon)
{
alert(respon);
},
error:function(e){
alert('Ajaxnya error');
}
});
Most people would not override the default contentType and receive in php using $_POST

not clear to me Your question anyway it seems like in the end You want to answer from the server what You sended via ajax... if it is the case I would recommend to use json_encode ... not json_decode
<?php
header('Content-Type: application/json');
echo (json_encode($_POST));
?>

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

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

Get result of php with jQuery

I have a button to call a php file with jQuery in my html file,
<script>
$('#mysubmit').bind('click', function(e){e.preventDefault();
var jqueryXHR = $.ajax({
'type': 'POST',
'url': 'http://localhost/lt/resources/lists/update.php',
'dataType': 'json'
});
</script>
<input type="submit" id="mysubmit" value="Submit" />
It works but I don't know how to get the result of the php file, i.e. the php file works, make an API POST and get the result as success or error, but I don't know how to get through jQuery if the php file response is success or error.
Please help me I am a noob in Ajax and Jquery.
your php file must respond with an echo:
<?php echo "success"; ?>
in your request do something like this:
$.ajax({
'type': 'POST',
'url': 'http://localhost/lt/resources/lists/update.php',
'dataType': 'json'
}).done(function(response){ /*DO SOMETHING WITH response*/ });
use jquery ajax success property.
<script>
$('#mysubmit').bind('click', function(e){e.preventDefault();
var jqueryXHR = $.ajax({
'type': 'POST',
'url': 'http://localhost/lt/resources/lists/update.php',
'dataType': 'json',
'success' : function(returnData){
alert(returnData); // or
console.log(returnData);
}
});
</script>
<input type="submit" id="mysubmit" value="Submit" />
what every you print at PHP side it will return in "success" function
Try adding a success \ error handler to see the response:
var jqueryXHR = $.ajax({
type: 'POST',
url: 'http://localhost/lt/resources/lists/update.php',
dataType: 'json',
success: function(data) {
console.log(data);
}
});
You should however follow #skobaljic's suggestion, and use a recognized response format such as JSON or XML - to make it easier to parse and more professional.
Using PHP it would look something like this:
<?php
$result = ..... whatever you like to return here ...
header('Content-Type: application/json');
echo json_encode($result);
?>

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