Search code examples
javascriptphpxmlhttprequest

Getting data in JavaScript from php


Specifically, I need to get data in html from a database. If there is a simple way to do that in JavaScript then just skip the next part ^^

I have successfully written the php code to retrieve the data from the database, which is something like this:

$host = (host)
$user = (user)
$db = (database)
$pw = (password)

$funct = $_GET["Function"];

switch ($funct) {
    case "getName": {
        $personid=$_GET["PersonID"];
        $output = getName($host, $user, $pw, $db, $personid);
        echo $output;
        break;
    }
}

Of course there are more values for $funct, but to keep things short I only wrote one and left out the function itself. I tested it by making a form with method="GET", and it correctly prints the name. So my actual question is how to pass the name onto a html document, where I want to list the names of certain people. I did research and found for example that I need to use "echo $output;", I had originally tried "return $output;" but that was not enough. My current js-code is something like this:

"use strict";

function getName(field_id, person_id) {
    var request = new XMLHttpRequest();

    request.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
           document.getElementById("name"+field_id).innerHTML=this.responseText;
        }
    };

    request.open("GET", "people.php");

    request.setRequestHeader("Function", "getName");
    request.setRequestHeader("PersonID", person_id);

    request.send();
}

I originally tried fetch(), because it was recommended by javascript.info, but I didn't find many examples, so I scratched that. If i change it to ".innerHTML=this.responseText+this.status;" it just prints "200" onto the name field. There are no error messages.

It probably looks like I'm making it too complicated, but the code is supposed to do more stuff than what I shared, I'm just keeping it simple for you to understand.

I hope you can help me!


Solution

  • $_GET won’t give you the request headers, it will give query string parameters. You want to change your request to request.open("GET", "people.php?Function=getName&PersonId=" + person_id).