Jump to content

Recommended Posts

Ok so I have a file called balancer.php which contain the basic html code for a form.  In the same file I have php code that requests the info which it uses to generate an image based on the info from the form.  Everything works fine except that I can't seem to figure out how to get the image to display alongside the original form.  It always appears in a new blank page.  As of now I am unsure of what method to use to generate the image on the same page.

 

Here is the start of my form (the options are not relevant):

<form method="post" action="Balancer.php">
<input name="Craft" type="submit" id="Craft" />
</form>

Here is the output of the php:

// tell the browser that the content is an image
header('Content-type: image/png');
// output image to the browser
imagepng($image_f);

 

What do I need to change and add in order to have the image display next to the form (preferably without reloading the page)?

I'm a noob... small words...please... ;)

Link to comment
https://forums.phpfreaks.com/topic/258081-generating-image-on-the-same-page/
Share on other sites

Quick note: anytime the phrase "no refresh/reload" with dynamic content than your looking at javascript/ajax/jquery

you cant display an image from the html processing script, they have to remain seperate scripts (your html output script & your image script)

using js to detect a change on your form to update the image itself

So I have been messing around with code that I got here: http://www.w3schools.com/ajax/ajax_aspphp.asp

I am trying to change it up so it displays the image, here is the js file:

// JavaScript Document
function displaycard(str)
{
var xmlhttp;
if (str.length==0)
  {
  document.getElementById("bla").innerHTML="";
  return;
  }
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("bla").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","balancer.php"+str,true); //Confused what should go here
xmlhttp.send();
}

 

I still confused on parts of the code...

I have this button at the end of my form

  <button type="button" onclick="displaycard(this.value)">Craft</button>

 

I know there is a lot wrong with this.  I was wondering if I could get some help with it.

 

Any help at all would be amazing!! :)

 

Thanks for the link PFMaBiSmAd

 

I tried using some of the code from the link but I get the broken link symbol where the image should be (paper ripped in half).

Here is the java/html:

<head>
<script language="javascript" type="text/javascript">
function ajaxFunction(){  
    var xmlHttp;
      try{    // Firefox, Opera 8.0+, Safari    
        xmlHttp=new XMLHttpRequest();
    }
      catch (e){    // Internet Explorer    
        try{      
            xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e){      
            try{
                xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
            }
              catch (e){
                alert("Your browser does not support AJAX!");
                return false;
            }
        }
    }
    xmlHttp.onreadystatechange=function()
      {
      if(xmlHttp.readyState==4)
        {
            document.getElementById("response").innerHTML=xmlHttp.responseText;
            var img = document.createElement('img');
            img.onload = function (e) {
                document.getElementById("imgHolder").width=this.width;
                document.getElementById("imgHolder").height=this.height;
                document.getElementById("imgHolder").src=this.src;
            }
            img.onerror = function(e){
                alert("Error processing Image.  Please try again.")
            }
            img.src = xmlHttp.responseText;
        }
      }
      
    sendVars="tx="+document.forms["myForm"]["txtTxt"].value;
    sendVars+="&fon=ARIAL.TTF";
    sendVars+="&sz="+document.forms["myForm"]["txtSz"].value;
    sendVars+="&fg="+document.forms["myForm"]["txtFG"].value;;
    sendVars+="&bg="+document.forms["myForm"]["txtBG"].value;;

    xmlHttp.open("POST","Test.php",true);
    xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); //include this for post or it won't work!!!!
    xmlHttp.send(sendVars);  
}
</script>
</head>
<body>
<form name="myForm">
text: <input type="text" name="txtTxt" /><br/>
size: <input type="text" name="txtSz" /><br/>
fg: <input type="text" name="txtFG" /><br/>
bg: <input type="text" name="txtBG" /><br/>
</form>
<img src="" id="imgHolder"/>
<a href="javascript:ajaxFunction()">Send!</a>
</body>
</html>

Here is the php:

<?php
$id= ("imgHolder");
$tx=$_POST["tx"];
$fon=$_POST["fon"];
$sz=$_POST["sz"];
$fg=$_POST["fg"];
$bg=$_POST["bg"];
$pad=0;

$imX=imagettfbbox($sz,0,$fon,$tx); //get bounding box for dimensions
$imDim=imgSize($imX, 0); //run a function to get image size

$im=imagecreate($imDim["w"], $imDim["h"]); //create new image

$bgCol=hex2rgb($bg); //convert bg color from hex to rgb
$bgColor=imagecolorallocate($im,$bgCol['r'],$bgCol['g'],$bgCol['b']); //allocate bg color

$fgCol=hex2rgb($fg); //convert fg color from hex to rgb
$fgColor=imagecolorallocate($im,$fgCol['r'],$fgCol['g'],$fgCol['b']); //allocate fg color

imagettftext ($im, $sz, 0,0, imagesy($im)-$imDim["bl"], $fgColor, $fon, $tx); //print the text

imagejpeg($im,$id.".jpg", 100); //create and save the image
echo $id.".jpg"; //Return Id of pic to javascript

//===============================================================================
function imgSize($bb, $pad){
    //a function to interpret the bounding box info here.

    $imgDim=array("w"=>$w,"h"=>$h,"bl"=>$blOff);
    return($imgDim);
}
function hex2rgb($hex) {
        return array( 'r' => hexdec(substr($hex, 0, 2)), // 1st pair of digits
                      'g' => hexdec(substr($hex, 2, 2)), // 2nd pair
                      'b' => hexdec(substr($hex, 4, 2))  // 3rd pair
                    );
    }


?>

 

What am I doing wrong!?!?  :confused: :confused: :confused:

I also tried the second method and got this message:

Warning: imagepng() [function.imagepng]: Unable to open 'img/sdfsa+MJoa.png' for writing: No such file or directory in /Library/WebServer/Documents/temp/test2.php on line 70

 

Here is the html file:

<html>
<head>
<title>Ajax with jQuery Example</title>
<script type="text/JavaScript" src="jquery.js"></script>
<script type="text/JavaScript">



$(document).ready(function(){

$("#generate").click(function() { loadImage(); });

function loadImage(){

    var inputString = $("#inputString").val();

    var inputFont = $("#inputFont option:selected").val();

        $("#image p").load("test2.php?text=" + inputString + "&font=" + inputFont)

}
});

</script>
<style type="text/css">
   #wrapper {
     margin-top: 30px;
     height: 50px;
     width: 600px;
     border: 1px solid black;
     text-align: center;
   }
   #image {
       padding-bottom: 80px;
       border-style: none;
       height: 100px;
       width: 600px;
       text-align: center;
   }
</style>
</head>
<body>
   <center><div id="image"><p> </p></div>
     <div id="wrapper">
    Engraved Text:<input size="30" id="inputString" type="text" />
    Font:<select id="inputFont">
  <option value="balmo">Balmoral</option>
  <option value="clar">Clarendon</option>
  <option value="curlz">Curlz</option>
  <option value="english">Old English</option>
  <option value="freehand">Freehand</option>
  <option value="greek">Greek</option>
  <option value="interlock">Interlocking Monogram</option>
  <option value="MJoa">Times</option>

<!--   
<option value="3">Cool Engraving</option>
<option value="3">Cool Engraving</option>
<option value="3">Cool Engraving</option>
<option value="3">Cool Engraving</option>
<option value="3">Cool Engraving</option>
-->
    </select>
    <input type="submit" id="generate" value="Generate!">
</div>
</center>
</body>
</html>

 

Here is the php:

<?php

// VARIABLES   ############################################################################

// The text to draw
$text = $_GET['text'];
//$text = 'poopie';

// Font File, don't need a slash if file is in same dir as php file
$font = $_GET['font'];
//$font = '1';

//size in PTS
$size = 78;

//Angle
$angle = 0;

//Width of Canvas
$width = 500;

//Height of Canvas
$height = 200;

//Text Bounding Box Dimensions
$tb = imagettfbbox($size, $angle, $font, $text);

/*
Output of imagettfbbox is an array as follows:

Array
(
    [0] => 0 // lower left X coordinate
    [1] => -1 // lower left Y coordinate
    [2] => 198 // lower right X coordinate
    [3] => -1 // lower right Y coordinate
    [4] => 198 // upper right X coordinate
    [5] => -20 // upper right Y coordinate
    [6] => 0 // upper left X coordinate
    [7] => -20 // upper left Y coordinate
)
*/

// Centering Function  #####################################################################

// X Position Calculated by subtracting width of Text Bounding Box from total canvas width
$posx = ceil(($width - $tb[2]) / 2);

// Y Position Calculated by subtracting height of Text Bounding Box from total canvas height
$posy = ceil(($height - $tb[5]) / 2);

// Creating Image File
$im = imagecreatetruecolor($width, $height);

// State Colors available to Image File
$white = imagecolorallocate($im, 255, 255, 255);
$grey = imagecolorallocate($im, 128, 128, 128);
$black = imagecolorallocate($im, 0, 0, 0);

imagefilledrectangle($im, 0, $angle, $width, $height, $white);

// Add the text
imagettftext($im, $size, $angle, $posx, $posy, $black, $font, $text);

// Usage of imagettftext()
// array imagettftext  ( resource $image  , float $size  , float $angle  , int $x  , int $y  , int $color  , string $fontfile  , string $text  ) //

$file= "$text+$font.png";

imagepng($im, "img/$file");
imagedestroy($im);

$imgloc= "img/$file";

echo "<img src=$imgloc>";

?>

 

I changed one of the fonts to use my font and I installed jquery.

What is wrong here???

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.