Brendan
Brendan

Reputation: 155

parse JSON object passed through Ajax

I'm trying to parse a information that gets returned from a DB and encoded into a JSON object.

this is the code that retrieves the information:

   private function retrieve_standards_one(){
    $dbh = $this->connect();
    $stmt = $dbh->prepare("SELECT code, standard_one_id 
                           FROM standard_one 
                           WHERE grade_id = :grade_id 
                           ORDER BY standard_one_id");
    $stnd = array();
    for($x = 0; $x < (count($this->grades)); $x++){                    
    $stmt->bindParam(':grade_id', $this->grades[$x], PDO::PARAM_STR);
    $stmt->execute();
    $stnd[] = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
    $json = json_encode($stnd);
    return $json;
}

and this id how I'm trying to parse the information:

  $.ajax({
        type: "POST",
        url: "lib/search/search.standards_one.php",
        async: "false",
        data: {subjects: subjects, grades: grades},
        success: function(response){
                $("#standards_results").html("");
                var obj = $.parseJSON(response);
                $.each(obj, function(){
                    alert(this['code'] + ", " + this['standard_one_id'])
                });
            }
        });

I've tried a number of different ways to do this, but I only ever get [object][object] as a response.

this is the response:

https://i.sstatic.net/l4R3V.png

Upvotes: 4

Views: 4474

Answers (2)

user1247091
user1247091

Reputation:

Add dataType attribute to your AJAX call.

$.ajax ({

    type: "POST",
    dataType: "JSON",
    url: "lib/search/search.standards_one.php",
    async: "false",
    data: {subjects: subjects, grades: grades},
    success: function(response){
            $("#standards_results").html("");
            var obj = $.parseJSON(response);
            $.each(obj, function(){
                alert(this['code'] + ", " + this['standard_one_id'])
            });
        }
    });

Upvotes: 0

Akhil Sekharan
Akhil Sekharan

Reputation: 12683

Use

console.log(this['code'] , this['standard_one_id'])

Instead of

alert(this['code'] + ", " + this['standard_one_id'])

Upvotes: 2

Related Questions