Thursday, May 5, 2011

PHP Form code mangled

I am generating a simple form with php. The following code has been reduced to showcase the problem.

<?php
$blah = "<h1>Well</h1>"; $test = "<h2>Done</h2>";
echo '<script type="text/javascript" src="fetchlayers.js"></script>';
$formcode = "<form action=\"process.php\" method=\"post\" enctype=\"multipart/form-data \">"
          . "<label for=\"file\">Filename:</label>"
          . "<input type=\"file\" name=\"file\" id=\"file\"/> <br />"
          . "<input type=\"submit\" name=\"submit\" value=\"Submit\" "
          .    "onclick=\"setTimeout(function() { sendInfo(\"$blah\", \"$test\"); },1250);\" />"
          . "</form>";

echo "<h1>hello</h1>
<div id='form'>
$formcode
</div>";

This results in this html code

<h1>hello</h1>
<div id="form">
<form action="process.php" method="post" enctype="multipart/form-data ">
<label for="file">Filename:</label><input name="file" id="file" type="file">
<br><input name="submit" value="Submit" onclick="setTimeout(function() { sendInfo(" type="submit"><h1>Well</h1>", "<h2>Done</h2>"); },1250);" /&gt;
</form>

Somehow the form code for type=submit is ending up after my call to sendinfo(). Why?

From stackoverflow
  • It's because of your quotes in the onclick. Use single quotes instead:

    "onclick=\"setTimeout(function() { sendInfo('$blah', '$test'); }, 1250);\" "
    

    The way it is now, your onclick attribute actually reads like this:

    onclick="setTimeout(function() { sendInfo("
    
  • It appears to be an escaping issues:

    <?php
    $blah = "<h1>Well</h1>"; $test = "<h2>Done</h2>";
    echo '<script type="text/javascript" src="fetchlayers.js"></script>';
    $formcode = "<form action=\"process.php\" method=\"post\" enctype=\"multipart/form-data \"><label for=\"file\">Filename:</label><input type=\"file\" name=\"file\" id=\"file\"/> <br /><input type=\"submit\" name=\"submit\" value=\"Submit\" onclick=\"setTimeout(function() { sendInfo('$blah', '$test'); },1250);\" /></form>";
    
    echo "<h1>hello</h1>
    <div id='form'>
    ". $formcode . "
    </div>";
    

    The javascript in onclick needs single quotes or it has to use &quot;.

    fiXedd : There's a typo where the first single-quote is supposed to be: sendInfo(;$blah', '$test');

0 comments:

Post a Comment