0

i'm trying to update img cover without refresh the page using ajax and php but it does not work at all

HTML

  <div class="cover" >
  <img  id="b1"  src="<?php echo $user->picture_path();>"class="cover"/>          
                <div id="modal-cover" class="cov-lo">        </div>
   </div>

js

$('#b2').on({
    'click': function(){ 
     $('#b1').attr('src', <?php echo $user->picture_path();?> + '?' + new Date().getTime());}
});

the input and form

   <form  action="profile.php" method="POST" enctype="multipart/form-data"  > 
            <div class="hio"> 
                                        Upload                                   <input  type="file" onchange="this.form.submit()" name="cover" id="bla2"class="custom-file-input" /> 
 </div> 
             </form>

2 Answers2

2

Ajax would look more like this:

js/jQuery:

$(document).on({'click', '#b2', function(){ 
    $.ajax({
        type: 'post',
         url: 'my_ajax_processor_file.php',
        data: '',
        success: function(data){
            $('#b1').attr('src', data);
        }
    }); //END ajax

}); //END #b2.click

my_ajax_processor_file.php:

<?php 
    $dt = new Date().getTime();
    $pp = 'get user picture path here';
    echo $pp .' - '. $pp;

Note that you need to have an external PHP file, which I've called my_ajax_processor_file.php, that does some additional PHP processing and ECHOs back a value.

This value is received in the AJAX code block's success function, and called data (call it what you like - the name is set here: function(data).

Note that the contents of data variable are only available within that success function.


Here are some more basic examples of what AJAX looks like:

A simple example

More complicated example

Populate dropdown 2 based on selection in dropdown 1

Community
  • 1
  • 1
cssyphus
  • 37,875
  • 18
  • 96
  • 111
0

I think you have a fundamental misunderstanding of where the PHP and HTML are interpreted:

  1. PHP is a server-side scripting language designed for web development (see this Wikipedia article). That means that the PHP code is executed on the server before arriving in the browser.

  2. HTML is interpreted as plain text by the browser. No PHP is executed in the browser.

Therefore, once the JS gets to the browser, echo $user->picture_path(); has already been executed and is interpreted as plain text by the browser.

Your JS will look like this once it hits the browser:

$('#b2').on({
    'click': function() {
        $('#b1').attr('src', '/the/path/to/the/picture' + '?' + new Date().getTime());
    }
});
Sumner Evans
  • 8,951
  • 5
  • 30
  • 47
  • 1
    Even though you're right, I have a feeling this isn't the case here because of the `+ '?' + new Date().getTime()` at the end. I'm assuming that's some way to guarantee a new image. Then again, I could be wrong and that part is just pointless. – Mike Jan 05 '16 at 02:29