0

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!";
?> 
frraj
  • 27
  • 5
  • Where do you want the message to appear? You aren't doing anything with the response that the PHP script is sending you. – Stoopkid Feb 28 '18 at 22:47
  • Here's some [documentation](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) - I recommend you read it to understand how to use `XMLHttpRequest` – Jaromanda X Feb 28 '18 at 22:48
  • Possible duplicate of [How to pass JavaScript variables to PHP?](https://stackoverflow.com/questions/1917576/how-to-pass-javascript-variables-to-php) – Obsidian Age Feb 28 '18 at 22:49
  • for now i am not concerned with the data a send, i am wondering how i make the "Hello!" string appear when the "insert.php" file after being called. – frraj Feb 28 '18 at 22:50

2 Answers2

0
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!

0
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.

Stoopkid
  • 1,885
  • 2
  • 17
  • 30