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

JavaScript

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

JavaScript

Data Code

JavaScript
Advertisement