views:

49

answers:

2

Hi, I want to display an image as a response to an ajax call using php.. Does anybody have the complete code for this?? Please help me out.. Thanks in advance..

+1  A: 

Well I don't have the complete code to this, and if I did, I wouldn't give it to you.

You need to start off by creating an image using PHP's various image generation functions. To make it dynamic you could send it various parameters which are encoded in the url and can be fetched using the $_GET superglobal in php.

You would then set the src of an existing image placeholder element to the location of your dynamic image, then voila! Instant dynamic image.

Andrew Dunn
This place has too many questions that expect free lunch
Aditya Menon
If the asker has difficulties with any of the above, then they probably shouldn't be attempting whatever they are doing and try something simpler.
Andrew Dunn
A: 

You should use jQuery + JSON combination. You can convert php array into JSON format using json_encode.

index.php:

<script type="text/javascript" src="jquery-1.4.2.js"></script>
<script type="text/javascript" src="ajax.js"></script>

<a href='car.php' class='ajax'>Car Image</a>
<a href='bike.php' class='ajax'>Bike Image</a>

<div id="title">Title comes here</div>
<div id="image">Image comes here</div>

car.php:

<?php
$jsonArray['title'] = "Car";
$jsonArray['image'] = "<img src='images/car.jpeg'>";
echo json_encode($jsonArray);
?>

bike.php:

<?php
$jsonArray['title'] = "Bike";
$jsonArray['image'] = "<img src='images/bike.jpeg'>";
echo json_encode($jsonArray);
?>

ajax.js:

jQuery(document).ready(function(){

  jQuery('.ajax').click(function(event) {

      event.preventDefault();

      jQuery.getJSON(this.href, function(snippets) {
          for(var id in snippets) {
              jQuery('#' + id).html(snippets[id]);
          }
      });
  });

});
NAVEED