0

I'm new in Website programming. Recently I'm building a log in website. First I want to find out how does JavaScript send and PHP receive data. My HTML codes are as followed:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>CSS Test</title>
        <link type="text/javascript" herf="script.js"/>
    </head>
    <body>
        <div id="div1">
            <input placeholder="Username:" class="inputter" id="inputter1"/>
            <input placeholder="Password:" class="inputter" id="inputter2"/>
            <button onclick="send()" id="button1">Submit</button>
        </div>
    </body>
</html>

The codes in file 'script.js' are as followed:

function send(){
    var xmlhttp;
    if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
      }
    else
      {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    xmlhttp.open('POST','query.php',true)
    xmlhttp.send("user="+document.getElementById("inputter1")+"password="+document.getElementById("inputter2"))
}

And the PHP codes are as followed:

<?php
echo "Data received:user is ".$_POST['user']
?>

When I typed in the 'inputter1' and clicked the button, nothing happened. There wasn't any echo on the page. I guess a syntax mistake caused that but I don't know where and how to change that. Please help me. Thanks to any help.

Maxwang
  • 3
  • 1
  • One issue is that [`getElementById()`](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById) returns an Element object, not a string. Resulting data looks like `user=[object HTMLInputElement]password=[object HTMLInputElement]`. You might try using the `value` properties of those [input elements](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement). You should be able to troubleshoot by inspecting the data transmitted and any errors encountered. – showdev Mar 21 '21 at 04:23
  • Also, nothing will echo to the page since the request is made asynchronously via `XMLHttpRequest`. You'll need to handle the response and add the returned content to the page. – showdev Mar 21 '21 at 04:29
  • @showdev Thank you very much for those experienced suggestions! – Maxwang Mar 21 '21 at 04:31
  • My intent is to make php receive my data and query the MySQL databases. So I want to make sure it receive the data. – Maxwang Mar 21 '21 at 04:32
  • You might find the examples here helpful: [How to get the response of XMLHttpRequest?](https://stackoverflow.com/questions/3038901/how-to-get-the-response-of-xmlhttprequest) – showdev Mar 21 '21 at 04:36
  • The "IE5" and "IE6" should be a hint that this code is rather outdated. You would be much better off looking up the jQuery ajax method IMHO. But https://stackoverflow.com/questions/5004233/jquery-ajax-post-example-with-php will help you. – Gavin Simpson Mar 21 '21 at 06:31

0 Answers0