Andrew Barker
Andrew Barker

Reputation: 41

How to test returned json result?

I have an Ajax Request that is getting data from my database, specifically two columns from it, company_id and people_id, I need to test the result that comes from the json result, I need to check if a specific people_id exists in the result,

Here is my Ajax Request

Ext.Ajax.request({
    url: 'system/index.php',
    method: 'POST',
    params: {
        class: 'CompanyPeople',
        method: 'secget',
        data: Ext.encode({
            people_id: Ext.getCmp('peopleGrid').selectedRecord.data.people_id
        })
    },
    success: function (response) {

    },
    failure: function () {

    }
});

I thought I could do this following code in the success function but it didnt work

if (data == 0) {
    Ext.MessageBox.alert('Status', 'Person is not attached to anything bud!.');
}
else {
    Ext.MessageBox.alert('Status', 'Person already attached to another company.');
}

Also here is my php

class CompanyPeople extends Connect {

    function __construct() {
        parent::__construct();
    }

    public function secget($vars) {
        $sql = "SELECT * FROM CompanyPeople where people_id={$vars->data->people_id}";

        $data = array();

        $total = 0;
        if ($result = $vars->db->query($sql)) {
            while ($row = $result->fetch_assoc()) {
                $data[] = array("people_id" => intval($row["people_id"]));
                $total++;
            }
            $result->free();
        }

        echo json_encode(array("success" => true, "total" => $total, "topics" => $data));
    }
}

Upvotes: 1

Views: 70

Answers (1)

Sergey Novikov
Sergey Novikov

Reputation: 4196

I think something like this should work:

success: function( response ){
    if(response.success === true) {
        var personExist = false;

        for(var i = 0; i < response.topics.lenght; ++i) {
            // Your specific people_id in myValue
            if(response.topics[i]['people_id'] === myValue) {
                personExist = true;
                break;
            }
        }
    }
},

Upvotes: 1

Related Questions