使用javascript和php验证可用性

I want to make a javascript function which checks the database whether the id requested by the user is available or not. My code is:

HTML:

<button type="button" onclick="chkId()">Check Availability</button><span id="chkresult"></span>

Javascript code:

function chkId()
        {
            $("#chkresult").html("Please wait...");
           $.get("check_id.php", function(data) { $("#chkresult").html(data); });
        }

The check_id.php file:

<?php
require 'connect.php';
$id_query = mysql_query("SELECT COUNT(*) AS TOTAL FROM `Table4` WHERE `Unique ID` = '$id'");
list ($total) = mysql_fetch_row($id_query);
if ($total == 0)
{
    echo "Available!";
}
else if ($total > 0)
{
    echo "Not Available!";
}
?>

But when the button is clicked, nothing happens. I just get a 'Please wait...' message, but as expected by the code, after 'Please wait...' it should change either to Available or to Not Available. But I only get the 'Please Wait...' message, and the result Available or Not Available is not printed on the screen. Please help me what changes do I need to make in my code.

I do not see the $id variable in your PHP script that is used by your $id_query.

Try adding that above $id_query

A few things I notice:

  • Your javascript is not passing the id parameter to your php backend. See the documentation for the proper syntax to pass that id param.

  • Your PHP is calling the mysql_query method and one of the parameters that it is passing in is the $id - but $id has not been declared. Check your PHP logs and you'll see where it is choking.

  • Because the PHP code is likely failing due to the unresolved variable, it is returning an error code. When JQuery receives the error code, it goes to call your ajax failure handler, but you have not declared one! Try adding a .fail(function(){}); to your get call as the docs describe - and you'll likely see the php error message show up.

EDIT: Obligatory php sql injection attack warning. Make sure to escape client input!!!

 $.ajax({
                    type: "POST",
                    url: "check_id.php",

                    data: {
                     id:id; //the id requested by the user.You should set this
                    },
                    dataType: "json",


                    success: function(data){  

                       $('#chkresult').html(data);   
                        }  

                    },

                    failure: function(errMsg) {
                        alert(errMsg);


                    }
                });

In your php

<?php
require 'connect.php';
$id_query = mysql_query("SELECT COUNT(*) AS TOTAL FROM `Table4` WHERE `Unique ID` = '$id'");
list ($total) = mysql_fetch_row($id_query);
if ($total == 0)
{
   header('Content-type: application/json');
    echo CJavaScript::jsonEncode('Available');
}
else if ($total > 0)
{
    header('Content-type: application/json');
    echo CJavaScript::jsonEncode('Not available');
}
?>