faalbane
faalbane

Reputation: 105

Inserting a PHP variable in an HTML string being passed to JavaScript function via AJAX?

Is something like this:

$html .= "<table>"
$html .= "<tr onclick=\"test(" . $phpvar . ")\"><td>test</td></tr>";
$html .= "</table>"

$rVal=array("htmltable" => $html);
echo json_encode($rVal);

JS:

success: function(data){
    $("#content").html(data.htmltable);

possible?

Everything works when no PHP var is involved, but I'm asking if there's a way to pass a PHP var like this ...

Upvotes: 0

Views: 217

Answers (1)

Quentin
Quentin

Reputation: 943165

It's correct (functioning without error) ... the value of $phpvar is a string of a person's first and last name, and nickname

So given:

$phpvar = "John 'the Something' Smith";

The value of $html will be:

<table><tr onclick="test(John 'the Something' Smith)"><td>test</td></tr></table>

So John will be treated as a JavaScript variable name. Then you'll hit a syntax error.

You need to encode the data as a JavaScript string literal. json_encode will do that.

$phpvar = "John 'the Something' Smith";

$javascript_literal = json_encode($phpvar);

$html = "";
$html .= "<table>";
$html .= "<tr onclick=\"test(" . $javascript_literal . ")\"><td>test</td></tr>";
$html .= "</table>";

print $html;

… but that still won't work because it will give you:

<table><tr onclick="test("John 'the Something' Smith")"><td>test</td></tr></table>

… and the " will terminate the attribute value.

So you also need to encode it for HTML.

$phpvar = "John 'the Something' Smith";

$javascript_literal = json_encode($phpvar);

$html_attribute_value = htmlspecialchars($javascript_literal);

$html = "";
$html .= "<table>";
$html .= "<tr onclick=\"test(" . $html_attribute_value . ")\"><td>test</td></tr>";
$html .= "</table>";

print $html;

which will give you:

<table><tr onclick="test(&quot;John 'the Something' Smith&quot;)"><td>test</td></tr></table>

… which will work.


But that is horrible. And headache inducing. So don't do that.

  • Pass data back to the client instead of markup.
  • Use appropriate markup for the task. You want something to click on? Use a button. Not a table.

Such:

$rVal = array("plaindata" => $phpvar);
header("Content-Type: application/json");
echo json_encode($rVal);

and

success: function(data) {
    $("#content")
        .empty()
        .append(
            $("<button />")
                .text("test")
                .on("click", function() { test(data.plaindata); })
         );
}

Upvotes: 2

Related Questions