Hossam Elddin Magdy
Hossam Elddin Magdy

Reputation: 3

Update img with jquery and php

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>

Upvotes: 0

Views: 72

Answers (2)

cssyphus
cssyphus

Reputation: 40038

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

Upvotes: 2

Sumner Evans
Sumner Evans

Reputation: 9157

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());
    }
});

Upvotes: 0

Related Questions