2

This is my javaScript code :

$(document).ready(function() {
    $('#IMDB').click(function() {  
       var MovieID = $('#MovieID').val();

       $.post('action/action.php', { url: "http://api.themoviedb.org/3/movie/"+MovieID
+"?append_to_response=credits,images&api_key=myapikey" }, function(data) {
           $("#test").html(data);
       });
    });
});

When I click the button I get imdb id from my input field which I inserted then I get the actual result from php. this is my php code.

<?php 
    $url = $_POST['url'];
    $url2 = file_get_contents($url);
    $json = json_decode($url2, true); //This will convert it to an array
    $title = $json['original_title'];
    $imdb = $json['imdb_id'];

    echo $title;
    echo $imdb;

    return true;

?>

But I get result like this :

Batman: The Killing Jokett4853102

One is movie title and another is imdb id in same html tage. but I want to display my each result in each html tag like this :

$("#test").html(data); // result 1  -- movie title
$("#test2").html(data); // result 2 --- imdb id

Please help me how to get multiple value?

1
  • echo json_encode(array($title, $imdb)); then use the object returned. Commented Aug 3, 2016 at 16:57

2 Answers 2

7

It would probably be easiest just to output the entire JSON structure and work with that in Javascript, but if you just want the title and id, change your individual echo calls to one with a hash:

header('Content-Type: application/json');
echo json_encode(array(
  'title' => $title,
  'id' => $imdb
));

Then you can reference them in your javascript using:

var id = data.id;
var title = data.title;
Sign up to request clarification or add additional context in comments.

3 Comments

OP: This is the best answer. I recommend using this as a jumping-off point.
wow thanks a lot @Rob M . perfect answer thank you so much :) :)
No problem, glad it helped you!
2

You could simply return an array instead of separated values :

return json_encode([$title,$imdb]);

Then in your js parse the returned data and pluck the attributes you want from it :

data = JSON.parse(data);

$("#test").html(data[0]); 
$("#test2").html(data[1]);

Or you could add json to the $.post request the you don't have to parse the returned data :

$.post('action/action.php', { url: ...}, function(data) {
    $("#test").html(data[0]); 
    $("#test2").html(data[1]);
}, "json");
//__^^^^__

Hope this helps.

1 Comment

it returns only one word :( first letter of movie title

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.