Datalist not opening after repopulation - javascript

I'm using AJAX to retrieve information from a database, this was provided for me through another question on StackOverflow, and I've got it working how I want (Minus this one fluke).
Here's how this is set up:
<script>
var input = document.getElementById('search_bar');
input.addEventListener('keypress', function () {
callServer(input);
});
</script>
<script>
function callServer (input) {
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
//return the JSON object
console.log(xmlhttp.responseText);
var arr = JSON.parse(xmlhttp.responseText);
var parentDiv = document.getElementById('items');
parentDiv.innerHTML = "";
//fill the options in the document
for(var x = 0; x < arr.length; x++) {
var option = document.createElement('option');
option.value = arr[x];
//add each autocomplete option to the 'list'
parentDiv.appendChild(option);
};
}
}
xmlhttp.open("GET", "incl/search.php?value="+input.value, true);
xmlhttp.send();
}
Now, when typing into the input field I expect the datalist to update continuously, which it does, the only issue is that the dropdown list is not visible, and I can't access it until I click off of the input field, and then back on the dropdown arrow.
How can I resolve this?
PHP Code for those who are curious:
<?php
include 'connection.php';
$results = array();
if(!isset($_GET['value'])) {
array_push($results, 'No results found.');
die(json_encode($results));
}
$value = $_GET['value'];
$statement = $connection->prepare("SELECT name FROM `item_table`.`items` WHERE `name` LIKE :val LIMIT 5");
$value = '%'.$value.'%';
$statement->bindParam(":val", $value);
if($statement->execute()) {
$rows = 0;
while($row = $statement->fetch()) {
$rows++;
array_push($results, $row['name']);
}
if($rows == 0) {
array_push($results, 'No results found.');
die(json_encode($results));
}
} else {
array_push($results, 'No results found.');
die(json_encode($results));
}
echo json_encode($results);
?>
The JSON being sent to the client is being parsed correctly, just to re-iterate, the issue is that the datalist is not being shown properly.

Related

Json decode from Javascript to php to Javascript

I am trying to get the value from json.stringfy sent to PHP file, for some reason php file is not receiving the key. If I manually add the key it is working fine. What could be wrong here:
My php file:
$request = json_decode(file_get_contents('php://input'), true);
$getID = $request['docid'];
$query = mysqli_query($con, "SELECT * FROM user_details WHERE id = $getID'");
if(mysqli_num_rows($query) > 0)
{
$response["details"] = array();
while ($row = mysqli_fetch_array ($query))
{
// temp user array
$detail = array();
$detail["docname"] = $row["docname"];
$detail["textresults"] = $row["textresults"];
array_push($response["details"], $detail);
}
echo json_encode($response);
$response["success"] = 1;
}
else
{
$response["success"] = 0;
echo json_encode($response);
}
This is my javascript file:
function loadData() {
var docid = window.localStorage.getItem('myKey');
console.log("Docid " + docid);
var xhr = new XMLHttpRequest();
var url = "./api/getData.php";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var json = JSON.parse(xhr.responseText);
console.log(json);
}
};
var data = JSON.stringify({'docid': docid});
xhr.send(data);
}

passing multiple values using xmlhttp.send

I am trying to pass two different values into an XMLHttpRequestObject.send but cannot seem to get the php script to read them both, it will only read the first value passed. How can I get the PHP to read both the values, here is the sample code:
HTML
<select id="mes" onchange="callCourseYards(this);">
<option>-</option>
</select>
Javascript
var XMLHttpRequestObject = false;
if(window.XMLHttpRequest){
XMLHttpRequestObject = new XMLHttpRequest();
}else if(window.ActiveXObject){
XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
}
function callCourseYards(selectObject){
if(XMLHttpRequestObject){
XMLHttpRequestObject.open("POST", "php/CourseChoiceTeeOff.php");
XMLHttpRequestObject.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
XMLHttpRequestObject.onreadystatechange = function(){
if(XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200){
var returnData = XMLHttpRequestObject.responseText;
var messageDiv = document.getElementById('tee');
messageDiv.innerHTML = returnData;
}
}
var data = selectObject.value;
var course = selectObject.value;
XMLHttpRequestObject.send("data=" + data + "course=" + course);
}
return false;
}
PHP
<?php
$pdo_dsn='localhost';
$dbname ='XXX';
$mysql_user='XXX';
$mysql_pass='XXX';
$db = mysqli_connect($pdo_dsn, $mysql_user, $mysql_pass, $dbname);
if(!$db){
print "Unable to connect to MySQL";
}
$myData = $_POST['data'];
$myData1 = $_POST['course'];
$sql_state = "SELECT * FROM ".$myData1." WHERE CourseCode = '".$myData."' ORDER BY CourseCode";
$result = mysqli_query($db, $sql_state);
$out = "";
$myrowcount = 0;
if(!$result){
$out = "Error";
}else{
$out = "<option>Selecciona un campo</option><br/ >";
$numresults = mysqli_num_rows($result);
for ($i = 0; $i < $numresults; $i++){
$row = mysqli_fetch_array($result);
$teeOff = $row['TeeOff'];
$out .= "<option id='".$myData."' value='".$teeOff."'> ".$teeOff."</option>";
}
$out .= "<br/ >";
}
print $out;
?>
I cannot seem to get the values through the XMLHttpRequestObject to go through into the PHP. I am not sure if its the syntax or how they should get past into the PHP.
I have tried using the & and the + symbols to concatenate both values, but I am not sure if this is possible. Does anyone know how I can fix this problem? I need both values to be able to do the mySQL search in the database.
Any help would be greatly appreciated. Thanks

Send php while loop variables to javascript file

My file.js is calling a php file to fetch from database and return an encoded JSON object so I can put it on a table. Here is the file.js -
url = "backend.php"
xmlhttp.open("GET", url, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
myJSONObj = JSON.parse(this.responseText);
for ( i=0;i<myJSON.length;i++)
{
var x = document.getElementById("datatable").rows[i].cells;
x[6].innerHTML =obj[i].age;
}
}
}
And the backend.php file goes -
$sql_stmt= "SELECT * FROM TABLE ";
$result = odbc_exec($conn_id, $sql_stmt);
while ($row = odbc_fetch_array($result)) {
$age=$row['age'];
$ages[] = array('age'=> $age);
}
$myJSON = json_encode($ages);
echo $myJSON;
This works completely fine, but I have to wait for the PHP while loop to finish, which takes too long with large number of entries. I want to be able to return the JSON within the loop, not at the end.
Is there any way I can make the xmlhttp request and keep receiving JSON while the PHP while loop runs, not having to wait for it to finish and then send across all the rows together? Thanks
I think you should use mysql limit
JS:
var hasData = true;
var loop = 0;
while(hasData){
url = "backend.php?page="+loop;
xmlhttp.open("GET", url, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
if(this.reponseText != ""){
myJSONObj = JSON.parse(this.responseText);
for ( i=0;i<myJSON.length;i++)
{
var x = document.getElementById("datatable").rows[i].cells;
x[6].innerHTML =obj[i].age;
}
}else{
hasData = false; //if no data retrieved
}//end if
}//end if
}
loop++; //increment loop
}//end while
PHP:
$loop = $_GET['loop'];
if($loop != ""){
$max_output = 10; //how many rows you want to display per query
$starting_row = $max_output * $loop;
// LIMIT 0, 10 = if loop is 0
// LIMIT 10, 10 = if loop is 1
// LIMIT 20, 10 = if loop is 2
$sql_stmt= "SELECT * FROM TABLE LIMIT {$starting_row}, {$max_output}";
$result = odbc_exec($conn_id, $sql_stmt);
if($result){
while ($row = odbc_fetch_array($result)) {
$age=$row['age'];
$ages[] = array('age'=> $age);
}
$myJSON = json_encode($ages);
echo $myJSON;
}else{
exit; //make sure nothing is echoed/print
}
}
{
myJSONObj = JSON.parse(this.responseText);
for ( i=0;i<myJSON.length;i++)
{
var x = document.getElementById("datatable").rows[i].cells;
x[6].innerHTML =obj[i].age;
}
}
}
Hope this helps

Why do I always get undefined response with this ajax post to php?

I am using mouseover event on span element to initiate an ajax post call to php page, but I always get undefined, first for responseText when I used a simple echo to get response and now when I use responseXML. Can somebody please explain me why.
Here is ajax code:
var span = document.getElementsByTagName('span');
for (var i = 0; i < span.length; i++) {
span[i].addEventListener("mouseover", showInformation, false);
}
function showInformation(event) {
var xhr = new XMLHttpRequest();
xhr.open("POST", "../includes/ajax_response.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
content(xhr, event);
}
};
xhr.send("uname=" + event.target.firstChild.textContent);
}
function content(xhr, event) {
var info = document.getElementById('displayInformation');
var xmlResponse = xhr.resopnseXML;
var xmlDocumentElement = xmlResponse.documentElement;
var message = xmlDocumentElement.firstChild.data;
info.innerHTML = message;
info.style.visibility = "visible";
event.target.addEventListener("mouseout", function() {
document.getElementById('displayInformation').style.visibility = "hidden";
}, false);
}
And this is php code:
$username = $_POST['uname'];
$query = "SELECT id, joined FROM users WHERE username = '{$username}' LIMIT 1";
$first_result = Database::getInstance()->query($query);
if ($first_result->num_rows == 1) {
foreach ($first_result as $first) {
$id = $first['id'];
$joined = $first['joined'];
}
}
$first_result->free();
$query = "SELECT COUNT(message) AS count FROM blogs WHERE user_id = '{$id}'";
$results = Database::getInstance()->query($query);
if ($results) {
foreach ($results as $result) {
$number = $result['count'];
}
}
header("Content-Type: text/xml");
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
echo '<response>';
echo "joined: {$joined}";
echo "number of posts: {$number}";
echo '</response>';
This is version of php with xml, I tired simpler versions with just
$username = $_POST['uname'] and then echo $username, but always response is
undefined.
I read your code once and there does not seem to be any major error. However, I found out this minor bug:
var xmlResponse = xhr.resopnseXML;
spelling of responseXML is incorrect .. maybe that's what's causing the xmlResponse to be undefined?

Why am I not able to fetch property of the object that I get from PHP?

I am trying to receive data from database based on the name entered by user, everything works fine I do see the value on screen and no error Here is the php code :
<?php
$dbhost = "localhost";
$username = "root";
$password = "";
mysql_connect($dbhost,$username,$password);
#mysql_select_db("trynew") or die(mysql_error());
$user ="mon";
$query = "SELECT * FROM trynewtable where name = '$user' ";
$all_result = array();
$result = mysql_query($query);
if($result==FALSE)
{
die(mysql_error());
}
while($row = mysql_fetch_assoc($result))
{
$all_result[] = $row;
}
header('Content-Type: application/json');
$jsondata = json_encode($all_result);echo $jsondata;
mysql_close();
?>
JavaScript code :
var loadingFunc=function()
{
var xhr;
if(window.XMLHttpRequest)
{
xhr = new XMLHttpRequest();
}
else
{
xhr = new ActiveXObject('Microsoft.XMLHTTP');
}
var jsonData= "";
xhr.onreadystatechange =function()
{
if(xhr.readyState==4)
{
if(xhr.success =200)
{
jsonData = xhr.responseText;
document.getElementById("dvID").innerHTML = jsonData;
//var parsejson = JSON.parse(jsonData);
//document.getElementById("dvIDO").innerHTML = parsejson.age;
document.getElementById("dvIDO").innerHTML = jsonData[0].age;
}
else
{
document.getElementIdById("dvID").innerHTML = "it's not success ";
}
}
else
{
console.log("error is here");
console.log(xhr.readyState);
}
}
var element1 = document.getElementById("dvID") ;
xhr.open("POST","index.php");
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
var sendD = document.getElementById("data_found").value;
var data = "data_found=" + sendD;
var element = document.getElementById("btn") ;
if(element)
{
element.addEventListener('click',function(){
console.log("just clicked")
xhr.send(data);
})
}
};
window.onload = loadingFunc();
but the output that I see on the html div is :
[{"id":"1","Name":"mon","Age":"26","Gender":"F"}]
undefined
I am getting the whole object but whenever I am trying to fetch any property of the object like age here (parsejson.age or jsonData[0].age) it's showing undefined , Could anyone help me how do I fetch any property of the object?
Kindly let me know what am I doing wrong ?
First transform the cleartext response into a javascript object. You have the line already there but commented out it seems, after that:
alert(jsonData["Age"]); //Age
alert(jsonData.Age); //Age

Categories

Resources