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?
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);
}
});
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);
}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With