Question

I need to make a DOM substitution, something like this:

$("#target").html('<?php echo $html?>');

where the $html variable could be a complex markup

$html = '<div>
    <input type="text" name="test" />
  </div>';

Of course I need some kind of escaping, or the javascript engine will break for a syntax problem at the first crlf or quote. In rails there's a simple function escape_javascript that makes it very easy. Is there anything similar in cakephp?

Was it helpful?

Solution 2

you can do this by using requestAction

in your view file add the below code

$html = $this->requestAction('/tests/func_name');

echo $this->Html->scriptBlock('
    $("#target").html('. $this->Js->value($html) .');
');

And in your TestsController.

public function func_name() {
    $this->layout = 'layout_name'; // The layout you want here for design.

    $this->render('/Elements/element_name'); // you can directly render the content of element by writing like this.
}

OTHER TIPS

I think using

$("#target").html('<?php echo $this->element("element_path"); ?>');

makes more sense. But it depends on what is in your element_path.ctp file. On the other hand, it's a bit weird to put replacement HTML in like this. Espacially if it's a lott, I would make an ajax call to load the HTML and have a Controller function return the contents of the element.

$("#target").html('Loading...').load('/myController/loadHtml/');

and the myController

function loadHtml(){
    $this->layout = false;
}

and the view for the function app/View/my/load_html.ctp:

<?php echo $this->element("element_path"); ?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top