简体   繁体   中英

how to retrieve data from database and display in textbox using php ajax and jquery?

can anyone tell me how to retrieve data from database and display it in text box in html by using php ajax and jquery? it will just only display if the button is click. Thanks for helping!

register.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>registion</title>
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
    <script>

        $(function () {
            $('#btn').click(function () {
              $.post(
                  'checkUserName.php',{
                      username:$('#username').val()
                  },function(data,textStatus){
                      $('#result').html(data);
                });
            });
        });

    </script>
</head>
<body>
    <h1>registion</h1>
    <form action="" method="post">
        userName:<input type="text" name="username" id="username">
        <input type="button" value="Verify userName" id="btn">
        <br>
        <span id="result"></span>


    </form>
</body>
</html>

checkUserName.php

<?php

$uname = $_POST['username'];

$conn = mysqli_connect('localhost','root','root','db_user');
$query = "SELECT * from tb_user where name = '$uname' ";
$result = mysqli_query($conn,$query);
$nums = mysqli_num_rows($result);

//echo $query;
//echo $nums;
if($nums > 0){
    echo "Username already exist";
}else{
    echo "Username OK";
}

mysqli_close($conn);

Next time please post together what have you done so far. From there only the community will be able to help you.

HTML Code :

<input type="text" id="input-box">
<button type="button" id="btn_get">Click</button>

Ajax Code :

$('#btn_get').on('click', function(){
 $.ajax({
   type    : "get",
   url     : '/path/to/php/file',       
   success : function(data)
   {
     $('#input-box').val(data);
   }
 });
});

PHP Code :

//get data from db here
$data = 'foo';
echo $data;

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