GePraxa GePraxa - 2 months ago 7
jQuery Question

include $variable in ajax success function

I am trying to return an image when Ajax is done, but i don't know how to include a session variable in the response, this is my code:

$(document).ready(function(){
$("#process").click(function(){

$.ajax({
type: 'POST',
url: 'process.php',
success: function (msg) {
$('#new-image').html('<img src="uploads/img/$_SESSION["sess_img"];" class="img-upload" alt="new image">')
}
});
});
});


Then, I want show the image
$_SESSION["sess_img"];
within the div
#new-image

Answer

You can echo that image filename in process.php like this:

<?php
// using time() as the cache buster, the image will never be cache by the browser
// to solve it, you need to add condition that will check if the image has change or not.
// or maybe you need to change the filename if it changes without adding a cache buster.
echo $_SESSION['sess_img_chofer']."?v=".time();

And in your javascript code:

$(document).ready(function(){
  $("#process").click(function(){

    $.ajax({
      type: 'POST',
      url: 'process.php',
      success: function (image) {
        $('#new-image').html($('<img>').attr('src', 'uploads/img/' + image).attr('class', 'img-upload'));
      }
    }); 
  });
});
Comments