mercredi 6 mai 2015

How to display array of json data properly in html?

My Ajax

$("form").on("submit", function () {
    var data = {
        "action": "test"
    };

    data = $(this).serialize() + "&" + $.param(data);
    $.ajax({
        type: "POST",
        dataType: "json",
        url: "ajax2.php", //Relative or absolute path to response.php file
        data: data,
        success: function (data) {

            $("#main_content").slideUp("normal",function(){

            $(".the-return").html("<br />JSON: " + data);
//how to alter this part to display data for each record in one div?

            });
        }
    });
    return false;

});

My query

$statement = $pdo->prepare("SELECT * FROM posts WHERE subid IN (:key2) AND Poscode=:postcode2");
    $statement->execute(array(':key2' => $key2,':postcode2'=>$postcode));
 // $row = $statement->fetchAll(PDO::FETCH_ASSOC);
  $json = array();
 while( $row = $statement->fetch()) {
     array_push($json, array($row['Name'], $row['PostUUID']));
 }

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

The result displayed currently in this form:

JSON: jack,55421894ab602,test,55439324cc43d

But I want to display like:

 Name:jack,
 Id:55421894ab602
.....and some other info-

 Name:test
 Id:55439324cc43d
.....and some other info-

This part:

$(".the-return").html("<br />JSON: " + data);

I tried: data[0]; But when I do this, only the first record displayed obviously.

What I'm trying is :

data[0] itself is an array. How to display that array together with other records fetched in nice html?

edited: WIth these edited code, i can only retrieve the last result, it's not looping through the array.

ajax success: function (data) {

            $("#main_content").slideUp("normal",function(){

            //$(".the-return").html("<br />JSON: " + j_data);
            for (i = 0; i < data.length; i++) {
            $(".the-return").html("<div>Name:" + data[i].name + "<br/>Id:" + data[i].id);
        }
            console.log(data); // this shows nothing in console,I wonder why?
            //alert(j_data);
            });
        }

php

$json = array();
 while( $row = $statement->fetch()) {
     //array_push($json, array($row['Name'], $row['PostUUID']));
     array_push($json, array("name" => $row['Name'], "id" => $row['PostUUID']));
 }

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

Aucun commentaire:

Enregistrer un commentaire