Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update two divs with one AJAX response

All, I'm using jQuery/AJAX to call a file to basically save it someone likes a song or not. I'm trying to do something like the following:

var html = $.ajax({
type: "POST",
url: "save_song.php",
data: "song_id=" + song_id + "&love_like_hate=hate",
async: false
}).responseText;

$("#div_song_id_"+song_id).html(responseText1);
$("#love_it").html(responseText2);

Then on the PHP side have something like this:

echo "This text would go in response text 1";
echo "This text would go in response text 2";

So basically I'm trying to have multiple echo's in the save_song.php file and then basically say the first echo goes to the first div and the second echo goes to the second div that needs updated. Any idea how to do this?

like image 646
user1048676 Avatar asked Jan 24 '12 14:01

user1048676


2 Answers

I would do this with json. If you echo out an associative array in your php and json encode it, jQuery will automatically convert the json string into an object.

Alternatively you could echo out the two statements with some kind of delimiter (like |&*etc...) and then split it with javascript, but I think this is a cleaner way to do it.

//php
echo json_encode(array(
    "responseText1" : "This text would go in response text 1",
    "responseText2" : "This text would go in response text 2"
))

//javascript
$.ajax({
    type: "POST",
    url: "save_song.php",
    dataType: "json",
    data: "song_id=" + song_id + "&love_like_hate=hate",
    success:function(val){
        $("#div_song_id_"+song_id).html(val.responseText1);
        $("#love_it").html(val.responseText2);

    }
});
like image 107
locrizak Avatar answered Sep 30 '22 20:09

locrizak


Your PHP code could give back a JSON string:

<?php
    echo json_encode(array(
        'test1' => 'This text would go in response text 1',
        'test2' => 'This text would go in response text 2'
    ));
?>

Then you can parse it in jQuery:

$.ajax({
    type: "POST",
    url: "save_song.php",
    data: "song_id=" + song_id + "&love_like_hate=hate",
    dataType: 'json',
    async: false,
    success: function(response) {
        if (response && response.text1 && response.text2) {
            $("#div_song_id_"+song_id).html(response.text1);
            $("#love_it").html(response.text2);
        }
    }
});
like image 27
entropid Avatar answered Sep 30 '22 20:09

entropid