Prayag Prayag - 2 months ago 12
Javascript Question

Alert the value in java-script which is queried from Database without using Ajax

i am working on a mini project to display value queried from database based on the check box selected.
i have come across many post : it can be done using ajax/jquery.
i donot know how to use ajax.
pl help me i am stuck at final Alert window output.

Here is my main test.php

<!DOCTYPE html>
<!--[if lt IE 7 ]><html class="ie ie6" lang="en"> <![endif]-->
<!--[if IE 7 ]><html class="ie ie7" lang="en"> <![endif]-->
<!--[if IE 8 ]><html class="ie ie8" lang="en"> <![endif]-->
<!--[if (gte IE 9)|!(IE)]><!--><html lang="en"> <!--<![endif]-->
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta charset="utf-8">
<title>--</title>

<script>

function checkAddress()
{


if (document.querySelector('form[name="frmUser"] input[type="checkbox"]:checked')) {
//alert("Success! (form would be submitted here)");
var $temp = <?php include 'alert.php';?>
//alert("Success! (form would be submitted here)");
alert($temp)
document.frmUser.action = "test.php";
document.frmUser.submit();
} else {
alert("Pl select checkbox which You wish to Update ");
}
}


</script>

</head>

<body >

<h1 style="text-align:center;"></h1>
<?php

// php populate html table from mysql database

$conn = mysqli_connect("localhost","root","11111111");
mysqli_select_db($conn, "test");
$result = mysqli_query($conn,"SELECT * FROM inputs ORDER BY userId DESC");
?>

<div class="form-style-1">
<form name="frmUser" method="post" action="">
<div style="width:1200px;">
<table style="text-align:center;"border="0" cellpadding="10" cellspacing="1" width="1200" class="tblListForm" align="center">
<tr class="listheader">
<td></td>
<td>SN</td>
<th>Domain</th>
<th>department</th>
<th></th>
</tr>
<?php
$i=0;
$j=1;
while($row = mysqli_fetch_array($result)) {
if($i%2==0){
$classname="evenRow";
} else {
$classname="oddRow";
}
?>
<tr class="<?php if(isset($classname)) {
echo $classname;
}?>">
<td><input type="checkbox" name="users[]" value="<?php echo $row["userId"]; ?>" ></td>
<td><?php echo $row["userId"]; ?></td>
<td><?php echo $row["department"]; ?></td>

<th colspan="4"><input type="button" name="update" class="button" value="Apply" onClick="checkAddress(this);" /></th></tr>
<?php
$i++;
$j=$i+1;
}
$conn->close();
?>
</table>
</div>
</form>

</div>

</body>
</html>


Below is my alert.php

<?php

$servername = "localhost";
$username = "root";
$password = "11111111";
$dbname = "test";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

if(isset($_POST['submit'])){
$rowCount = count($_POST['users']);
//echo "The rowcount is ".$rowCount."";
$queried_name;
for($i=0;$i<$rowCount;$i++) {
$num_var= " ";
$num_var = mysqli_real_escape_string($conn,$_POST['users'][$i]);
//echo "The numvar is ".$num_var."";

$result = mysqli_query($conn, "SELECT * FROM inputs WHERE userId='".$num_var."'");
if (!$result) {
echo 'MySQL Error: ' . mysqli_error($conn);
exit;
}

while($row[$i]= mysqli_fetch_array($result)) {

$queried_name = $row[$i]['department'];
return $queried_name;
echo 'alert("Please Use below department.' .$queried_name.'")';
}}}

$conn->close();

?>

Answer

If you are using jQuery, you can make use of their inbuilt ajax function. If you are limited to "vanilla" javascript, below is the function I normally use for AJAX calls:

function ajaxQuery(url, method, param, async, onsuccess, onfailure) {
    var xmlHttpRequest = new XMLHttpRequest();

    var callback = function(r) { r.status==200 ? (typeof(onsuccess)=='function' && onsuccess(r)) : (typeof(onfailure)=='function' && onfailure(r)); };

    if(async) { xmlHttpRequest.onreadystatechange = function() { if(xmlHttpRequest.readyState==4) { callback(xmlHttpRequest); } } }
    xmlHttpRequest.open(method, url, async);
    xmlHttpRequest.setRequestHeader('X-REQUESTED-WITH', 'XMLHttpRequest');
    if(method == 'POST') { xmlHttpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); }
    xmlHttpRequest.send(param);
    if(!async) { callback(xmlHttpRequest); }
}

Usage example:

ajaxQuery('alert.php', 'GET', null, true, function(r) {
    alert(r.responseText);
}, function() { alert('Something went wrong.'); });

Naturally, if alert.php performs any complex tasks, it will have to take parameters, and you then could refer to alert.php?parameter0=something&parameter1=something instead of just alert.php.

I would recommend doing something a bit more simple at this stage, as you are confusing php with javascript, and you seem to not quite understand what exactly an include statement does in a php file. It doesn't return the output of the script - what it does is kind of equivalent to echoing the whole php file into another! You were assigning the contents of alert.php to poor old alert() from javascript. I would personally separate out the projects into languages at this stage (do something purely in javascript, purely in php, etc.) and start mixing them together when I felt ready.

You don't need javascript to assign a value to a form's action attribute. This can be done inside the form tag itself.

Please let me know if anything needs to be explained further.


Update: here are the code samples you have requested. I went through your code and "fixed" it. Important notes: you should pick a formatting standard and stick to it. Examples:

  • You connect to the database in 2 different places in 2 different ways, you should have a single database connection file that you include in all the relevant php's.
  • Your quotation marks are sometimes single and sometimes - double, I personally only use double quotes when necessary or convenient (SQL queries, strings containing special characters like "\n").
  • Indentation wasn't following any particular logic, and empty lines were everywhere; it's important that you format your code so that you and others can read it in a few months when no-one remembers what the hell it was about.
  • In your test.php you have a table nested inside a div, nested inside a form, nested inside a div - that's hardly necessary.
  • Why are there empty td and th tags present?
  • You should pay close attention to how your HTML tags are closed: I've noticed a few " > and " />. Of course, browsers won't care for the most part, but your code readability suffers.
  • HTML attributes are always lowercase, as far as I know (onClick should be onclick, etc.).
  • Your table layout is strange, but I didn't touch it. I have no idea why you have a colspan="4" element in every row.
  • Method names (GET and POST) should always be uppercase (except in XHTML where it's the other way around).

1) test.php

<!DOCTYPE html>
<!--[if lt IE 7]><html class="ie ie6" lang="en"><![endif]-->
<!--[if IE 7]><html class="ie ie7" lang="en"><![endif]-->
<!--[if IE 8]><html class="ie ie8" lang="en"><![endif]-->
<!--[if (gte IE 9)|!(IE)]><!--><html lang="en"><!--<![endif]-->
<head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta charset="utf-8">
    <title>--</title>
    <script>
    function ajaxQuery(url, method, param, async, onsuccess, onfailure) {
        var xmlHttpRequest = new XMLHttpRequest();
        var callback = function(r) { r.status==200 ? (typeof(onsuccess)=='function' && onsuccess(r)) : (typeof(onfailure)=='function' && onfailure(r)); };
        if(async) { xmlHttpRequest.onreadystatechange = function() { if(xmlHttpRequest.readyState==4) { callback(xmlHttpRequest); } } }
        xmlHttpRequest.open(method, url, async);
        xmlHttpRequest.setRequestHeader('X-REQUESTED-WITH', 'XMLHttpRequest');
        if(method == 'POST') { xmlHttpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); }
        xmlHttpRequest.send(param);
        if(!async) { callback(xmlHttpRequest); }
    }

    function checkAddress(e) {
        var checkbox = e.target.parentNode.parentNode.querySelector('[type="checkbox"]');
        if(checkbox) {
            ajaxQuery('alert.php', 'POST', 'users[]='+checkbox.value, true, function(request) {
                alert(request.responseText);
            }, function() { alert('Shiver me timbers!'); });
        } else {
            alert('Please select a checkbox to update.');
        }
    }
    </script>
</head>
<body>
    <h1 style="text-align: center;"></h1>
    <?php
        $conn = mysqli_connect('localhost', 'root', '11111111');
        mysqli_select_db($conn, 'test');
        $result = mysqli_query($conn, "SELECT * FROM inputs ORDER BY userId DESC");
    ?>
    <div class="form-style-1">
        <form name="frmUser" method="POST" action="test.php">
            <div style="width: 1200px;">
                <table style="text-align: center;" border="0" cellpadding="10" cellspacing="1" width="1200" class="tblListForm" align="center">
                    <tr class="listheader">
                        <td></td>
                        <td>SN</td>
                        <th>Domain</th>
                        <th>Department</th>
                        <th></th>
                    </tr>
                    <?php
                    $i=0;
                    $j=1;
                    while($row = mysqli_fetch_array($result)) {
                        $classname = $i%2==0 ? 'evenRow' : 'oddRow';
                    ?>
                    <tr<?php if(isset($classname)) { echo ' class="'.$classname.'"'; } ?>>
                        <td>
                            <input type="checkbox" name="users[]" value="<?=$row["userId"];?>">
                        </td>
                        <td><?=$row["userId"];?></td>
                        <td><?=$row["department"];?></td>
                        <th colspan="4">
                            <input type="button" name="update" class="button" value="Apply" onclick="javascript: checkAddress(event);">
                        </th>
                    </tr>
                    <?php 
                        $i++;
                        $j=$i+1;
                    }
                    $conn->close();
                    ?>
                </table>
            </div>
        </form>
    </div>
</body>
</html>

2) alert.php

<?php
$servername = 'localhost';
$username = 'root';
$password = '11111111';
$dbname = 'test';
$conn = new mysqli($servername, $username, $password, $dbname); // Create connection
if($conn->connect_error) { die('Connection failed: '.$conn->connect_error); } // Check connection
if(isset($_POST['submit'])){
    $rowCount = count($_POST['users']);
    $num_var= '';
    $queried_name = '';
    for($i=0; $i<$rowCount; $i++) {
        $num_var = mysqli_real_escape_string($conn, $_POST['users'][$i]);
        $result = mysqli_query($conn, "SELECT * FROM inputs WHERE userId='".$num_var."'");
        if(!$result) { die('MySQL Error: '.mysqli_error($conn)); }
        while($row[$i]= mysqli_fetch_array($result)) {
            $queried_name = $row[$i]['department'];
            echo "Please refer to the following department: $queried_name\n";
        }
    }
}
$conn->close();
?>