Skip to content
Advertisement

Getting data out of a database with XMLHttpRequest, PDO, JSON, PHP and JavaScript

So following my last question I want to use the value that is submitted in the input tag to get the matching id in my database. I have created two files for it but I can’t figure out how to link them. Also note I made a database with a few values(id, firstname, etc.) and when the user fills in 1 I want it to display id 1 & the firstname.
This code is from the last question & I’ve added xmlhttp:

Input code

Choose a number between 1 and 5 Your info shall be shown here Click me! var myButton = document.getElementById(‘btn’); myButton.onclick = function(){ alert(document.getElementById(‘myid’).value); var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if( xmlhttp.readyState == 4 && xmlhttp.status == 200) { var dbText = xmlhttp.responseText; document.getElementById(‘dbinfo’).innerHTML = dbText; } } xmlhttp.open(“POST”, “LinkToDataFile”, true); xmlhttp.setRequestHeader(“Content-type”, “application/x-www-form-urlencoded”); }

That is what the user sees and the number is displayed correctly however I now need to link it to my file data.php which I have tried but it cannot get the value.

Data Code

<?php
    require_once('input_code');
    //Get the data from the database and echo them here
    $servername = "localhost";
    $username = "root";
    $password = "";
    $databasename = "db_name";

    try
    {
        $connection = new PDO("mysql:host=".$servername.";dbname=".$databasename, $username, $password);
        $connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        
        
        $statement = $connection->prepare("SELECT `id`, `firstname`, FROM `db_name` WHERE `id` = :myid"); //Here it needs to grab the value but it does not work.
        $statement->bindParam(':id', $id);
        $id = $_POST['id'];
                        
        $statement->execute();
        
        $result = $statement->setFetchMode(PDO::FETCH_ASSOC);
        
        $data = "";
        foreach($statement->fetchAll() as $key => $value)
        {
            $data .= $value['id']." | ".$value['firstname'];
        }
    }
    catch(PDOException $e)
    {
        echo "The following error occurred : ".$e->getMessage();

    }

    echo $data;
    

?>

So what am I doing wrong? am I missing something obvious like the $id again or is it a series of errors, the only thing it does now is giving me an alert with the number.

Advertisement

Answer

By adding a line and moving $id before $statement it is all fix thanks to Dante Javier

Input code

xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");  //Under this add the following lines:
                var id = document.getElementById('myid').value; 
                xmlhttp.send("id="+id);

Data Code

$id = $_POST['id']; //Move this above the $statement = $connection->prepare.
Advertisement