简体   繁体   中英

How to fetch data from MYSQL with AJAX from PHP

i want to call my array data from database using ajax. but i don't know the way. im confused in ajax call to show it into text field. how to get array data from my sql query

this the index.php looks like..

<body>
<div class="container" >
<h2>View data</h2>
<h4>Word List : </h4>

        <div class="form-group">
        <input id="wordlist" type="text" class="form-control" name="wordlist">
        </div><br>
        <button id="display" title="Generate Word">Generate</button>
        <div class="input-single">
        </div>

        <script type="text/javascript">
        $(document).ready(function() {
        $("#display").click(function() {
        $.ajax({    
            type: "POST",
            url: "getword.php",
            dataType: "json",
            cache: false,
            success: function(result){
              $('#wordlist').html(result[0]);
            }        
        }); 
  });
});

</script>
</body>

and then this is the url getword.php looks like

<?php
$host = "localhost";
$user = "root";
$password = ""; 
$dbname = "wordlist";

$con = mysqli_connect($host, $user, $password, $dbname);
if (!$con) {
 die("Connection failed: " . mysqli_connect_error());
}

$sql = "select kata from word"; 

 $res = mysqli_query($con,$sql); 
 $result = array(); 
 while($row = mysqli_fetch_array($res)){
    $result[]= $row[0];
 }
 echo json_encode(array('kata'=>$result));  
 mysqli_close($con);

?>

id="wordlist" is an input, what you passing back from the API is a object

{
 kata: [...]
}

So $('#wordlist').html(result[0]); wont work, your need to use $('#wordlist').val(result.kata[0]); (note: val not html) for first item, else it will join the values word1,word2,word3 etc

If your intention is not to place all words in a single input then you should change it so it loops over result.kata and creates an input for each word etc

I would like to suggest you to debug your code by yourself using following steps :

1.You can check what response you are getting from server side by printing your ajax response data at console to print this use below code.

 success: function(result){
   console.log(result); 
   // $('#wordlist').html(result[0]);
 }
This will print that you are receiving data from server side.
2.Another point is you are handling the response inside an input field if want to print fetch data inside input field then you have to replace $('#wordlist').html(result[0]); from $('#wordlist').val(result[0]); this line from your JavaScript code because it is an input field.

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