Submitting JSON data via JQuery ajax.post to PHP
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 $_POST
you would make it:
data: {"data":JSON.stringify({'Absence' : JSON.stringify(this)})},
And then in PHP do:
$json = json_decode($_POST['data']);
How do I use jQuery.post to send JSON data to a php script?
Using jQuery you can send data to your end point using the POST protocol. Example below
$.ajax({
url : 'taskmanager.php',
type : 'POST',
data : JSON.stringify(dataStore),
success : function(res) {
// Successfully sent data.
console.log(res);
},
error: function(err) {
// Unable to send data.
console.log(err);
})
});
You may also use the $.post method, its just a preference. $.ajax provides with some extra flexibility, in case you maybe want to update your protocol to GET instead of post or numerous other instances...
More info on this here: http://forum.jquery.com/topic/what-should-i-use-post-vs-ajax
Sending JSON to PHP using ajax
Lose the contentType: "application/json; charset=utf-8",
. You're not sending JSON to the server, you're sending a normal POST query (that happens to contain a JSON string).
That should make what you have work.
Thing is, you don't need to use JSON.stringify
or json_decode
here at all. Just do:
data: {myData:postData},
Then in PHP:
$obj = $_POST['myData'];
how to pass JSON data to php using ajax post
1) How can I examine the posted data? I.e. "Received Data: "+WHAT in syslog to see its structure.
As I understand you are debugging the code, so syslog can be not the best idea.
I would simply use the browser network console to see the content of requests and a simple php file like this to see the content of $_POST
:
<?php
echo json_encode($_POST);
In more complex cases - use the actual debugger.
2) JSON parse error? Most examples I see use this stringify function. then they use json_decode to get the values. Why the parse error?
You are trying to use the json
key in your $_POST
, but you didn't instruct jQuery to add it, so you are receiving not what you expected.
There are few issues with your $.ajax
call, here is the commented version:
$.ajax({
type: 'POST',
url: './json.php',
dataType: 'json', // Note: dataType is only important for the response
// jQuery now expects that your server code
// will return json
// here you need to add the 'json' key
data: {'json': JSON.stringify(data)},
// the success method has different order of parameters
//success: function(xhr, status, errorMessage) {
success: function(data, status, xhr) {
alert("response was "+data);
},
error: function(xhr, status, errorMessage) {
$("#debug").append("RESPONSE: "+xhr.responseText+", error: "+errorMessage);
}
});
Now on the server you will have $_POST['json']
with serialized string and you can json_decode
it.
Alternatively you can send the JSON data without serialization:
var data = {'test': 'abc'};
$.ajax({
type: 'POST',
url: './json.php',
// No 'JSON.stringify()', just send your data
data: data,
...
});
And on the server you will have $_POST['test']
with abc
value (so you have your json already converted into array).
Posting JSON with jquery ajax to PHP
Your code works if you remove dataType: 'json'
, just tested it.
$('#save').click(function() {
var tmp = JSON.stringify($('.dd').nestable('serialize'));
// tmp value: [{"id":21,"children":[{"id":196},{"id":195},{"id":49},{"id":194}]},{"id":29,"children":[{"id":184},{"id":152}]},...]
$.ajax({
type: 'POST',
url: 'save_categories.php',
data: {'categories': tmp},
success: function(msg) {
alert(msg);
}
});
});
Saving data into a text file sent as JSON with Ajax
You must know that in PHP json_decode
generates an Array that you can't write into an text file.
So only remove the json_decode
command.
Uable to send POST data to JSON file via JQuery/AJAX, Why?
Client side scripting languages are used to send and retrieve data which resides on server side. We can't use them to write/edit data on server side.
For doing so, we have to use server side scripting languages like PHP or ASP or any other which you prefer.
The video you referred was an API written in Core PHP used for retrieving / writing data from / to a json file which resides on server.
In my below code i have used PHP to write submitted data to a json file via jQuery/AJAX.
Check this out..
api/process.php
if (isset($_POST['params'])) {
$params = $_POST['params'];
$oldData = file_get_contents('orders.json');
$tmp = json_decode($oldData);
array_push($tmp, $params);
$newData = json_encode($tmp);
if (is_writable('orders.json')) {
file_put_contents('orders.json', $newData);
echo $newData;
} else {
echo "file is not writable, check permissions";
}
}
index.html
<h1>Jquery Ajax Tutorial</h1>
<h3>Coffie Orders</h3>
<ul id="orders"></ul>
<h4>Add a Coffie Order</h4>
<p> Name: <input type="text" id="name"> </p>
<p> Drink: <input type="text" id="drink"> </p>
<button id="add-order">Add!</button>
<script src='js/jquery.min.js'></script>
<script src='js/main.js'></script>
js/main.js
let $orders = $('#orders');
let $name = $('#name');
let $drink = $('#drink');
function addOrder(order) {
$orders.append('<li>Name: '+ order.name +', Drink: '+ order.drink +'</li>');
}
$('#add-order').click(function(){
let order = {
name: $name.val(),
drink: $drink.val()
};
$.ajax({
type: 'POST',
url: '/api/process.php',
data: { params: order },
success: function(resp) {
addOrder(resp);
},
error: function(){
alert('Error Adding Orders');
}
});
});
$.ajax({
type: 'GET',
url: '/api/orders.json',
success: function (orders) {
$.each(orders, function(i, orders) {
addOrder(orders);
});
},
error: function(){
alert('Error Loading Page');
}
});
api/orders.json
[
{
"id": 1,
"name": "James",
"drink": "Coffiee"
},
{
"id": 2,
"name": "John",
"drink": "Latte"
}
]
Note: Here, i am not writing id
to json file for new orders.
Hope, this piece of code works fine for you. :) :)
Send form data with jquery ajax json
here is a simple one
here is my test.php for testing only
<?php
// this is just a test
//send back to the ajax request the request
echo json_encode($_POST);
here is my index.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form id="form" action="" method="post">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="email"><br>
FavColor: <input type="text" name="favc"><br>
<input id="submit" type="button" name="submit" value="submit">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
// click on button submit
$("#submit").on('click', function(){
// send ajax
$.ajax({
url: 'test.php', // url where to submit the request
type : "POST", // type of action POST || GET
dataType : 'json', // data type
data : $("#form").serialize(), // post data || get data
success : function(result) {
// you can see the result from the console
// tab of the developer tools
console.log(result);
},
error: function(xhr, resp, text) {
console.log(xhr, resp, text);
}
})
});
});
</script>
</body>
</html>
Both file are place in the same directory
Related Topics
PHP Inserting Multiple Checkbox and Textbox Arrays into MySQL Database
Sanitizing User's Data in Get by PHP
How to Password Protect Folder/Page Using PHP Without a Db or Username
PHP Built in Server and .Htaccess Mod Rewrites
Is Is Possible to Set a Default Pdo Fetch Mode
Ajax Post Request in Laravel 5 Return Error 500 (Internal Server Error)
Access a File Which Is Located Before/Outside the Server Root Directory
Str_Replace() on Multibyte Strings Dangerous
Set Precision for a Float Number in PHP
How to Connect to MySQL Database in PHP Using MySQLi Extension
Laravel: Using Try...Catch with Db::Transaction()
Detecting Image Type from Base64 String in PHP
How to Make PHP Generate Chunked Response
PHP - Indirect Modification of Overloaded Property
Php: How to Disable Dangerous Functions
Get the Keys for Duplicate Values in an Array
Can PHP and ASP.NET Run Together Within the Same Web Site in Iis 7.5