androidnation
androidnation

Reputation: 636

Error when JSON array is echoed back to AJAX script

I have a text box where I search database for a specific information.

The PHP code when I just type and click on search is the following:

try
{
    $date_emp = $_POST['date_emp'];
    $val = $_POST['data1'];
    $gender = $_POST['gen'];


    if($date_emp == "choose" && $gender == "specify")
    {
        $search = "SELECT * FROM employee 
                    WHERE emp_name = :val OR position = :val 
                    OR salary = :val OR date_employed = :val 
                    OR gender = :val";
        $searchStmt = $conn->prepare($search);
        $searchStmt->bindValue(":val", $val);

        $searchStmt->execute();

        $res = $searchStmt->fetchAll();
        echo json_encode($res);
    }
catch(PDOException $ex)
{
    echo $ex->getMessage();
}

And here the AJAX script for it:

$("#search").click(function()
        {
            var txt = $("#txtSearch").val();
            var drop = $("#date_employed").val();
            var gender = $("#sex").val();
            //console.log(txt);
            if(txt == '' && drop == "choose" && gender == "specify")
            {
                $("#txtSearch").css('border-color', 'red');
            }
            else
            {
                if(drop == "choose" && gender == "specify")
                {
                    $.ajax
                    ({
                        url: 'search.php',
                        type: 'POST',
                        data: {data1: txt, date_emp: drop, gen: gender},
                        dataType: 'JSON',

                        success:function(res)
                        {
                            $("#myTable tr").remove();
                            $("#myTable").append("<tr><th>Name</th><th>Position</th><th>Salary</th><th>Date</th><th>Gender</th></tr>");
                            $.each( res, function(key, row){
                                $("#myTable").append("<tr><td>"+row['emp_name']+"</td><td>"+row['position']+"</td><td>"+row['salary']+"</td><td>"+row['date_employed']+"</td><td>"+row['gender']+"</td></tr>");
                            });
                        },
                        error:function(res)
                        {
                            alert("Something Wrong");
                        }
                    });
                }

                $("#date_employed, #sex").change(function()
                {
                    var txt = $("#txtSearch").val();
                    var drop = $("#date_employed").val();
                    var gender = $("#sex").val();

                    $.ajax({
                        url: 'search.php',
                        type: 'post',
                        data: {data1: txt, date_emp: drop, gen: gender},
                        datatype: 'json',

                        success:function(res)
                        {
                            $("#myTable tr").remove();
                            $("#myTable").append("<tr><th>Name</th><th>Position</th><th>Salary</th><th>Date</th><th>Gender</th></tr>");
                            $.each( res, function(key, row){
                                $("#myTable").append("<tr><td>"+row['emp_name']+"</td><td>"+row['position']+"</td><td>"+row['salary']+"</td><td>"+row['date_employed']+"</td><td>"+row['gender']+"</td></tr>");
                            });
                        },
                        error:function(res)
                        {
                            alert("Couldn't find any data!");
                        }
                    });
                });
            }
        });

WHERE gender and drop are 2 drop lists that forming a search filters

When I change one of the drop lists, per example, when I choose the date equal to: this week I should see in table 2 rows. But I can only see them in the network (in devTool), and at console tab I see the following error:

Uncaught TypeError: Cannot use 'in' operator to search for 'length' in [{"id":"48","0":"48","emp_name":"Alexa","1":"Alexa","position":"Secretary","2":"Secretary","salary":"8000","3":"8000","date_employed":"2016-02-23","4":"2016-02-23","gender":"female","5":"female"}]

The PHP code when I change drop lists is:

if($date_emp == "week" && $gender == "specify")
    {
        $search = "SELECT * FROM employee WHERE (emp_name = :val OR position = :val 
                    OR salary = :val OR date_employed = :val 
                    OR gender = :val) AND date_employed > DATE_SUB(NOW(), INTERVAL 1 WEEK)";
        $searchStmt = $conn->prepare($search);
        $searchStmt->bindValue(":val", $val);

        $searchStmt->execute();

        $res = $searchStmt->fetchAll();
        echo json_encode($res);
    }

Upvotes: 1

Views: 44

Answers (1)

zion ben yacov
zion ben yacov

Reputation: 725

When you make an ajax call and expect the response to be a json you need to send a json header from the PHP

header('Content-Type: application/json');
echo json_encode($data);

Sending the json header from the PHP will turn the "res" param in your ajax to a json object and not a json string. If you don't send the the header you need to parse the json string into a json object

var json = JSON.parse(res);

Upvotes: 2

Related Questions