XMLhttpresponse returning empty array - javascript

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 ?

Related

AJAX request returning response text of 'false' instead of desired response text

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

how to send data to php file then echo a message

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.

javascript ajax login form handling

Im working on an ajax form to show errors without reloading the page. So if everything is good, the user we be redirected to home.php. At the moment the user will also be redirected when there is an error.
This is my code so far:
index.php:
<script>
function myFunction()
{
var elements = document.getElementsByClassName("formVal");
var formData = new FormData(elements);
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
window.location.replace("/index.php");
}
}
xmlHttp.open("post", "login.php");
xmlHttp.send(formData);
}
</script>
login.php
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
if (!$user->logUser($$_POST['username'], $_POST['password'])) {
echo 'ok';
} else {
echo 'not ok';
}
}
?>
Remove loop from the code and pass elements in FormData() because passing element will take all the fields inside the form
var elements = document.getElementsByClassName("formVal");
var formData = new FormData(elements);
Throw a 401 error if it fails login, this will stop the redirect.
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
if (!$user->logUser($$_POST['username'], $_POST['password'])) {
echo 'ok';
} else {
header("HTTP/1.1 401 Unauthorized");
exit;
}
}
?>
do you know jquery ?
jquery w3 school search on google
avaible
$('#data-div-id').load('www.sdasd .php ? or whatevver');
function tmp_func_sil_ok(e){
$.ajax({type:"GET",url:"go.php",data:{'snf_sil':e},success: function(e){msg_("<h3>Başarılı</h3>");}});
}

I am trying to pass Blob object to php file using AJAX but failed to do so

I am trying to upload Blob Object to php file using XMLHttpRequest(); but Blob is not passing to the php file.
blob_it = new Blob(array_of_blobs);
var xhr = new XMLHttpRequest();
xhr.open("POST","page.php",true);
xhr.send("blob_object="+blob_it);
xhr.onreadystatechange = function(){
if(this.status == 200 && this.readyState == 4){
console.log(this.response);
}
}
On 'page.php' script looks like
<?php
if(isset($_POST['blob_object']) === true){
echo "Object received";
}else{
echo "No object received";
}
?>
It returns 'No object received'. I think something is missing in my AJAX request. Please can any one tell.

Retrieving AJAX data in PHP

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']);

Categories

Resources