I need to use the xhr.send(VALUE) to send the data in AJAX. How do I get this data in a PHP file?
JS:
window.onload = function() {
var value = 'hello';
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
} else {
alert("no");
}
}
xhr.open('POST', 'json.php', true);
xhr.send(value);
}
You are just sending a string to the PHP file. You are not sending it as a query string or with a content type, so PHP doesn't populate the $POST array.
You can try to read the raw post data:
$post = file_get_contents('php://input');
echo $post; // hello
Or, if you want PHP to populate $_POST, you need to do some extra steps in your JavaScript.
window.onload = function() {
var value = 'hello';
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
} else {
alert("no");
}
}
xhr.open('POST', 'json.php', true);
// Tell the server you are sending form data
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
// Send it as a query string
xhr.send('value='+value);
}
Then in your PHP, you can access $_POST['value'].
echo $_POST['value']; // hello
If you want to see the $_POST variables on the PHP page you can use this code to display them all so you can visually see their keys and values
echo "<pre>";
print_r($_POST);
echo "</pre>";
From there you will know how to use the data in any file. You can do the same thing with $_GET
Try this, replace your xhr.send with
JS
xhr.send('value='+value);
PHP
echo($_POST['value']);
Related
I have a browserside javascript file that's supposed to be asking the serverside php file for a string with an ajax request. The php file seems to have the correct string, but for some reason the ajax request is returning the string 'false'.
This is the php file, named test.php:
<?php
$dir = "site/uploads";
$a = scandir($dir);
$b = json_encode($a);
echo $b;
?>
This is the js file:
function load(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.responseType = "text";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
console.log('test' + xmlhttp.responseText);
console.log('test' + JSON.parse(xmlhttp.responseText));
}
};
xmlhttp.open("GET", "test.php", 'false');
xmlhttp.send();
var xmlhttp2 = new XMLHttpRequest();
xmlhttp2.responseType = "text";
xmlhttp2.onreadystatechange = function() {
if (xmlhttp2.readyState == 4 && xmlhttp2.status == 200) {
console.log('test2' + xmlhttp2.responseText);
console.log('test2' + JSON.parse(xmlhttp2.responseText));
}
};
xmlhttp2.open("GET", "test2.php", 'false');
xmlhttp2.send();
}
when i open the website in my browser and run load(), the console reads:
testfalse
testfalse
test2false
test2false
and has no errors. What am I doing wrong here? Thanks!
scandir() in the php-file is probably returning false, because of an error.
https://www.php.net/manual/de/function.scandir.php (Check the return values)
There are multiple possiblities for this to happen:
The folder doesn't exist
The path is incorrect (Try using absolute paths)
The folder isn't accessible, because of missing permissions
In my JS code, I take in 3 inputs on a html page and save them to local storage. I then want to send these variables to php in order to save them to my database. No matter how hard I try no tutorial using ajax, jquery etc allows me to successfully post and echo variables from javascript in my php code. I see no reason why my code below doesn't echo the variables, but it doesn't.
Full code: https://codeshare.io/ayvK9e
Exact PHP elements (just trying to send normal variables right now as it still won't work"
PHP:
foreach($_POST as $post_var){
echo($post_var);
}
JS:
const xhr = new XMLHttpRequest();
xhr.onload = function(){
const serverResponse = document.getElementById("serverResponse");
serverResponse.innerHTML = this.responseText
};
xhr.open("POST", "eDBase.php");
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send("name=dominic&message=bumbaclaat");
If $post not work try using input php
$data = json_decode(file_get_contents('php://input'), true);
When calling my function with the inputs onclick=showFunction; I was passing nothing to the function. In order for my values to be echoed in php I had to pass a parameter to the function onclick=function('text or variable'); IDK how I missed that.
Try using the FormData()
let form = new FormData();
form.append('name', 'dominic');
form.append('message', 'bumbaclaat');
const xhr = new XMLHttpRequest();
xhr.open("POST", "eDBase.php");
xhr.onreadystatechange = function(){
if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
const serverResponse = document.getElementById("serverResponse");
serverResponse.innerHTML = this.responseText;
}
else console.log('error')
};
xhr.send(form);
Comment out the setRequestHeader to test it.
And at PHP
if(isset($_POST['name'])){
echo $_POST['name'];
echo $_POST['message'];
}
else{
echo 'There was a problem';
}
I am trying to send data to php file then echo the word "Hello!" when i call a function in javascript, however, no message appear, i guess there is en error in the calling, can you guide me please?
Here is my code:
Javascript:
function asyncpost_deviceprint() {
var xmlhttp = false;
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
xmlhttp = new XMLHttpRequest();
}
else if (!xmlhttp) return false;
xmlhttp.open("POST", "http://localhost/Assignment/insert.php", true);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send("userAgent" + userAgent()); /* fire and forget */
return true;
}
PHP:
<?php
echo "Hello!";
?>
echo "Hello!";
won't display any message because in Ajax request this function sends a respond to Javascript.
If you want to display sth on the screen with PHP instead of Ajax you should use:
window.location.href="path to your php site"
it will redirect you to php file and display Hello!
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4) {
if (xmlhttp.status === 200) {
document.body.innerHTML += xmlhttp.responseText;
}
}
};
Add this before xmlhttp.send
It will literally just stick the php echo text after the last thing in the document.
I have this simple js code:
ajax.open("POST", "test.php", true); //
//ajax.setRequestHeader(contentType, mimeType); // SETUP HEADER
//ajax.setRequestHeader('Content-Type', 'text/plain');
ajax.onreadystatechange = function() {
if (ajax.readyState == 4) {
if(this.status == 200){
console.log(ajax.response);
}
}
}
ajax.send("test");
The string "test" should be sent to the test.php file.
The test.php file contains the following:
<?php
print_r($_POST);
?>
And the console.log(ajax.response) returns an empty array.
Why is it so? Do I have to do something else to get the $_POST print from the php file ?
I need to get some JSON data from and AJAX function in PHP
This is what i've written so far but not sure exactly what to do on the PHP side.
JS:
window.onload = function() {
var json = {
hello : 'howareyou',
good : 'yes i am good',
toast : 'i love toast'
}
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
} else {
alert("no");
}
}
xhr.open('POST', 'json.php', true);
xhr.send(json);
}
PHP:
<?php
if(isset($_POST['json']) ){
$json = $_POST ['json'];
$json_d = json_decode($json);
echo $json . 'hello';
} else {
echo 'error';
}
?>
HTML:
<html>
<head>
<script type="text/javascript" src='ajax.js'></script>
<body>
HELLO THERE THIS IS AN HTML PAGEEEEE
</body>
</html>
Stringify your JSON on the client side.
window.onload = function() {
var json = {
hello : 'howareyou',
good : 'yes i am good',
toast : 'i love toast'
}
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
} else {
alert("no");
}
}
xhr.open('POST', 'json.php', true);
xhr.send(JSON.stringify(json));
}
Decode the JSON from the raw request body.
$json = json_decode(file_get_contents("php://input"));
If you want to use raw post data, to get JSON try:
$json = json_decode(file_get_contents("php://input"));
JS example:
var xmlhttp = new XMLHttpRequest(); // new HttpRequest instance
xmlhttp.open("POST", "/json-handler");
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send(JSON.stringify({key:"value", key:"value"}));