0

I would like to retrieve each element inside of this.responseText, and put them in my HTML on Javascript. Is there something wrong in my code? I hope my code helps you to understand my question. Thanks. (p.s. the html code is provided, and so I cannot use jquery.)

an example of this.responseText is below; (By using alert, I got that)

{"name":"Hermione Grainger","number":"4","review":"Not as good as the NEXT book in the series, but hilarious and satisfying."}{"name":"Ronald Drumpf","number":"1","review":"Feminist propaganda!"}{"name":"Brienne of Tarth","number":"5","review":"Alanna is my best friend."}

And my java script is below;

function bookReview(){
    var reviews = JSON.parse(this.responseText);
    for(var i=0; i<reviews.length; i++){
        var name = document.createElement("h3");
        var text = document.createElement("p");
        name.innerHTML = reviews[i].name + reviews[i].number;
        text.innerHTML = reviews[i].review;

        document.getElementById("reviews").appendChild(name);
        document.getElementById("reviews").appendChild(text);
    }
}

or is there something wrong in my PHP code??

$path = "books/$book/";
review(glob($path . "review" . "*" . ".txt"));

function review($reviews) {
    foreach ($reviews as $each) {
        $review = file($each, FILE_IGNORE_NEW_LINES);
        $output = array (
            "name" => $review[0],
            "number" => $review[1],
            "review" => $review[2]
            );
        header("Content-type: application/json");
        print(json_encode($output));
    }
}

2 Answers 2

1

This doesnt look like valid JSON, should be like '[{},{},{}]'. If you want you can use a JSON validator, e.g. http://json-validator.com/.

To generate the JSON array properly you can do:

$array = [];
foreach ($reviews as $each) {
    $review = file($each, FILE_IGNORE_NEW_LINES);
    $output = array (
        "name" => $review[0],
        "number" => $review[1],
        "review" => $review[2]
        );
    array_push($array,$review);
}
print(json_encode($array));
Sign up to request clarification or add additional context in comments.

5 Comments

I added my PHP code. Can you check my PHP code, please??
see 2nd answer here: stackoverflow.com/questions/6739871/… (generate the arrays in the loop, then outside of it put them in an array and json.encode this one).
I changed it to the code below, but it did not work well... function review($reviews) { foreach ($reviews as $each) { $review = file($each, FILE_IGNORE_NEW_LINES); $output = array ( array( "name" => $review[0], "number" => $review[1], "review" => $review[2] ) ); } header("Content-type: application/json"); print(json_encode($output)); }
Each $output = array (...); in the loop just generates one datastructure, you have to put them all in an array (see my edit). Also $output is only available in the block it is declared in (aka the inside of the for loop), or at least i guess php handles it this way.
Thank you so much! I can understand that!
0

Simple use this exemple for ajax:

AJAX:

 $.ajax({
        url: 'test.php',
        type: 'POST',
        datatype: 'Json',
        data: {'q': val_1},
        success: function (response) {
           var newhref;
           var newhrefid;
           var div=document.getElementById("myDropdown"); 
           for(var i = 0; i<response.nunber_of_rows; i++){
             newhref= document.createElement("a");
             newhref.href= response.tabel[i];
             newhref.innerHTML= response.tabel[i];
             newhrefid = "idhr_"+i;
             newhref.setAttribute('id', newhrefid );
             div.appendChild(newhref);
           } 
        }
    });

PHP:

...//your code
echo json_encode (array(
                    'tabel'=>$tabel,
                    'nunber_of_rows'=>$nunber_of_rows
));

In this example you define, that you are using Json with this line of code:

datatype = "Json";

In your php you send back the data through:

echo json_encode (array(
                    'tabel'=>$tabel,
                    'nunber_of_rows'=>$nunber_of_rows
));

To use the data in your ajax:

response.nunber_of_rows

The example it's from this link How to use Ajax and JSON for making dropdown menu?

If you do not want to use AJAX:

PHP:

$phpArray = array(
          0 => "Mon", 
          1 => "Tue", 
          2 => "Wed", 
          3 => "Thu",
          4 => "Fri", 
          5 => "Sat",
          6 => "Sun",

    )

JS:

    var jArray= <?php echo json_encode($phpArray ); ?>;

    for(var i=0;i<6;i++){
        alert(jArray[i]);
    }

To get the php array you need only to do this:

var jArray= <?php echo json_encode($phpArray ); ?>;

The example it's from this link Pass a PHP array to a JavaScript function

To use JSON.parse:

var data = JSON.parse( '<?php echo json_encode($data) ?>' );

Example:

PHP:

<?php
$books = array(
    array(
        "title" => "Professional JavaScript",
        "author" => "Nicholas C. Zakas"
    ),
    array(
        "title" => "JavaScript: The Definitive Guide",
        "author" => "David Flanagan"
    ),
    array(
        "title" => "High Performance JavaScript",
        "author" => "Nicholas C. Zakas"
    )
);
?>

JS:

<script type="text/javascript">
// using JSON.parse on the output of json_encode
var books = JSON.parse( '<?php echo json_encode($books); ?>' );

/* output (with some whitespace added for readability)
[
    {"title":"Professional JavaScript", "author":"Nicholas C. Zakas"},
    {"title":"JavaScript: The Definitive Guide", "author":"David Flanagan"},
    {"title":"High Performance JavaScript", "author":"Nicholas C. Zakas"}
]
*/

// how to access
console.log( books[1].author ); // David Flanagan
</script>

Now to get a value from your original array, you just have to use:

books[1].author

The example it's from this link http://www.dyn-web.com/tutorials/php-js/json/parse.php

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.