Mixing PHP Variables with Javascript (Zend Framework and jQuery)
Filed Under (General) by Wenbert on 23-04-2008
Tagged Under : jquery, PHP, Web Development, Zend Framework
Sometimes, I “mix” PHP variables with Javascript. For example, I have something like this:
-
-
function deletenote(notes_id)
-
{
-
if(!confirm("Delete note? You will not be able to undo this action."))
-
return false;
-
-
$.post("< ?=$this->baseUrl?>/notes/deletenote",{
-
skeedl_notes_id: notes_id
-
}, function(data){
-
$(‘#notes_id’+data).fadeOut();
-
});
-
}
-
Note the $this->baseUrl, I need it like that. The thing is, I have that code in my view file (.phtml - in Zend Framework, this is parsed like a normal PHP file). If I remove all the Javascript in my view file and place it in a .js file, the $this->baseUrl will not be parsed. To go around this, I create a hidden input element in my view file with $this->baseUrl echoed as the value. Like this:
-
-
// … in my .phtml file …
-
// rest of the php and html code goes here
-
< input type="hidden" id="base_url" value="<?=$this->baseUrl?>" />
-
// rest of the php and html code goes here
-
Then in my .js file (assuming that you have already included this file in your header, or somewhere else), I have something like this:
-
-
//This is using jQuery, but you can use document.getElementById(’base_url’).value if you like
-
function deletenote(notes_id)
-
{
-
if(!confirm("Delete note? You will not be able to undo this action."))
-
return false;
-
-
$.post($(‘base_url’).val()+"/notes/deletenote",{
-
skeedl_notes_id: notes_id
-
}, function(data){
-
$(‘#notes_id’+data).fadeOut();
-
});
-
}
-
What it does is that jQuery gets the value of the hidden form element. The value of this hidden form element is from a PHP Variable.
So there you go, nothing special. Just something that works and I just wanted to share.
nice ething