简体   繁体   中英

How do I populate second textbox based on the value entered in first textbox using jquery?

I am trying to populate the text fields based on the value entered in the first textbox field from the database but I am not getting any response when I enter some value into the first textbox field. Please check the code

Javascript:

 <script type="text/javascript">
    $("#tin").blur(function () {
    $.post("tin_handle.php",
           {
               tin: $(this).val() 
        }, 
    function (data){
        $("#cname").val(data.cname);
        $("#caddress").val(data.caddress);
    });

</script>

Tin_handle.php:

<?php
    $tn = trim($_POST['tin']);

    require_once("sqlconnect.php");

    $q="SELECT CONCAT(address,',',city,',',state) AS caddress,cname,tin FROM company WHERE tin=$tn;                                                                          

    $r = @mysqli_query ($dbc, $q);

    //$arr=array();
    while ($row = mysql_fetch_array($r))
    {

        $arr=array('cname'=>$cname, 'caddress'=>$caddress);
        echo json_encode($arr);

    }

?>

Have you checked a JavaScript error console? Where is the { on the first line of your JavaScript matched?

First, I've never used mysqli. Does mysqli_query work with mysql_fetch_array ?

In any case, one potential problem I see is here:

while ($row = mysql_fetch_array($r)) {
    $arr=array('cname'=>$cname, 'caddress'=>$caddress);
    echo json_encode($arr);
}

That won't be a correct json unless the result count is 1. For example if you get two results you'll generate an incorrect JSON:

{"cname":"CNAME1","caddress":"CADDRESS1"}{"cname":"CNAME2","caddress":"CADDRESS2"}

If you need to read multiple rows, the loop should be:

$arr = array();    
while ($row = mysql_fetch_array($r)) {
    //...
    $arr[] = array('cname'=>$cname, 'caddress'=>$caddress);
}
echo json_encode($arr);

But then the javascript code will get an array back, rather than an object, so you'll have to change it too.

If this doesn't solve your problem, add some more info/code to your question so that we could understand it better

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM