0

I'm encountering some odd behaviour when juggling a String from (generation in JavaScript) through (form submission in HTML form) to (echoing in PHP). Generation:

function constructCanvasString(){                   

    //<table> added later, when title and artist name is available.
    var canvasString = '';

    for (var y = 0; y < height; y++) {
        canvasString += "<tr>";
        for (var x = 0; x < width; x++) {
            canvasString += "<td x='" + x + "' y='" + y + "' style='background-color: " + $("#" + x + "-" + y).css('background-color') + "'></td>";
        }
        canvasString += "</tr>";
    }    
    canvasString += "</table>";
    console.log(canvasString);
    document.getElementById('canvasstring').value = canvasString;
}

The console.log(canvasString); returns code where the td's look like this:

<td x='23' y='4' style='background-color: rgb(0, 0, 255)'></td>
<td x='24' y='4' style='background-color: transparent'></td>

The string is given to a form field. The form looks like this:

<form id="publishform" method="POST" action="publish-canvas.php">
        <input type="text" name="title" value="Title"> by 
        <input type="text" name="artist" value="Artist">
        <input type='hidden' id="canvasstring" name='canvasstring' value=''>
        <input type="submit" id="publishbutton" value="Publish">
</form>

The form info is then passed to publish-canvas.php which holds this code:

<?php

$title = $_POST['title'];
$artist = $_POST['artist'];
$canvasstring = $_POST['canvasstring'];
$canvasstring = "<table id=\"" . $title . "_by_" . $artist . "\" title=\"" . $title . "_by_" . $artist . "\">" . $canvasstring;
echo $canvasstring;

?>

On that page, the td's look like this, messing up my careful formating:

 <td transparent\'="" style="\'background-color:" y="\'0\'" x="\'2\'"></td>
 <td 0)\'="" 255,="" rgb(255,="" style="\'background-color:" y="\'0\'" x="\'3\'"></td> 

Where is this happening, and how do I stop it?

user3195417
  • 329
  • 1
  • 2
  • 9

1 Answers1

0

I would say the problem occurs in the first step, when you are generating the html in javascript and putting it in an input box. You are putting real - unescaped - html in your input box and that will mess up the html of the page. The result you see is probably the browser trying to correct it.

You would need to generate escaped html in your javascript function and put that in your input box. So no < character, but a &lt;, no > but &gt;, etc.

You can change that directly in your javascript or you can use a function from an answer here on SO.

Community
  • 1
  • 1
jeroen
  • 91,079
  • 21
  • 114
  • 132