简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM