Search code examples
javascriptphpmysqlajaxfetch

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);

?>

Solution

  • 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