Mixing PHP Variables with Javascript (Zend Framework and jQuery)

Filed Under (General) by Wenbert on 23-04-2008

Tagged Under : , , ,

Sometimes, I “mix” PHP variables with Javascript. For example, I have something like this:

  1.  
  2. function deletenote(notes_id)
  3. {
  4.     if(!confirm("Delete note? You will not be able to undo this action."))
  5.         return false;
  6.        
  7.     $.post("< ?=$this->baseUrl?>/notes/deletenote",{
  8.         skeedl_notes_id: notes_id
  9.     }, function(data){
  10.         $(‘#notes_id’+data).fadeOut();
  11.     });
  12. }
  13.  

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:

  1.  
  2. // … in my .phtml file …
  3. // rest of the php and html code goes here
  4. < input type="hidden" id="base_url" value="<?=$this->baseUrl?>" />
  5. // rest of the php and html code goes here
  6.  

Then in my .js file (assuming that you have already included this file in your header, or somewhere else), I have something like this:

  1.  
  2. //This is using jQuery, but you can use document.getElementById(’base_url’).value if you like
  3. function deletenote(notes_id)
  4. {
  5.     if(!confirm("Delete note? You will not be able to undo this action."))
  6.         return false;
  7.        
  8.     $.post($(‘base_url’).val()+"/notes/deletenote",{
  9.         skeedl_notes_id: notes_id
  10.     }, function(data){
  11.         $(‘#notes_id’+data).fadeOut();
  12.     });
  13. }
  14.  

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.

Comments:

One Response to “Mixing PHP Variables with Javascript (Zend Framework and jQuery)”


  1. nice ething

Leave a Reply

Subscribe to Rss Feed : Rss