Detective merry Detective merry - 4 months ago 26
HTML Question

How to count number of records using AJAX(without jQuery) and PHP

I am a beginner programmer and I would like to count the number of records in a table. I have seen plenty of extracts of codes but I cant seem to piece them together to transfer the PHP result to my javascript codes. Here are the codes I have ended up with :

showscan.php

<php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
error_reporting(E_ERROR);
try{
$conn = new mysqli("localhost", "root", "root", "bencoolen");

$query = "SELECT COUNT(*) FROM discountcode";
$result = $conn->query($query);
echo mysql_num_rows($result);

$conn->close();
}
catch(Exception $e) {
echo "error";

}
?>


index.html

<head>
<!-- The policy below is cancelled out so the project can run on my android device's version -->
<!--<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">
-->
<meta name="msapplication-tap-highlight" content="no">
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
<link rel="stylesheet" type="text/css" href="css/index.css">
<link rel="stylesheet" href="js/jquery.mobile-1.4.5.min.css">
<link rel="stylesheet" href="css/jquery.mobile.datepicker.css" />
<script src="js/jquery-1.11.3.min.js"></script>
<script src="js/jquery.mobile-1.4.5.min.js"></script>
<script src="js/jquery.ui.datepicker.js"></script>
<script id="mobile-datepicker" src="js/jquery.mobile.datepicker.js"></script>
<script type="text/javascript" charset="utf-8" src="phonegap-1.4.1.js"></script>
<script type="text/javascript" src="barcodescanner.js"></script>
<script type="text/javascript" src="cordova.js"></script>
<script src="common.js"></script>

<script type="text/javascript">
function showscan(){

var xmlhttp = new XMLHttpRequest();
var url = serverURL() + "/showscan.php";
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {

//The alert below was alerted
alert("readystate and status OK");

document.getElementById("noscan").innerHTML = xmlHttp.responseText;

//The alert below was not alerted
alert(document.getElementById("noscan").innerHTML);

}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();

}

</script>
</head>

<body>
<div data-role="page" id="pageone">
<div data-role="content" class="ui-content" id="loginsection">
<form name="LoginForm">
<div class="ui-grid-a">
<div class="ui-block-b">
<input id="noscan" type="text" class="input-text" placeholder="Number of scans"/>
</div>
</div>
</form>
</div>
</div>
</body>


'document.getElementById("noscan").innerHTML' was not getting alerted and the field containing 'document.getElementById("noscan").innerHTML' stated below html file was also blank after the function ran. These codes were part of my programming notes after I removed all json_encoding, because I was not sure what it does and to follow examples better. I do have jQuery installed but jQuery Ajax is a little too overwhelming for me and I can visualise making an Ajax call without jQuery better.

Question: How to I make it so that the count(*) value from PHP gets transfered over to my javascript code?
In what situations will I have to encode my results with JSON before sending them over?

Thanks!

Answer

Alright you have some typos & some errors in your code:

TYPOS Your <php tag in your showscan.php => <?php

xmlHttp in the line document.getElementById("noscan").innerHTML = xmlHttp.responseText; of javascript function showscan() should be xmlhttp. (small h) since JavaScript is a case-sensitive language.

Errors javascript showscan() noscan in document.getElementById("noscan").innerHTML = xmlHttp.responseText; is a text input and input text does not have property innerHTML

showscan.php

mysql_num_rows; in echo mysql_num_rows($result); should be mysqli_num_rows; notice the difference? mysql & mysqli

Suggesstion

serverURL() in var url = serverURL() + "/showscan.php"; if you have this showscan.php page in the same folder then just write showscan.php.

By the looks of your HTML code, I don't see anything calling your function showscan(). Therefore, either you can call it on body load <body onload="showscan();"> or insert a <button> and call it with onclick attribute <button type="button" onclick="showscan();">submit</button>

NOW TRY THIS CODE

showscan.php

<?php
    header("Access-Control-Allow-Origin: *");
    header("Content-Type: application/json; charset=UTF-8");
    error_reporting(E_ERROR);
    try{
        $conn = new mysqli("localhost", "root", "root", "bencoolen");
        $query = "SELECT COUNT(*) FROM discountcode";
        $result = $conn->query($query);
        echo mysqli_num_rows($result);
        $conn->close();
    }
    catch(Exception $e) {
        echo "error";
    }
?>

Javascript Function showscan()

function showscan(){
    var xmlhttp = new XMLHttpRequest();
    var url = "showscan.php";
    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            //The alert below was alerted                           
            alert("readystate and status OK");
            document.getElementById("noscan").value = xmlhttp.responseText;
            //The alert below was not alerted
            alert(document.getElementById("noscan").value);
        }
    };
    xmlhttp.open("GET", url, true);
    xmlhttp.send(); 
}