0

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?

1

2 Answers 2

1

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"); ?>
Sign up to request clarification or add additional context in comments.

6 Comments

The problem is the same. It returns an unescaped html
@VecchiaSpugna Why would you want to escape HTML when using the jQuery.html() function? That doesn't make any sense. If you want the data to appear as text, then use jQuery.text() instead. And when there's really need to escape HTML manually, then check out h().
because if the Jquery.html() argument is a text containing a crlf the javascript will break
@VecchiaSpugna What JavaScript? Please update your question with actual data, ie the markup of #target and the contents of the element.
@VecchiaSpugna Now I got you... ps in comments please use @username so that the one you are talking to gets notified, see stackoverflow.com/editing-help#comment-formatting
|
0

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.
}

3 Comments

Nice, but I can't use $this->Js : Undefined property View::$Js
May be you're not including the js helper. just check $helpers property in your controller & appcontroller and include it.
it works! I thought the JS and the Javascript helper were the same thing, but they're not.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.