I have a javascript code which makes an Ajax request to a URL and on success (in the success callback) call a cakePHP element like so:
$.ajax({
type: 'POST',
url: "the_url_where_the_request_should_go",
success: function(data) {
"<?php echo $this->element('the_path_to_my_element'); ?>";
}
});
As you can see, because I am in javascript code, I have to put double quotes ("") around my PHP tags for this to work. The problem I'm having is that in the success function, when I call my element, the double quotes are sent along. Meaning, if the code in my element file is for example:
<div>element_code_here</div>
I get:
"<div>element_code_here</div>" (notice the double quotes gets included also)
Does anybody know why it's doing this and how can I fix this?
By the way, if I just remove the double quotes around my PHP tags, it just won't work (it gives me a javascript Invalid Identifier error message.
Thanks in advance
The success callback is still a javascript function so you need to treat the element you are echoing with PHP as a string. I'm not 100% sure what you are trying to accomplish and I would probably suggest returning the element (html) from your ajax endpoint instead of interpolating it directly into the script but using your example you should do something like this:
$.ajax({
type: 'POST',
url: "the_url_where_the_request_should_go",
success: function(data) {
var html_string = "<?php echo $this->element('the_path_to_my_element'); ?>";
//do something with the html string.. like insert it into a waiting div
$('div.container').html(html_string);
}
});
Wild guess. Try returning element from server with something like this:
//Function to call with $.ajax
function giveElement($elementName){
//logic to do with POST
//element to return
$this->render('/elements/'.$elementName);
}
//NOT TESTED. This might need something else too.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.