PHP not receiving JSON from Ajax post - javascript

I am trying to send some JSON to a PHP processing code via Ajax. Here is my JavaScript:
var j = {"a":"b"};
var xmlhttp;
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
};
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
console.log(xmlhttp.responseText)
};
};
xmlhttp.open("POST", "server.php", true);
xmlhttp.setRequestHeader("Content-Type", "application/json; charset=utf-8");
xmlhttp.send({
"json": j
});
And the PHP:
$json = $_POST["json"];
echo $json;
But this echoes null. What have I done wrong? This seems like it should work. Thanks!
Please no jQuery. And if you vote down, please tell me why so I can improve.

Your j variable is a object. You need to encode this into a json string before you post it.
Okay I have re-written my answer from scratch.
Update your server.php like this:
<?php
// Request Handler
if (count($_POST))
{
$json = isset($_POST['json']) ? $_POST['json'] : '';
if (!empty($json))
{
$jsonObj = json_decode($json);
print_r($jsonObj);
}
else
{
echo "No json string detected";
}
exit();
}
?>
Change your ajax request like this:
<script type="text/javascript">
var j = {"a":"b"};
var xmlHttp = new XMLHttpRequest();
var parameters = "json="+ encodeURIComponent(JSON.stringify(j));
xmlHttp.open("POST", "server.php", true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", parameters.length);
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
console.log(xmlHttp.responseText);
}
}
xmlHttp.send(parameters)
</script>
Here's a demo of it working:
So, in the PHP script, I am printing the $jsonObj and it's contents. If you want to use it in your script; you'd do this:
e.g.
<?php
if ($jsonObj->a == 'b') {
// do something ?
}
?>
If you want an associative array to work with (instead of an object), you can do this:
Change: $jsonObj = json_decode($json); To: $jsonObj = json_decode($json, true);
Now you can do this:
<?php
if ($jsonObj['a'] == 'b') {
// do something ?
}
?>

Javascipt :
encode en JSON with JSON.stringify(j);
if j contain & in string and not a separator de data :
j.split("&").join("%26");
in php
$json = $_REQUEST['json'];
$json = str_replace("%26","&",$jsonData);
$json = html_entity_decode($json,ENT_NOQUOTES,'UTF-8');
$data = json_decode($json,true);
the value of json as array of data.

To submit JSON properly, it'd be:
xmlhttp.send(JSON.stringify({"json": j});
Then for the PHP:
$json = json_decode(file_get_contents('php://input'));
The problem is that when sending JSON (if it's a proper JSON request), PHP won't automatically parse it.

Related

Can we send ajax from a javascript file?

since I wrote this code and it turned out that it is not entering the if statement ,My target was to bring the array from php(db) and put it in array in js,what to do?Here is the code ,is the problem that it is located in an extension js file ?Moreover php file getusercatpref.php is returning ["violen","ios","programming","nodjs"].
var arr = new Array();
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
arr = myArr;
}
};
xmlhttp.open("GET", "getusercatpref.php", true);
xmlhttp.send();
PHP Code
<?php
$name="root";
$pas="";
$dbname="jobpursuit";
$con=mysqli_connect("localhost", $name, $pas,$dbname);
$arrayCategories = array();
$sql="Select * FROM preferences where username='12' ";
$result=mysqli_query($con,$sql);
$index=0;
while($row = mysqli_fetch_assoc($result)){
$arrayCategories[$index] = $row['categoryname'];
$index=$index+1;
}
echo json_encode($arrayCategories);
?>

Repeat PHP function every 2 seconds

So I have a code, where a number is retrieved from a text file and is displayed through HTML.
The thing is that it only retrieves the number when I refresh the page. If I change the number on other page, it doesn't change on the other page.
I've seen similar questions before, most of them said to use AJAX, but I don't understand much about AJAX and I only need it for this bit of code, it's not like I'm going to constantly use it. I would like to know if there is any other besides AJAX and if there is only AJAX, please present examples of code.
PHP code:
<?php
$file = "num.txt"; //Path to your *.txt file
$contents = file($file);
$num = implode($contents);
?>
JavaScript code. Basically it gets the PHP value and outputs to the html.
document.getElementById("num").innerHTML = '<?php echo $num; ?>';
Keep in mind, I don't want to refresh the page. Just the variable.
EDIT: PHP code - Getting an error - Notice: Undefined index: keynum in C:\xampp\htdocs\num.php on line 3
Here is the code of the PHP
<?php
$keynum = $_POST['keynum'];
$post = "INSERT INTO post (keynum) VALUES ($keynum)";
$fileLocation = getenv("DOCUMENT_ROOT") . "/num.txt";
$file = fopen($fileLocation,"w");
$content = $keynum;
fwrite($file,$content);
fclose($file);
echo 'Response';
die();
?>
You can achieve what you want using XMLHttpRequest, like this:
function updateData() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById('num').innerHTML = this.responseText;
}
};
xhttp.open('GET', '/num.php', true);
xhttp.send();
}
setInterval(updateData, 2000);
If you want to refresh the variable without refreshing the page, then you need to use an asynchronous request. It doesn't need to be AJAX, you can use the native XMLHttpRequest() function.
If you want more info: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests
or with jquery:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
setInterval(function(){
$.ajax({url:"num.php", success:function(result){
$("#num").html(result);
}});
}, 3000);
</script>
<textarea id="num"></textarea>
get_nbr.php
<?php
$file = "num.txt"; //Path to your *.txt file
$contents = file($file);
$num = implode($contents);
echo $num;
?>
index.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!---trigger get_nbr() on page load on an infinite loop every two seconds -->
<body onload="setInterval(get_nbr, 2000)">
<script>
function get_nbr() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("num").innerHTML = this.responseText;
}
};
xhttp.open("GET", "get_nbr.php", true);
xhttp.send();
}
</script>
<p id="num"></p>
like this.
let url = ""; //whatever url your requesting.
setInterval(function(){
var x = new XMLHttpRequest();
x.open("GET" , url , true);
x.onreadystatechange = function(){
if(x.readyState == 4 && x.status == 200)
{
document.getElementById("num").innerHTML = x.responseText;
}
}
x.send();
} , 2000);
-- UPDATE , added post --
setInterval(function(){
var x = new XMLHttpRequest();
x.open("POST" , url , true);
x.setRequestHeader("Content-Type" , "application/x-www-form-urlencoded");
x.onreadystatechange = function(){
if(x.readyState == 4 && x.status == 200)
{
document.getElementById("num").innerHTML = x.responseText;
}
}
x.send("postVar1=123");
} , 2000);

send and receive variable using javascript and php

I am trying to send variable to php using javascript and trying to receive back and alert that variable. I don't know what I am doing wrong.
Here is my javascript code:
function getMessageType(data)
{
var xhr = new XMLHttpRequest();
var url = "test.php";
xhr.open('POST', url, true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
alert(xhr.responseText);
}
};
xhr.send(data);
}
Here is my Php code:
<?php
$obj = $_POST['data'];
return $obj;
?>
this is what I tried:
getMessageType('some data'); //function call
function getMessageType(data)
{
var xhr = new XMLHttpRequest();
var url = "test.php";
xhr.open('POST', url, true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
xhr.send(data);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
alert(xhr.responseText);
}
};
}
Php code :
<?php
$obj = $_POST['data'];
echo $obj;
Still I am getting blank alert.
You should echo this variable from php side.
<?php
$obj = $_POST['data'];
echo $obj;
Also in this case you should use text/plain content-type.
Instead of returning your object.
echo $obj;
Also you are sending your data request AFTER you are alertingg your data, so you are alerting before you have anything to alert.
Do something like this.
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
xhr.send(data);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
alert(xhr.responseText);
}
};

Cant parse JSON with JavaScript and Ajax

Ive got an PHP which creates a .json file:
<?php
$data=array( "Name"=>"Someone", "Surname" => "Somebody");
$jsontext = "[";
foreach($data as $key => $value) {
$jsontext .= "{objectValue: '".addslashes($key)."', textObject: '".addslashes($value)."'},";
}
$jsontext = substr_replace($jsontext, '', -1);
$jsontext .= "]";
echo $jsontext;
$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($jsontext));
fclose($fp);
?>
This is the results.json:
"[{objectValue: 'Name', textObject: 'Someone'},{objectValue: 'Surname', textObject: 'Somebody'}]"
The javascript:
var xmlHttp = createXmlHttpRequestObject();
var finalText;
window.onload = process;
function createXmlHttpRequestObject() {
var xmlHttp;
if (window.ActiveXObject) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
xmlHttp = false;
}
} else {
try {
xmlHttp = new XMLHttpRequest();
} catch (e) {
xmlHttp = false;
}
}
if (!xmlHttp) {
alert("Cant create XmlHTTP...");
} else {
return xmlHttp;
}
}
function process() {
if (xmlHttp.readyState == 0 || xmlHttp.readyState == 4) {
xmlHttp.open("GET", "http://localhost/results.json", true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
} else {
//setTimeout('process()', 1000);
alert("Error: Server is busy");
}
}
function handleServerResponse() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
finalText = xmlHttp.responseText;
}else{
//alert("Error: server is busy");
}
}
function convertJSON(){
parsedText = JSON.parse(finalText);
alert(parsedText); //This shows the parsed text, it gets here
document.getElementById('finalResult').innerHTML += parsedText.objectValue;
document.getElementById('finalResult').innerHTML += parsedText.Name;
}
Whenever I summon convertJSON from a button onclick I keep getting undefined, when printing the results into the "finalResult" div... what am I doing wrong?
You're building your JSON by string concatenation, then sending it into json_encode. Instead build your JSON as an array:
$jsonData = array();
foreach($data as $key => $value) {
$jsonData[] = array('objectValue' => $key, 'textObject' => $value);
}
$jsontext = json_encode($jsonData);
echo $jsontext;
fwrite($fp, $jsontext);
You need to use valid JSON, strings are always surrounded with double-quotes and object keys are also surrounded by double-quotes. So your JSON string that is served up by PHP should read as follows:
[{"objectValue":"Name","textObject":"Someone"},{"objectValue":"Surname","textObject":"Somebody"}]
There's a good online reference for JSON structure that you might want to give a read.

AJAX not passing variable to PHP for MySQL query

I am trying to get the below AJAX script to pass a dropdown ID to PHP to run a query on, however it doesnt appear that the variable is actually being passed. When I hardcode the PHP file the query runs correctly, but when I try to do it dynamically the query returns "undefined" or nothing at all.
AJAX code
function ajax_post(){
var request = new XMLHttpRequest();
var id = document.getElementById("editorginfo").value;
alert (id);
request.open("POST", "parse.php", true);
request.setRequestHeader("Content-Type", "x-www-form-urlencoded");
request.onreadystatechange = function () {
if(request.readyState == 4 && request.status == 200) {
var return_data = request.responseText;
alert (return_data);
document.getElementById("orgeditname").value = return_data;
document.getElementById("orgeditphone").value = return_data;
}
}
request.send("id="+id);
}
PHP Parse Code
<?php
include_once('../php_includes/db_connect.php');
$searchid = $_POST['id'];
//$searchid = 1;
$sql = 'SELECT * FROM orginfo WHERE id = $searchid';
$user_query = mysqli_query($db_connect, $sql) or die("Error: ".mysqli_error($db_connect));
while ($row = mysqli_fetch_array($user_query, MYSQLI_ASSOC)) {
$orgid = $row["id"];
$orgname = $row["orgname"];
$orgphone = $row["orgphone"];
echo $orgname, $orgphone;
}
?>
Not really sure where the information is getting lost. When I alert the id out it is capturing the right information, so I assume the issue is in my send portion, but I can't figure out what I'm doing wrong. Any help would be appreciated.
Thanks in advance.
Your request header is wrong. Change this line -
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
^^^^^^^^^^^^

Categories