Search code examples
phpjquerysrc

Inserting php code into src of image in jquery


I have no idea how to do this. I want to insert php code into an image source through jquery.. but it is not working. Here is my code and help would be greatly appreciated!

JQUERY:

var mainId = $(this).attr('id');
$("#intabdiv img").attr('src', '<?=resize("../php/admin/portfolio/before/'+mainId+'",$settings)?>' );

HTML:

<div id="intabdiv">
<?php $settings = array('w'=>450,'h'=>450,'crop'=>true); ?>
              <img src="" border="0" class="pic" />
          </div>
</div>

Solution

  • It looks to me like you're trying to have the client browser execute PHP. That's not going to work for you. I'm not sure you have a completely clear idea of the separation between server and client, and what happens where.

    Here's a simple model that you can use to think about where things occur:

    1. User puts URL in browser and hits enter
    2. Browser sends request to server
    3. Server receives request and attempts to provide the resource requested
    4. At this stage, if the file is a PHP file, any PHP instructions are executed. The end result of this, after all PHP is finished and done, is an HTML file, perhaps with some javascript.
    5. The server sends this HTML file back to the browser.
    6. The browser loads the HTML file, and executes any javascript, which can manipulate the HTML on the client side.

    So, where does that leave us? You're attempting to take an image file that exists on the server, resize it, and display it to the end user. Presumably the "resize" function is one you have defined somewhere in your PHP code. I'll go on the assumption that you just need to do this once and have it show up for the user when the page loads.

    In this case, what you need to do is something more like the following (all in the same file):

    <?php
    $settings = array('w'=>450,'h'=>450,'crop'=>true);
    $imgsrc = resize("../php/admin/portfolio/before/imageid.jpg",$settings);
    ?>
    <div id="intabdiv">
        <img src="<?= $imgsrc; ?>" border="0" class="pic" />
    </div>
    

    ... no javascript required. Obviously, imageid.jpg must be the actual filename of the image you're trying to access. If, instead, you're trying to have some user action trigger the access to the image, please provide more context for what you're trying to accomplish and a better answer can be given.