Alex Tech Adventures The webs best tutorials!

AJAX requests with Zend Framework

E-mail Print PDF
(0 votes, average 0 out of 5)
AJAX requests in Zend Framework are no different than regular requests. You can call any controller/action from the background and it will give you an HTML response. However, you probably do not want the unnecessery code that layout and view scripts provide. You could, of course, create separate controllers and viewers specially for AJAX but that's repetitive code we obviously do not want. Manually switching off layout and view scripts on xmlHttp header detection is not pretty too. To the rescue comes action context switcher that detects the type of request sent and applies appropriate changes to te controller. Watch the video to see how to set it up.

But that is not enough. Once you got ZF to output the desired response, be it XML or JSON, you need to update your front end to accept that response and make sense out of it. In the video I show how you can grap JSON output with a response JavaScript function and put the variables in their right places on the page.


Key notes in the presentation:
  • Setting up action context switcher.
  • Creating links using ajaxLink view helper from ZendX_Jquery ...
  • ... that invoke the context switcher.
  • Review view script to make sure that only final variables are in the view.
  • Review view script's design for more comfortable jQuery manipulation.
  • Create a callback function in JavaScript that accepts JSON generated by context switcher and ...
  • ... applies variables from JSON to the appropriate sections of the page.

Mistake in frontend.js was noted by Yorian

In the video I have <div id="books"> in the loop JSON loop so each book entry becomes an accordion container on its own.  To fix that, need to take <div id="books"> outside of the loop.  I am also putting all HTML in a string and then appending it at the end becuase if you append <div id="books"> on its own, jQuery parses it as a complete HTML code and puts a self closing /> at the end so the rest of the code breaks.  I could, of course, append children but that too complex for this scenario:
1
2
3
4
5
6
7
8
9
10
11
function displayBooks(response){
	response = JSON.parse(response);
	$("#booksResponse").html('');
	var booksHtml = '<div id="books">';
	for(var i in response.books){
		booksHtml += '<h3><a href="#">'+response.books[i].title+'</a></h3><div>written by'+response.books[i].author+'</div>';
	}
	booksHtml += '</div>'
	$("#booksResponse").append(booksHtml);
	$("#booksResponse #books").accordion({"active":"none", "collapsible" : "true"});
}

 

Download soarce

Context Switcher
JSON
ZendX_JQuery ajaxLink

Last Updated ( Sunday, 25 October 2009 13:23 )  
Discuss (24 posts)
Re:AJAX requests with Zend Framework
Oct 25 2009 09:18:40
In the end you change div#books to #bookResponse and you append div#book inside #bookResponse in the loop. Doesn't that mean you have multiple div#books ? That would mean you have the same ID more than once, which isn't really correct...
#129
Re:AJAX requests with Zend Framework
Oct 25 2009 13:00:48
AAAAAA!!!
Can't believe I did that. Thank you for noting.
I will make an adjustment in the article and update the source.
#130
AJAX requests with Zend Framework
Oct 26 2009 11:22:28
I've being checking your site if you added new tutorial. This Ajax requests one looks very good except the sound quality (my office was really noisy ).
Actually, I really don't know much about JavaScript and Ajax.
After this tutorial, I got this tutorial will not work on IE6/7 and Firefox 3.0 or above unless if we include JavaScrip JSON parser script. If you have time please consider how we can include and use jQuery JSON parser. And you didn't mention how it would be on Google Chrome.

Actually, it is a little bit difficult to see the javascript code. Is there any simple and Zend-like way to use Ajax without duplicating many things you mentioned?
#137
Re:AJAX requests with Zend Framework
Oct 26 2009 12:28:59
For non JSON compatible browsers, just include json parser JS file, which is found on json.org/json2.js, in the head.

ZF doesnt provide much actual ajax functionalities. Zend_Dojo and ZendX_JQuery are there to asist with common front end tasks like controllers, forms etc. If you want to do anything advanced, like parse data or more complex user interaction, you still have to get down to JS development. Often, even the default Zend_Dojo and JQuery functions are not enough: they are either simplified versions or do not have certain parts altogether. Creating JavaScript functions for things like data parsing is something completly beyond zend.

I am not sure about chrome. Can't test it without windows atm. I cannot find any references on chrome and json. Can anyone confirm?
#139
AJAX requests with Zend Framework
Oct 27 2009 04:47:04
Thank you Alex.

I'm on Windows. I just extracted and tried to run the application after creating the db and tables, but it is not working on both firefox and chrome. Firefox shows only empty page and Chrome shows an empty page with 403 Forbidden, in the browser title.

I'm using wamp on my windows. All other projects are working properly with the following vhost record:

NameVirtualHost *:80


ServerName xet
DocumentRoot "G:/Profiles/BEREGU/Projects/Web Projects/Active Projects/xet/public"


Options Indexes FollowSymLinks MultiViews
AllowOverride all
Order Deny,Allow
Allow from all
#142
AJAX requests with Zend Framework
Oct 27 2009 04:51:16
Oh, it's being breaking. Please remove my previous post.

The record was:


NameVirtualHost *:80

''
ServerName unigas
DocumentRoot "G:/Profiles/BEREGU/Projects/Web Projects/Active Projects/unigas/public"

''
Options Indexes FollowSymLinks MultiViews
AllowOverride all
Order Deny,Allow
Allow from all
''
''
#144
AJAX requests with Zend Framework
Nov 18 2009 09:02:23
Hi again,
i found that on my local server, there is no need for this :
ajaxLink('test',.... ?> in list.phtml
i've done it like this :
ajaxLink('test',.... ?>
so i didn't close the previous tag and "echo" out inside of it.

In the manual (i think) they say that you can replace an "echo" by
Very usefull when you have single var to insert into html tags like so :
==
#185
AJAX requests with Zend Framework
Nov 18 2009 09:05:46
somethig went wrong in the previous post
nderstanding the previous post
#186
Re:AJAX requests with Zend Framework
Nov 18 2009 12:01:48
What is it suppose to look like?
#187
AJAX requests with Zend Framework
Nov 19 2009 09:40:32
Well it's opening tag's for php, but i gust that u now it allready,
opemin with php or equal....
Thx anyway for this serie of tutos, very helpfull. waiting for the next ones
#190
Re:AJAX requests with Zend Framework
Dec 23 2009 18:23:09
how i make ajax file? because I create new html "ajaxtest.html" in public file with code which is in tutorial, but it does not have same page source code, like you say in tutorial? understand what i mean? pls help.
#284
Re:AJAX requests with Zend Framework
Dec 23 2009 18:29:19
I think you are referring to javascript file? that would be under public in frontend.js

To be able to create ajax request you have to know JavaScript language. Look at some JavaScript and AJAX tutorials to see how its done.
#285
Re:AJAX requests with Zend Framework
Dec 27 2009 23:28:09
Hello Alex.

First of all thx for ur great tutorials. they are awsome and really helpfull.

I came across an error I can't figure out by myself on the 'AJAX requests with Zend Framework'.
Everything is fine considering the visual aspect, but when i clivk the 'test' link for the ajax call, most of the data's are set to null.
To be precised out of three books every value except 1 author is set to null and printed as null on the web page (that's 5 values out of 6!!!).
I do not have the error when i navigate using the pagination controls; just for the ajax call

Do you have any idea, what have i done wrong?
Any help would be appreciated.

Cheers
Seb
#288
Re:AJAX requests with Zend Framework
Dec 28 2009 12:08:28
Forgot to add - i build my source on following all the tutorials.
But i also tried downloading directly the source and not changing anything, and i had the exact same issue.

If u have any clue on where that might come from, i'll be glad u share it.

thx in advance
Seb
#289
Re:AJAX requests with Zend Framework
Jan 18 2010 22:45:00
Hey Alex,

First off.. I want to thank you a thousand times for your tutorials.. You have no idea how lost I would have been without them. You've really done a service for me and I am great full!

I was wondering if you could give me a hand though.. I'm updating a site where I've implemented you're AJAX paginator example to paginate through some news articles that I've got stored in a DB. Problem is, a lot of the articles are in very poor HTML (looks like whomever wrote the articles that I migrated from the previous site was using something like TinyMCE or the like) and so it looks like the JSON context switch isn't liking the data because it's outputting null values for some of the values. So I figured I'd try using XML instead of JSON since that way I can wrap the info in a CDATA wrapper and tranfer it that way. Problem is, when I set the contextSwitch format to xml, it appends ".xml.phtml' to the end of the request. Is there anyway that you know of to get your AJAX paginator example to work with XML?

Thanks a lot in advance
#342
Re:AJAX requests with Zend Framework
Jan 20 2010 15:34:48
@RavenHurstT
Indeed, thats how xml contextSwitcher works. You have to create a view file same way you would as if it was a regular html output, just with .xml.phtml extension. So I would call it list.xml.phtml as per my existing examples.
Move all the logic of creating the variables from controller into that xml.phtml file. Again, thats identical to how you would create any old HTML view file just make the final output from there look like xml this time.

Hope this helps.

@stkfdt
sorry I am yet to look over my code to answer your question
#354
Re:AJAX requests with Zend Framework
Jan 21 2010 19:27:06
Thanks Alex.. so you have to actually build the xml yourself? It doesn't just build the xml based on the view's stored variables like the json context switcher does?
#361
Re:AJAX requests with Zend Framework
Jan 21 2010 19:36:50
Thats right. XML view is no different from HTML view so unlike json it needs to be built manually with all tags, attributes and parameters.

controller:
$this->view->book_name = 'core php';
$this->view->book_type = 'chm';

book.xml.phtml:
<book>
<name><?= $this->book_name; ?></name>
<type><?=$this->book_type; ?></type>
</book

I think its a good thing to not let ZF create XML automatically just because there are unlimited number of ways you can organize data in xml file compared to one and only variable:data format in json.
#362
Re:AJAX requests with Zend Framework
Jan 24 2010 00:40:00
Hi Alex,

in your tutorial you was wondering about why you need the opening tag <?= before the call $this->ajaxLink... to make it work.
<?=
is a synonym for <?php echo

To insert an ajaxlink inside regular <?php and ?> tags it's not enough just to call $this.ajaxLink..., one have to call echo $this.ajaxlink... instead

with best regards
Jochen
#385
Re:AJAX requests with Zend Framework
Jan 24 2010 05:08:35
Thanks for the response.

However, I do know that <?= is same as <?php echo

What bothers me is why <?php echo $this->ajaxLink does not work but <?= $this->ajaxLink does if technically they are the same.
#387
Re:AJAX requests with Zend Framework
Jan 24 2010 18:56:43
Hi Alex,

that's funny, for me it don't work the other way around, though I know why, because shortcuts are not enabled on my apache. Due to that I'm even forced to use <?php echo $this->ajaxLink..., and it works for me fortunately.

Jochen
#389
Re:AJAX requests with Zend Framework
Jan 25 2010 17:50:20
Yeah... so we should probably just use the built in PHP XML construction methods in the .xml.phtml view?
#405
Re:AJAX requests with Zend Framework
Jan 25 2010 17:52:45
I've found that on some systems, the opposite doesn't work. (<?php echo works, whereas <?= ends up throwing a warning). I think it may have something to do with the php.ini settings on the server. But as to what setting that is, I have no idea..
#406
Re:AJAX requests with Zend Framework
Jan 25 2010 18:32:37
For complex xml structures I found PHP's DOM very useful and reliable.
#409

You need to login or register to post comments.
Discuss...
You are here: Home Development Zend Framework AJAX requests with Zend Framework

Statistics

Members : 571
Content : 36
Web Links : 1
Content View Hits : 40312

Who's Online

We have 38 guests online