Kid Diamond
Kid Diamond

Reputation: 2301

How to retrieve and store data with Ajax

I want to return multiple data (variables) from PHP instead of just 1 piece of returned html code.

Right now I got this:

$.ajax({
    url: "test.php",
    cache: false
})
.done(function(html) {
    $('video').attr('src', html);
});

But I want to be able to do someting similar to this:

$.ajax({
    url: "test.php",
    cache: false
})
.done(function(data) {
    $('video').attr('src', data.videoUrl);
    $('video').attr('poster', data.posterUrl);
});

In my test.php I have this:

$posterUrl = "thumbnail.png";
$videoUrl = "video.mp4";

echo $posterUrl;
echo $videoUrl;

How can I accomplish something like that?

Upvotes: 0

Views: 84

Answers (3)

sheng
sheng

Reputation: 1372

The easiest way? JSON.

JavaScript:

$.ajax({
    url: "test.php",
    dataType: "JSONP"
}).done(function(json) {
    $("video").attr("src", json.videoURL).attr("poster", json.posterURL);
});

PHP:

$output = array();
$output["posterURL"] = "poster.png";
$output["videoURL"] = "video.mp4";

echo json_encode($output);

Upvotes: 3

A.M.N.Bandara
A.M.N.Bandara

Reputation: 1508

You may need to json_encode the response like this.

$response = array("videoUrl"=>"video.mp4","posterUrl"=>"video.mp4");

echo json_encode($response);

Upvotes: 1

Cyrus
Cyrus

Reputation: 131

You can return a JSON instead of a string.

More info here: http://api.jquery.com/jQuery.getJSON/

Upvotes: 0

Related Questions