Question

I have a simple PHP script that uses ImageMagick to build a simple text based image. Instead of saving the image, I just need to show it on the screen for now.

So I have a PHP file that builds the image and prints it to the screen using this...

/* Create image */
$image->newImage($metrics['textWidth'], $metrics['textHeight'], $background);
$image->setImageFormat('png');
$image->drawImage($draw);

/* Show image */
header('Content-type: image/png');
echo $image;

To view the image and change how it looks I format a URL like this....

http://my-domain.com/magick-test.php?font=&fontsize=100&fontcolor=ffffff&bgcolor=000000

Now I need some help. I am creating a 2nd PHP file that will have an HTML Form trhat will allow me to change the variables for my image. I would like to submit the form and then have it display the image on the same page. I beleive I can do this using JavaScript and perhaps AJAX.

Could someone show me a basic example how to submit my form and have it show the image that is created on the same screen inside of a preview DIV? I can use jQuery too.

My HTML Form will be something like this...

<form action="magic-text.php">
Text: <input type="text" name="text" size="100"><br>
Font: <select name="font">
  <option value="angelica-webfont.ttf">Angelica</option>
  <option value="angelica-webfont.ttf">Angelica</option>
  <option value="angelica-webfont.ttf">Angelica</option>
</select><br>
Font Size: <select name="fontsize">
<option value="11">Font Size</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
</select><br>
Font Color <select name="fontcolor">
  <option value="#FF0000">Red</option>
  <option value="#FF5000">Orange</option>
  <option value="#FFF200">Yellow</option>
</select><br>
<input type="submit" class="btn" style="display: inline-block;">
</form>
Was it helpful?

Solution

Add a second html element

<img src="" id="myimg" />

then use jQuery and take the FORM element and make a ajaxSubmit on it...

$(function() {
    $("form").submit(function(ev) {
        $("#myimg").attr("src", "http://..." + $(this).serialize());
        ev.preventDefault();
        return false;
    });
});

OTHER TIPS

So you can do:

$(".btn").click(function(e){
     e.preventDefault();
     $("<img />").attr("src","http://my-domain.com/magick-test.php?"+$("form").serialize).appendTo("#target_element");
});

Where target element is where you want to show the image.

$(".btn").click(function(e){
   e.preventDefault(); 
   var request = $.ajax({ url : "http://my-domain.com/magick-test.php", type : 'POST', dataType : 'json', data : $('#myform').serializeArray() });

    request.done(function(json) { 
       if (json.status == 'ERROR') {
        return false; 
       } 
       $('#preview').innerHML = json.image; 
       return true;
    });
   request.fail(function() { 
      return false;
   }); 
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top