send and receive variable using javascript and php - javascript

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

Related

I need to send a request through JS to a php file via API

Help me please. There are two php files Data.php and Status.php. When you enter data in the zip field, you need to send a request to the Data.php file, and if zip is available, send the data to Status.phpenter code here and parse the response in the field.Below I will give a js example and Data.php, Status.php
I will be grateful for the help)
function ajax(params) {
var xhr = new XMLHttpRequest();
var url = params.url || '';
var body = params.body || '';
var success = params.success;
var error = params.error;
xhr.open('POST', url, true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(body);
xhr.onload = function () {
if (xhr.readyState === 4 && xhr.status === 200 && typeof success === 'function') {
success(xhr.response);
} else if (xhr.readyState === 4 && xhr.status !== 200 && typeof error === 'function') {
error(xhr.response);
}
};
xhr.onerror = error || null;
}
//Data.php
<?php
header('Content-Type: application/x-www-form-urlencoded');
header('Access-Control-Allow-Origin: *');
if (isset($_POST['zip'])) {
$zip = filter_var($_POST['zip'], FILTER_VALIDATE_REGEXP, array('options'=>array('regexp'=>'/^[0-9]{5}/')));
if ($zip) {
$status = (int) $zip < 33333 ? array('zip' => $zip, 'state' => 'OH', 'city' => 'NEWTON FALLS') : array('zip' => $zip, 'state' => 'CA', 'city' => 'BEVERLY HILLS');
echo json_encode($status);
} else {
echo 'error';
}
} else {
echo 'error';
}
//Status.php
<?php
header('Content-Type: application/x-www-form-urlencoded');
header('Access-Control-Allow-Origin: *');
if (isset($_POST['zip'])) {
$zip = filter_var($_POST['zip'], FILTER_VALIDATE_REGEXP, array('options' => array('regexp' => '/^[0-9]{5}/')));
if ($zip) {
$status = (int) $zip < 33333 ? 'allowed' : 'blocked';
echo $status;
} else {
echo 'error';
}
} else {
echo 'error';
}
You need to send an AJAX call from the first php to second php.
Include following script inside first php file.
test1.php
<?php
// other content
<script>
(function() {
var httpRequest;
document.getElementById("ajaxButton").addEventListener('click', makeRequest);
function makeRequest() {
httpRequest = new XMLHttpRequest();
if (!httpRequest) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
httpRequest.onreadystatechange = alertContents;
httpRequest.open('GET', 'test2.php');
httpRequest.send();
}
function alertContents() {
if (httpRequest.readyState === XMLHttpRequest.DONE) {
if (httpRequest.status === 200) {
alert(httpRequest.responseText); // your response
} else {
alert('There was a problem with the request.');
}
}
}
})();
</script>
?>
Then return your content data from the next php file as follows.
test2.php
<?php
$x = "content data";
echo $x;
?>
For more details about AJAX, follow below link
https://developer.mozilla.org/en-US/docs/Web/Guide/AJAX/Getting_Started
javaScript Code
const data = { name: 'scott' }; // data for post
fetch('url', {
method: 'POST',
headers: {
'Content-Type': 'application/json', // type
},
body: JSON.stringify(data),
})
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch((error) => {
console.error(error);
});

Why does file_put_contents not work in my online php script?

I am trying to use a .php file to edit a .txt file on my http web server. I can call the .php file and get it to run (and echo something random back) just fine, but when I use file_put_contents it doesn't work. I have tried setting file permissions to 777, 0775, etc but nothing happens. (although from what I have gathered, it seems that permissions are for local systems only). I know that there are some similar questions already here, but I cannot understand the answers to any of them.
testingPHP.js (trimmed):
function submitData() {
var data = prompt('Enter data');
sendToServer(data, 'test.txt');
}
function sendToServer(data, file) {//file is file to write into, not the php file
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
}
}
xmlhttp.open("GET", "editTXT.php?txtFile=file&data=data");
xmlhttp.send();
setTimeout(update, 500);
}
function update() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var response = xhttp.responseText;
console.log(response);
}
};
xhttp.open("GET", "readTxt.php?file=test.txt", true);
xhttp.send();
}
setInterval(update, 1000);
editTxt.php:
<?php
$txtFile = $_GET["txtFile"];
$data = $_GET["data"];
file_put_contents($txtFile, $data);
?>
readTxt.php:
<?php
$file = $_GET['file'];
$data = file_get_contents($file);
echo $data;
?>
I hope the following might help - I think the main problem is in the javascript funnily enough but I'll post here the changes I made to all files anyway. Incidentally - constant polling like this using Ajax could instead be done in a cleaner way using an EventSource connection and Server Sent Events.
If the textfile is to be overwritten completely when the script is invoked then this works fine ( in test anyway ) but if the data is intended to add to existing content you'd need to add FILE_APPEND as the final argument to file_put_contents
editTxt.php
<?php
if( $_SERVER['REQUEST_METHOD']=='GET' && isset( $_GET['txtFile'], $_GET['data'] ) ){
$file=__DIR__ . '/' . $_GET['txtFile'];
$data=$_GET['data'];
$bytes=file_put_contents( $file, $data );
if( !$bytes )exit('error');
}
?>
readTxt.php
<?php
if( $_SERVER['REQUEST_METHOD']=='GET' && isset( $_GET['file'] ) ){
$file=__DIR__ . '/' . $_GET['file'];
exit( file_get_contents( $file ) );
}
?>
And the HTML & Javascript
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title></title>
</head>
<body>
<script>
function submitData() {
var data = prompt('Enter data');
if( data ){/* only submit if there is data */
sendToServer(data, 'test.txt');
setInterval(update, 1000);
return true;
}
}
function sendToServer(data, file) {//file is file to write into, not the php file
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
}
}
/* the filename and the data need to be escaped in the string */
xmlhttp.open("GET", "editTXT.php?txtFile="+file+"&data="+data);
xmlhttp.send();
setTimeout(update, 500);
}
function update() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var response = xhttp.responseText;
console.log(response);
}
};
xhttp.open("GET", "readTxt.php?file=test.txt", true);
xhttp.send();
}
/* call the function that prompts for data input */
submitData();
</script>
</body>
</html>

Use Ajax to update data on page which is read from text file with PHP

I want to update data on my webpage using Ajax. This data is read using PHP script
and I want this function to carry out EVERY 5 seconds. For some reason, this is not happening at all.
My JavaScript:
<script>
function refresh(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementClassName("scroll").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "gm.php?q=" + "<?php echo $mf[0]."-".$mf[1].".txt" ?>", true);
// The PHP variables refer to a specific file
xmlhttp.send();
}
setInterval(refresh,5000);
</script>
My gm.php file:
<?php
$q = $_REQUEST["q"];
$mr=fopen($q, "a+");
$line = fgets($mr);
while (!feof($mr)) {
$line = $line.fgets($mr);
} # while ends
fclose($mr);
echo $line. "<br />";
?>
I figured out that my element selector was wrong as I was using get ElementClassName instead of getElementsByClassName. Also, I hadn't given the element index in the class, due to which the element could not be selected.
Another reason was my usage of quotes within the JavaScript string which included the PHP script.
My JavaScript:
<script>
function refresh(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementsByClassName("scroll")[1].innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "gm.php?q=" + '<?php echo $mf[0]."-".$mf[1].".txt" ?>', true);
// The PHP variables refer to a specific file
xmlhttp.send();
}
setInterval(refresh,5000);
</script>
My gm.php file:
<?php
$q = $_REQUEST["q"];
$mr=fopen($q, "a+");
$line = fgets($mr);
while (!feof($mr)) {
$line = $line.fgets($mr);
} # while ends
fclose($mr);
echo $line. "<br />";
?>

Error in a javascript ajax post

I have a problem with an AJAX request (POST method) with pure Javascript.
I have the following function:
function ajaxPost(page, fields) {
XHR = new XMLHttpRequest();
XHR.open("POST", page, false);
XHR.setRequestHeader("content-type", "application/x-www-form-urlencoded");
if(XHR.readyState == 4 && XHR.status == 200) {
return XHR.responseText;
}
XHR.send(fields);
}
and the page where I need to do an ajax request I make the following:
<script type="text/javascript">
var ajax = ajaxPost("ajax/ajax.php", "var1=bla&var2=blabla");
alert(ajax);
</script>
While in ajax/ajax.php:
<?php
if(isset($_POST['var1') && isset($_POST['var2'])) {
echo var1 . " " . var2;
}
?>
But the alert displays the value "undefined", where is that wrong?
Use this as your ajax/ajax.php :
<?php
if($_GET['var1'] && $_GET['var2']) {
echo var1 . " " . var2;
}
?>

PHP not receiving JSON from Ajax post

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.

Categories