0

Edit: I can output the table now but the strange thing is, trying to parse the JSON returned from PHP using JS or jQuery methods results in skipping all remaining lines in the debugger with zero output to the browser. Where as not parsing and using it to construct at table works. Also, trying to .append() the JSON using the parse methods or not to a ` does not work.
I'm so confused right now.

Anyways, the jQuery that worked looks like this making a .post() request, notice I added the 'json' fourth parameter although it might work without it.

$(document).ready(function(){
    $('#disease_btn').click(function(){
        showDisease();
    });
});

function showDisease(){
    //var disease = $("#disease-dropdown:selected").text();
    //var disease = $("#disease-dropdown:selected").val();
    var disease_dropdown = document.getElementById("disease-dropdown")
    var disease = disease_dropdown.options[disease_dropdown.selectedIndex].text;
    var controller = 'controller.php';
    $.post(controller, //url, data, callback, dataype=Json
    {
    page: 'SpaPage',
    command: 'search-disease',
    search_term: disease
    },
    function(disease_json, status){
        //#search-results display table
        //var disease_obj = JSON.parse(disease_json); this did not work
        //var disease_obj = jQuery.parseJSON(disease_json);  //this did not work
        var disease_obj = disease_json;
        //$('#test-out').append(disease_obj);  /this did not work
        var table = $.makeTable(disease_obj);
        $('#search-results').append(table);  //this worked!
    }, 'json');

    //https://stackoverflow.com/a/27814032/13865853
    $.makeTable = function(disease_obj){
        var table = $('<table border=1>');
        var tblHeader = "<tr>";
        for (var h in disease_obj[0]) tblHeader += "<th>" + h + "</th>";
        $(tblHeader).appendTo(table);
        $.each(disease_obj, function(index, value){
        var tblRows = "<tr>";
        $.each(value, function (key, val){
        tblRows += "<td>" + val + "</td>";
        });
        tblRows += "</tr>";
        $(table).append(tblRows);
    });
    return ($(table));
    }
};

That table code I mimicked what I saw here: https://stackoverflow.com/a/27814032/13865853 I sort of get it but still not crystal clear on all of it. I guess it's outputting HTML so I can throw in a class for the table to take advantage of bootstrap.

On the PHP side I do this:

case 'search-disease':
            $matches_arr = [];
            $disease = $_POST['search_term'];
            $matches_arr = search_disease($disease);
            //todo: decide to use session or returned arr
            if(isset($_SESSION['disease-matches_arr'])){
                $matches_arr = $_SESSION['disease-matches_arr'];
            }
            if(count($matches_arr) > 0) {
                //jsonify array here to send back
                //https://stackoverflow.com/a/7064478/13865853
                //https://stackoverflow.com/a/58133952/13865853

                header('Content-Type: application/json');
                $disease_json = json_encode($matches_arr);
                echo $disease_json;
                exit;
            }

and then the model.php interaction with database looks like this:

function search_disease($disease_option){
    // search DB for substring of question
    //add results to an array of strings
    //return array of strings or empty array
    //
    $user_id = -1;
    $matches_arr = array();
    $sql = "SELECT * FROM diseases 
    WHERE disease LIKE '%$disease_option%'";

    $result = mysqli_query(Db::$conn, $sql);
    if (mysqli_num_rows($result) > 0) {
        //iterate
        while($row = mysqli_fetch_assoc($result)){
            //get username
            $disease = $row['disease'];
            $food = $row['food'];
            $en_name = $row['en_name'];
            $health_effect = $row['healthEffect'];
            $metabollite = $row['metabollite'];
            $citation = $row['citation'];
            $next_row = array("Disease"=>$disease, "Food"=>$food,
                "Name"=>$en_name, "Health Benefits"=>$health_effect, "Metabollite"=>$metabollite,
                "Sources"=>$citation);
            $matches_arr[] = $next_row;
        }
    }
    $_SESSION['disease-matches_arr'] = $matches_arr;
    return $matches_arr;
    //https://stackoverflow.com/questions/1548159/php-how-to-sen

So I set a session variable and also return it, still have to decide which way but they are both working.

My questions still remaining are:

  1. Why do the parse methods cause this strange behavior?
  2. How can I just output the JSON to a testing <div>?
mLstudent33
  • 1,033
  • 3
  • 14
  • 32
  • Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackoverflow.com/rooms/224365/discussion-on-question-by-webnoob13-php-how-to-return-json-for-jquery-get-or). – Samuel Liew Nov 10 '20 at 13:55

1 Answers1

-1

If you have to return data from PHP to javascript you must have use json_encode() if data type is array otherwise just return. To take action with array type data by javascript you have to decode this json data by JSON.parse() function.

Array example

 $data = array('carname' => 'TOYOTA','model'=>'ARTYIR500');
 echo json_encode($data);
 exit;

String example

 echo 'lorem ipsum is a simple text';
 exit;
  • 1
    `if data type is array` would be more accurate if it said something like `if data type is an array or object (not a simple type such as string, int or bool)`. Objects need encoding too, not just arrays. – ADyson Nov 09 '20 at 10:38
  • 1
    `To take action with array type data by javascript you have to decode this json data by JSON.parse() function`...not necessarily. jQuery's ajax functions, for example, can be told to parse automatically by setting the `dataType: "json"` option. If using `fetch()` you would do it using `response.json()`. There are several different ways, so your statement is too simplistic. – ADyson Nov 09 '20 at 10:39