An.Gell
An.Gell

Reputation: 11

Setting value to textbox using PHP with help of Javascript

What I intend to do is a dialog box will prompt and the user will input his username, when clicked OK, the php codes inside the javascript function mySearch will get his details in mysql and display it in the textbox. HELP. T_T It won't work.

    <script>
        function mySearch()
        {    var name = prompt("Search","Enter username");

            if (name!=null && name!="")
            {
                    var sentval = document.getElementById("sentval");
                    sentval.value = name;

                    <?php
                        $myLink = mysql_connect('localhost','root', '1234') or die(mysql_error());
                        $selectDB = mysql_select_db('proj2db', $myLink) or die(mysql_error());
                        $sql = "SELECT * FROM userTBL WHERE uName ='".$_POST['sentval']."'";
                        $exec = mysql_query($sql, $myLink);
                        $row = mysql_fetch_array($exec);

                        $uname = $row['uName'];
                        $pwd = $row['pwd'];
                        $code = $row['sAns'];
                        $link = $row['path'];
                    ?>              
            }
        }
    </script>
</head>
<body>
    <form method="post" action="" name="myform" id="myform">
        <input type="hidden" id="sentval"/>
        <center>
            <table>
                <tr>    
                    <td><font face="Tahoma" size = "2" color="#0B3861">Username:&nbsp&nbsp</font></td>
                    <td>
                        <input type = "text" id = "uname" name = "uname" size="35" value="<?php echo $uname ?>"/>
                        <button type="button" style="height: 25px; width: 60px" onclick="mySearch()">Search</button>
                    </td>
                </tr>
                <tr>    
                    <td><font face="Tahoma" size = "2" color="#0B3861">Password:&nbsp&nbsp</font></td>
                    <td><input type = "password" id = "pwd" name = "pwd" size="35" value="<?php echo $pwd ?>"/></td>
                </tr>
                <tr>
                    <td><font face="Tahoma" size = "2" color="#0B3861">Re-type Password:&nbsp&nbsp</font></td>
                    <td><input type = "password" id = "repwd" name = "repwd" size="35" value="<?php echo $pwd ?>"/></td>
                </tr>
                <tr>
                    <td><font face="Tahoma" size = "2" color="#0B3861">Code:&nbsp&nbsp</font></td>
                    <td><input type = "text" id = "code" name = "code" size="35" value="<?php echo $code ?>"/></td>
                </tr>
                <tr>
                    <td><font face="Tahoma" size = "2" color="#0B3861">Link:&nbsp&nbsp</font></td>
                    <td><input type = "text" id = "link" name = "link" size="35" value="<?php echo $link ?>"/></td>
                </tr>
                <tr>                        
                    <td colspan=2 align="right">
                        <font face="Tahoma" size = "2" color="#0B3861">(e.g. http://www.google.com or index.php)</font>
                    </td>
                </tr>
                <tr>                        
                    <td colspan=2 align="right">
                        <input type="submit" name="submit" value="Save" style="height: 25px; width: 60px"/>
                        <button type="button" style="height: 25px; width: 60px" onclick="location.href='adminMain.php'">Cancel</button>
                    </td>
                </tr>               
            </table>
        </center>
    </form>
</body>
<?php
    if (!empty($_POST['uname']) && !empty($_POST['pwd']) && !empty($_POST['repwd']) && !empty($_POST['code']) && !empty($_POST['link']))
    {
        if ($_POST['pwd'] == $_POST['repwd'])
        {
            $myLink = mysql_connect('localhost','root', '1234') or die(mysql_error());
            $selectDB = mysql_select_db('proj2db', $myLink) or die(mysql_error());

            $sql = "UPDATE `proj2db`.`usertbl` SET pwd='".$_POST['pwd']."', sAns='".$_POST['code']."', path='".$_POST['link']."' WHERE uName='".$_POST['uname']."';";
            $exec = mysql_query($sql, $myLink);
        }
        else
            echo "<font face='Tahoma' size = '2' color='red'><center>Error: Password mismatched <br> Press cancel to return to home page </center></font>";
    }
?>

Upvotes: 1

Views: 4827

Answers (1)

S&#233;bastien Renauld
S&#233;bastien Renauld

Reputation: 19662

You seem to be confused as to the presence of PHP and JavaScript. Javascript is strictly client-side (barring node.JS), and PHP is strictly server-side. You can't inline-combine both of them the way you've done - or at least not in how you expect it to work. Right now, the PHP code will run regardless the moment the user has visited the page.

Here's a solution for you (it relies on jQuery, so you'll need a copy of it). I've also switched you to PDO to make your life a bit easier and show you how to transition away from mysql_query.

Keep your <body> code almost the same. The only difference is the mySearch() function, as follows:

<script type='text/javascript'>
function mySearch() {
   var uname = prompt("Search","Enter username");
   if (uname !== undefined && uname.length > 0) {
       $.ajax({
         url: "ajax.form.php",
         type: "POST",
         dataType: "json",
         data: { sentval: uname },
         success: function(d) {
            if (d.length > 0) {
               $("#uname").val(d[0].uName);
               $("#pwd").val(d[0].pwd);
               $("#code").val(d[0].sAns);
               $("#link").val(d[0].path);
            }
            else {
               alert("Not found");
            }
         }
       });
   }
}
</script>

To do this, you will also need another PHP script. I named it ajax.form.php. The content:

<?php
try {
   $DB = new PDO("mysql:host=localhost;dbname=proj2db","root","1234");
} catch (Exception $e) {
   die("Could not connect: ".$e->getMessage());
}
$DB->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

if (!empty($_POST['sentval'])) {
   $q = $DB->prepare("SELECT * FROM userTBL WHERE uName = :username");
   $q->bindValue(":username",$_POST['sentval']);
   $q->execute();
   if (($r = $q->fetch()) !== false) {
      echo json_encode(array($r));
   }
   else {
      echo "[]";
   }
} ?>

And that's it! It should work, though I have written this on-the-fly and have not tested it. The idea behind it:

  1. JavaScript calls the other PHP script with sentval through $.ajax()
  2. PHP runs
  3. PHP returns an array of rows (in this case, just one, but the script works just as well by changing fetch() to fetch_all() and removing the Array() in json_encode) to JavaScript
  4. JavaScript parses and updates the client's form.

Upvotes: 2

Related Questions