Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get multiple return value from php by javaScript / jquery?

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?

like image 404
Kamruddin Bivob Avatar asked Feb 15 '26 06:02

Kamruddin Bivob


2 Answers

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;
like image 196
Rob M. Avatar answered Feb 16 '26 20:02

Rob M.


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.

like image 36
Zakaria Acharki Avatar answered Feb 16 '26 20:02

Zakaria Acharki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!