Error in a javascript ajax post - javascript

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

Related

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>

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

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 />";
?>

Live Search Using Ajax and PHP mysql

I created a Live Search using AJAX,PHP and mysql.here when I click on search result ,redirecting me to a particular page it works perfectly. Now I need a small change.
All I need is:
When I click on the search result, that particular result should be display in the input field.
Here is my AJAX code:
<script type="text/javascript">
END OF AJAX CODE
PHP CODE
<?php
ob_start();
session_start();
include("Base.php");
$dbase=new Base();
#$userID=$_SESSION['userID'];
$createdDate=date("Y-m-d");
$createdTime=date("h:i:s A");
$partialStates=mysql_escape_string($_REQUEST['q']);
$qryy="SELECT * from `gon_pro` WHERE `pro_name` LIKE
'%$partialStates%' ";
$pser=$dbase->execute($qryy);
$ser_nums=mysqli_num_rows($pser);
while($co[]=mysqli_fetch_array($pser)){
}
?>
<?php
foreach ($co as $key => $namo) {
$cv=$namo['pro_name'];
$cv_id=$namo['id'];
$cv_p=$namo['price'];
?>
<a href="pro_det.php?prolod=<?php echo $cv_id; ?>"><p class="res
col-md-6"><?php echo $cv; ?></p></a>
<?php
}
?>
END OF PHP CODE
function getStates(str) {
if (str.length == 0) {
document.getElementById("row").innerHTML = "";
document.getElementById("results").innerHTML =""
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("results").innerHTML =
xmlhttp.responseText;
}
};
xmlhttp.open("GET", "support/getStates.php?q=" + str, true);
xmlhttp.send();
}
}
</script>

Categories