Update two divs with one AJAX answer

That's it, I use jQuery / AJAX to call the file to save it, someone likes the song or not. I am 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 there is something like this:

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

So basically I try to have a multiple echo in save_song.php, and then basically say that the first echo goes to the first div and the second echo goes to the second div, which needs updating. Any idea how to do this?

+4
source share
2 answers

Your PHP code can return 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); } } }); 
+2
source

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

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

 //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); } }); 
+4
source

Source: https://habr.com/ru/post/1392698/


All Articles