I'm trying to post an array in javascript to php session variable using JSon. I searched a lot, there are 3 ways to post; HTML form Posting Request, AJAX and cookies. I want to post by posting request, in my script I convert my array to a JSon object no problem. Then I tried to send it to php page like this;
$('#firstConfirmButton').click(function(){
var json_text = JSON.stringify(ordersArray, null);
alert(json_text.toString());
request= new XMLHttpRequestObject();
request.open("POST", "test.php", true);
request.setRequestHeader("Content-type", "application/json");
request.send(json_text);
});
In test.php I tried to get array by using file_get_contents('php://input') but it did not work. When i try to echo son_text, it shows "firstConfirmButton=" instead of array content. What should I do?
<?php
require("includes/db.php");
require("includes/functions.php");
session_start();
if (isset($_POST['firstConfirmButton'])) {
$json_text = \file_get_contents('php://input');
echo $json_text;
}
?>
As you are using jQuery, use ajax functions of jQuery for better compatibility on browsers:
$('#firstConfirmButton').click(function(){
$.post("test.php", { data: ordersArray }, function(response){
// success callback
// response variable can be used for response from PHP, if any
});
});
In your PHP Code:
print_r($_POST['data']);
Please note that ordersArray
should be valid JSON. You can then use variables in PHP as per your need.
I appreciate Apul's answer but you have missed somethings that are causing the problem, do this:
$('#firstConfirmButton').click(function(){
var json_text = JSON.stringify(ordersArray, null);
alert(json_text.toString());
var request;
var XMLHttpFactories = [
function () {return new XMLHttpRequest()},
function () {return new ActiveXObject("Msxml2.XMLHTTP")},
function () {return new ActiveXObject("Msxml3.XMLHTTP")},
function () {return new ActiveXObject("Microsoft.XMLHTTP")}
];
function createXMLHTTPObject() {
var xmlhttp = false;
for (var i=0;i<XMLHttpFactories.length;i++) {
try {
xmlhttp = XMLHttpFactories[i]();
}
catch (e) {
continue;
}
break;
}
return xmlhttp;
}
function sendRequest(url,callback,postData) {
var req = createXMLHTTPObject();
if (!req) return;
var method = (postData) ? "POST" : "GET";
req.open(method,url,true);
req.setRequestHeader('User-Agent','XMLHTTP/1.0');
if (postData)
req.setRequestHeader('Content-type','text/json');
req.onreadystatechange = function () {
if (req.readyState != 4) return;
if (req.status != 200 && req.status != 304) {
alert('HTTP error ' + req.status);
return;
}
callback(req);
}
if (req.readyState == 4) return;
req.send(postData);
}
});
And finally call the sendRequest
function like this:
sendRequest('file.txt',handleRequest,ordersArray);
function handleRequest(req) {
var writeroot = [some element];
writeroot.innerHTML = req.responseText;
}
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","demo_post2.asp",true);
xmlhttp.setRequestHeader("Content-type","text/json");
xmlhttp.send(ordersArray);
$json_text = file_get_contents('php://input');
echo json_decode($json_text); //I have changed the send data from `json_text` to the direct non-Stringified json object, the `ordersArray`.
Difference between the two is of scalability.
Note: Difference between my and Apul's answer is of jQuery, I didn't used it, he did.
Apul is right about using an AJAX library. On the PHP side, I 'receive' the data using
$value = urldecode(file_get_contents('php://input'));
Actually I am still trying to solve this problem and I think I have some progress. Maybe somebody else will have same problem, I hope it will help him. Firstly I changed my javascript code to that, especially adding "async:false" saved my life because without this update, Safari and Firefoc can not post any Json variable to php(Chrome is ok). It took my 2 days to learn this.
$('#firstConfirmButton').click(function(){
var my_json_val = JSON.stringify(ordersArray, null);
alert(my_json_val.toString());
$.ajax({
type: "POST",
url: "gazanfer.php",
data: my_json_val,
cache: false,
contentType: false,
async: false,
processData: false,
success: function(data){
//alert("---"+data);
alert("Settings has been updated successfully.");
window.location.reload(true);
}
});
});
Now posting is ok but still I can not read the data on php side. I don't know why, here is my php code. Is there any idea?
<?php
require("includes/db.php");
require("includes/functions.php");
$my_json_encoded = $_POST['data'];
$my_json_val = json_decode($my_json_encoded);
echo $my_json_val;
?>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.