javascriptphphtmljsonxmlhttprequest

Output PHP already encode to json, and send to javascript to be json, not working


I'm do output with json_encode to send to javascript, with this code.

<?php

    include "Connection.php";

    $syntax_query = "select * from product";

    $thisExecuter = mysqli_query($conn, $syntax_query);

    $result = array();

    while($row = mysqli_fetch_assoc($thisExecuter)){
        
        array_push(
            $result,
            array(
                "id"       => $row["product_id"],
                "name"        => $row["product_name"]
            )
        );
    }

    echo json_encode($result);

    ?>

So output show like this:

[
    { "id": "121353568", "name": "Baju Casual - Black" }, 
    { "id": "556903232", "name": "Tas LV - Red" },
    { "id": "795953280", "name": "Sword - Wood" },
    { "id": "834032960", "name": "Scooter - Iron Plate" }
]

And code in Javascript is like this:

function showHint() {
    const xmlhttp = new XMLHttpRequest();
    xmlhttp.onload = function() {
        var obj = this.responseText;
        
        document.getElementById("txtHint").innerHTML = obj.id;
    }
  xmlhttp.open("GET", "Download.php");
  xmlhttp.send();
}

obj.id is not working, output shows "undefined".


Solution

  • I use ajax calls when I want to call a Php file and get a response from the same as below to try once that as I have shown. Before moving with Ajax you must need jquery to be imported into the calling file.


    If Jquery is imported then ignore the steps


    Here are steps,

    1. Go to the link https://code.jquery.com/jquery-3.6.0.min.js copy whole content (use ctl+A to select whole content and ctl+C to copy)
    2. Open a new file in the current project folder and paste the copied content (use ctl+V to paste) save it as 'jquery-3.6.0.min.js'
    3. Import the js file in the HTML file in script tag as shown '

    Now, this is the ajax example to call the PHP file and to get a response

    function showHint() {
    //since you have used GET method I have used here GET but You can use POST also here 
     $.ajax({
        url: 'Download.php',
        type: 'get',
    //if any value you want to pass then uncomment below line
    //    data: {'name_to_pass':'value'}, 
    //the variable can be accessed in the php file by 'name to pass' under $_GET['name_to_pass'] or $_POST['name_to_pass'] based on type
        success: function(res)
        {
          //  open DevTool console to see results
          console.log(JSON.parse(res));
        }
        });
    }
    Hope this will help you out, thank you