1

Could someone please help me out.

How can i put this foreach statement in json_encode for example.

<?php foreach ($movies as $movie) { ?>

  <div>
    <h3><?php echo $movie['title']; ?><h3>
    <img src="/somewhere/<?php echo movie['image']; ?>" />
  </div>

<?php } ?>

So what i want to do is pass all movies from the foreach to json function So i can pass it to ajax

$.ajax({
  type: "GET",
  url: path+'/ajax/somefile.php',
  dataType: 'json',
  data: {page: requestTime},
  success: function(response) {
    var data = $.parseJSON(response.data);
    var $row = $('<div></div>', { 'class': 'row', style: 'display: none;' }).html(data.join(''));
    $row.appendTo('#movie-rating-grid').fadeIn();
  }
});

Could someone explain or show how to do this thanks

2
  • What you want to achieve? Provide more information. You show 2 parts of working code and so? Commented May 6, 2014 at 20:32
  • 2
    If you're just going to dump everything in a div, you don't really need json. Commented May 6, 2014 at 20:49

2 Answers 2

1

You might want to update your PHP to have only PHP instead of breaking out of PHP to have HTML.

somefile.php

foreach ($movies as $movie) { 
    $html = '
    <div>
        <h3>'.$movie['title'].'<h3>
        <img src="/somewhere/'.$movie['image'].'" alt="'.$movie['title'].'" />
    </div>
';
    $array[] = $html;
}
echo json_encode($array);

With this approach, you won't need to assign response to data.

movies.html

success: function(data) {
    var $row = $('<div></div>', { 'class': 'row', style: 'display: none;' }).html(data.join(''));
    $row.appendTo('#movie-rating-grid').fadeIn();
}

You could, also, adjust the PHP to give you output like $array[] = array('title' => $movie['title'], 'image' => $movie['image']); and then add the necessary HTML markup in your JavaScript success function.

Sign up to request clarification or add additional context in comments.

Comments

1

First, you need to encode your movies array as a json string.

$movies_json_string = json_encode($movies);

Then, you simply need to echo it.

echo $movies_json_string;

When ajax retrieves this view, it will interpret it as a json string and appropriately convert it to a json array.

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.