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
Thanks for your tip!
I also move lots of PHP data (HTML really) to JS by using in the :
<?php
echo ‘var myhtml=’.$HTML.’;';
?>
Further in JavaScript you can use the myhtml variable.
To be successful, be careful of quotes in $HTML (str_repl them with un backslash.
In the previous post, you have to add script tags to the echo’ed variable.
This was removed by the system, sorry.
Thank you, this was a big problem I was having and you’ve just solved it for me!
All my AJAX requests within Zend work great now.
Instead of using a hidden field, I simply declared it in my page head as a Javascript variable.
@Mr B, thanks. Yes, sometimes declaring a variable in Head tag works better if the variable is required to “exist” throughout the application.
//head…
//js tag…
jsVar = “< ?=$this->baseUrl ? >”;
//close js tag…
//close head
would also work…
it is working if we define
var baseUrl = baseUrl()?>
and this variable will be available in js file like
url: baseUrl+”/notes/deletenote”,
Thanks for this post.
By the way, how can i call this from a button created using zend form element?