Ajax

Ajax Archives

Yii Framework

Avoiding duplicate script download when using CActiveForm on Ajax calls

0

Yii Framework

Introduction

Sometimes the active form we wish to use to edit/add a new element on our database is too small and we believe that is much better to use an AJAX’ed dialog/slide form rather than reloading the page to just display one or two fields.

The only thing required is simple, we just need to create a view that will be partially rendered by a call to a controller (using renderPartial) and make sure that we process output -setting to true the parameter on the function. Everything will work as expected but…

The issue

If we open firebug (firefox), or developer tools (chrome), or whatever the tool you use in order to see the XmlHttpRequest object calls and resources downloaded, you will see that every time we do call the controller to display the active form, different Yii “core JS” files keeps being downloaded to the client. The JS files downloaded depends on your code but there are at least jquery.js, jquery-ui.js and jquery.yiiactiveform.js.

The solution

The solution is a bit tricky but simple. We need to pre-render the jquery.yiiactiveform.js on the view where we are going to place the AJAX functionality (the button that opens the modal dialog or slides/shows a layer with AJAX’ed form contents). For example, on index.php view file:

cs()->registerCoreScript('yiiactiveform');

Now, I assume that you have created your function to display the AJAX’ed active form and its contents are returned by a call to a controller’s action that will partially render a view. This is what we have to do in our action:

// Just before rendering the view that
// has our activeform
Yii::app()->clientScript->corePackages = array();

It is very important that we set corePackages to array() instead of null, as setting it to null will make CClientScript to reload the packages.php file (located in framework/web/js/) and we won’t stop the duplication of the script.

And that’s it, everything is working as it should.



Tweet this!Tweet this!
Picture-121-300x157

jQuery Livebuttons Plugin

4

Introduction

I normally develop CMS (control management systems) based on a heavy use of AJAX, and I normally endup writing tones of jQuery functions for different IDs and/or CLASSes. Thinking to create a library that will free me to create the same functions again and again and for different classes I thought about this simple plugin. The reason was that if I was to create a new CMS for my beloved Yii framework, I just wanted to have a system where, by setting some meta data into the HTML elements, the client script will smartly know what to do. I didn’t want to necessary worry about different classes on  my client scripts, I wanted to be just one class.

The idea behind goes a bit further and has something to do with Yii, I want to create extensions that will take care of the correct rendering of a button without having to worry about the client scripts **and** also the same extension could actually call jquery commands easily. I emphasized **and** because Yii already provides an ajaxLink and an ajaxButton but they are not listened to perform client jquery executions and that, as seen in its forums, is causing problems to PHP programmers a lot of times.

Also, I envision an environment where through this, Yii extension designers will be able to create CMS styles, completely different that the one coming from Yii, so Yii users could easily integrate a new layout without even tweaking CSS, or Themes, or Layouts, just their views and by integrating some specialized widgets API, user will be able to program a gallery (for example) with just one line of code on their views. Enough talking, here is the plugin for you to test it and tell me what do you think.

How to use

Include jquery and jquery.livebuttons.js on your document’s head and start monitoring for livebuttons like this:

//
// .selector is the class name the HTML elements have
$('.selector').livebuttons();
$('.selector').livebuttons( options );
//
// we can have more than one
$('.otherselector').livebuttons( otheroptions );

Options

useFirebug

A useful property for debuggin processes. If set to true all logs will be displayed on firebug console (or chrome).

var options = {
    useFirebug: true
}
$('.selector').livebuttons( options );

events

An array of options where to specify the events to monitor. In future releases, we will be able to specify which methods correspond for certain events.

var options = {
    events: ['click','mouseover'] // not a good practice though *yet*
}
$('.selector').livebuttons( options );

methods

This is the most interesting part of the plugin. We could implement our own javascript methods to be used with livebuttons. All methods will receive a ‘command’ parameter, which is actually the object in the meta-data of the HTML element (see below on the examples provided for default methods).

var options = {
    methods: {
        alert: function( command ) {
              alert( command.message );
        }
   }
}
$('.selector').livebuttons( options );

When designing our own javascript functions to be attached to the plugin, we can access internal parser functions with this keyboard. All functions receive a command object and also a reference to the options object. This object have a reference to the parser it self and we could easily access parser’s functions by using this.parser.

The Parser

If you look at the code inside the plugin, you will see that the parser has a couple of good methods to use:

stringify

Converts an object to its JSON representation string

createIFrame

Creates an iframe to be used with FORMs with multipart/form-data. So you can easily send files to the server without the need of reloading the page. Check at its code to see its

removeIFrame

Removes the iFrame previously created with parser.createIFrame() method.

parseJSON

Parses a JSON string and converts it into an object. I know jQuery comes with one, but it throws an error when you include a function into a command object’s property.

Default Methods

You have a couple of methods that already come with the plugin. You can easily override them if required. Here they are:

ajax

Its name is self-explanatory. It receives a command object on the following format:

{method:'ajax',url:'',data:{},success:function(){},error:function(){}}

Example of live button markup

<a class="livebutton" href="#"
data-cmd='{"method":"ajax","url":'http://localhost/',"success":handleAJAX}">test ajax</a>

getscript

Its calling jQuery’s getScript method. It receives a command object on the following format:

{method:'getscript',url:''}

Example of live button markup

<a href="#" class="livebutton"
   data-cmd='{method:"getscript",url:'http://localhost/script.js'}' >test getscript</a>

jquery

Its calling any jQuery’s method. It receives a command object on the following format:

{"method":"jquery","jqmethod": "","target":"","arguments":["url",function(){}]}

Example of live button markup

<a class="livebutton" href="#" data-cmd="{"method":"jquery","jqmethod":"load","target":"#layer","arguments":["url":"http://localhost"]">test load jquery function</a>

Remarks

As previously said, all functions also receive the command object extracted from the HTML element, but that’s not all. The parser automatically includes a jquery reference of the HTML element to the command’s element property.

var options = {
    methods: {
        alert: function( command ) {
              alert( command.message );
             // do not use $( command.element ) as it would like $( $( element ) )
              command.element.attr('title','I have already been clicked');
        }
   }
}
$('.selector').livebuttons( options );

Demo

For the sake of having a demo (I will build a better one) the following script will create a live button that can perform jquery ‘append’ commands. Please note that when you load new content via AJAX on a page that has the livebuttons plugin that you have successfuly initiated, the plugin will also listen to the specified events to those livebuttons loaded via AJAX.

<html>
<head>
<script src="path\to\jquery.livebuttons.js"></script>
<script>
$('.testbuttons').livebuttons();
<body>
<a href="#" class="testbuttons"
  data-cmd="{"method":"jquery","jqmethod":"append","target":"#container","arguments":["new content<br>"]}">Test append</a>
<div id="container"></div>
</body>
</html>

Download

I seriously would like to know what do you think about this system as, again, I am planning to develop extensions for Yii that will embrace it in order to easy the tasks of PHP programmers with client Javascript. I do use this system to create a new system for a personal project and it is working quite good; but I won’t dare to create Yii extensions if you think that what I envision is wrong.

If the below link doesn’t work (it happens normally because you are not registered), please use the following link to download: jquery.livebuttons.js.

http://www.ramirezcobos.com/wp-content/plugins/downloads-manager/img/icons/default.gif download: JQuery Livebuttons Plugin (15.33KB)
added: 15/12/2010
clicks: 167



Tweet this!Tweet this!
Yii Framework

jqAutocomplete Extension for Yii

0

It was only a matter of time until I try to develop an extension for the Yii Framework and I have chosen the Ajax Powered Autocomplet plugin for JQuery to exercise with this technology.

How to use the Extension

I have included a test within the downloadable package that shows how to implement this extension. The test includes a TestController, a view and a test_layout; so I hope this will easy the way for you to check it.

First download and unzip its contents

  • Move jqAutocomplete contents (I said contents) into your application’s protected/extension folder
  • Copy TestController.php and paste it in (you guessed well) your application’s protected/controllers folder
  • Move test folder (not the contents but the whole folder this time) into your application’s protected/views folder
  • Finally test_layout.php into your application’s protected/layouts folder

That’s it! Ready for the test. Go to your browser and type http://<replace_with_your_application_url>/index.php?r=test/autocomplete. If everything was good, you will be able to see the first field (JSON TEST) working as an autocomplete.

Please check TestController.php to see an example of AJAX response from the client autocomplete’s Request calls -and yes, you can also do it from a database result query. Look also at the test view’s code for an example on how to use the extension.

Download
** If you have problems to download from below; please try it here.

http://www.ramirezcobos.com/wp-content/plugins/downloads-manager/img/icons/default.gif download: Ajax Powered AutoComplete Extension for Yii (126.83KB)
added: 20/10/2010
clicks: 226

Tweet this!Tweet this!
 

Bookakar.com Finally!

0

Finally, after long time of work, the first release of my own company: bookakar.com.

I have implemented lots of concepts widely spread throughout the Internet and I truly hope that they all work. Still, lot of work to do but as soon as I have spare time I will share with all of you guys lots of PHP and JS bits and pieces that I hope we, all together, could improve in order to make a great Open Source Resource for everybody to use.

For example, I have developed a set of PHP classes that help PHP programmers to implement GMaps without the need of Javascript knowledge.

I can wait to share…

Anyway, any feedback related to my site will be highly appreciated. One more thing and very important: I DO NOT SUPPORT INTERNET EXPLORER due to its security pitfalls on the bank payment gateway and its sillly way of understanding CSS rendering and styles -and I don’t mention its JS engine at all.

Bookakar.com works only on two Spanish areas: Alicante and Ibiza, but it will grow to other areas very soon.

Tweet this!Tweet this!
Picture-121-300x157

jQuery 1.4 -Are you ready?

0

jQuery lovers, today, 14th of January, the programmers of jQuery celebrate its anniversary releasing a new version of this wonderful library. Better iFrame support, great new shorthands, I don’t know what to say fellows but I am eager to find out what its new features are capable of.

The jQuery programmers not happy with a new release has also created a new  jQuery API site. Check what they have done on their API site here.

John Resig will announce 1.4 release details tomorrow but meanwhile, you can download it and see for yourself.

Also, if you want to learn more about what is new in jQuery 1.4 then you might find the following resources useful:

  1. 14 Days of jQuery
  2. Official jQuery Blog
  3. jQuery 1.4 Cheatsheet
  4. jQuery on Tweeter

Check what is new or changed on this new release here.

Happy birthday jQuery! Thanks for the good work!

Tweet this!Tweet this!
autocomplete

Ajax Powered Autocomplete Plugin for JQuery.js

3

I am glad to announce the launch of the successfull Ajax Powered Autocomplete for Prototype.js now as a plugin for JQuery. No much to say… if any of you want to have a look at this piece of code you can check it here.

Any feedback is highly appreciated.



Tweet this!Tweet this!
 

Ajax Load -Ajax Loading GIF Generator

0

Ajax Load - AJax Loading GIF GeneratorWho of those of you that use ajax on your projects aren’t looking around the web to find the perfect ‘loading please wait’ GIF for your brand new web application or site? I have to confess that I was one of them. I am not a designer, I can program any web application in a matter of days but when it comes to design… puff… It is the reason why I am always crawling the web for ‘inspiration’.

One of those days crawling I found an online tool created by kath called Ajax Load – Ajax Loading GIF Generator. There you don’t need to worry if you know how to design or not, this simple but very useful tool allows you to select the type of design you want for your ajax loading gif, the foreground and background colors and voilá, your ajax loading gif is ready to download.

Dropdown List

For those, like me, without a clue about designing there it is, the Ajax Load – Ajax Loading GIF Generator.



Tweet this!Tweet this!
 

Image Gallery via Ajax using JQuery Tools

8

overlayThe other day I was having a bit of headache trying to find the best way to display a gallery via Ajax for one of my projects. There are tons of great lightbox type scripts out there (I even have one: lightboxXL) but none of them truly suit my needs as most of them, including mine, are creating the image galleries on DOM load, or on Document load, or on Window load… none of them allowed me to make use of Ajax and I certainly didn’t want to rewrite the code of anybody.

Suddenly, searching the web I found the OVERLAY object from JQuery Tools. This library offers a set of objects that extend the functionality of JQuery, it contains six of the most useful JavaScript tools available for today’s website. The beauty of this library is that all of these tools can be used together, extended, configured and styled. In the end, you can have hundreds of different widgets and new personal ways of using the library.

This is how I used it to create the Image Gallery via Ajax:

Insertion of Libraries

First we must include the library on the HEAD section of the page (JQuery Tools have a compressed version of its tools and latest version of JQuery library)

<!-- Full version of jQuery Tools + jQuery 1.3.2 -->
<script type="text/javascript" src="js/jquery.tools.min.js"></script>

CSS Coding

This is where we are going to apply styles to our overlay.

/* scrollable should not disable gallery navigation */
#gallery .disabled {
    visibility:visible !important;
}
#gallery .inactive {
    visibility:hidden !important;
}
/* the overlayed element */
.simple_overlay {
    /* must be initially hidden */
    display:none;
    /* place overlay on top of other elements */
    z-index:10000;
    /* styling */
    background-color:#333;
    width:675px;
    min-height:200px;
    border:1px solid #666;
    /* CSS3 styling for latest browsers */
    -moz-box-shadow:0 0 90px 5px #000;
    -webkit-box-shadow: 0 0 90px #000;
}
/* close button positioned on upper right corner */
.simple_overlay .close {
    background-image:url(images/overlay/close.png);
    position:absolute;
    right:-15px;
    top:-15px;
    cursor:pointer;
    height:35px;
    width:35px;
}
/* styling for elements inside overlay */
.simple_overlay .details {
    position:absolute;
    top:15px;
    right:15px;
    font-size:11px;
    color:#fff;
    width:150px;
}
.simple_overlay .details h3 {
    color:#aba;
    font-size:15px;
    margin:0 0 -10px 0;
}
/* "next image" and "prev image" links */
.next, .prev {
	/* absolute positioning relative to the overlay */
	position:absolute;
	top:40%;
	border:1px solid #666;
	cursor:pointer;
	display:block;
	padding:10px 20px;
	color:#fff;
	font-size:11px;
	/* upcoming CSS3 features */
	-moz-border-radius:5px;
	-webkit-border-radius:5px;
}
.prev {
	left:0;
	border-left:0;
	-moz-border-radius-topleft:0;
	-moz-border-radius-bottomleft:0;
	-webkit-border-bottom-left-radius:0;
	-webkit-border-top-left-radius:0;
}
.next {
	right:0;
	border-right:0;
	-moz-border-radius-topright:0;
	-moz-border-radius-bottomright:0;
	-webkit-border-bottom-right-radius:0;
	-webkit-border-top-right-radius:0;
}
.next:hover, .prev:hover {
	text-decoration:underline;
	background-color:#000;
}
/* when there is no next or previous link available this class is added */
.disabled {
	visibility:hidden;
}
/* the "information box" */
.info {
	position:absolute;
	bottom:0;
	left:0;
	padding:10px 15px;
	color:#fff;
	font-size:11px;
	border-top:1px solid #666;
}
.info strong {
	display:block;
}
/* progress indicator (animated gif). should be initially hidden */
.progress {
	position:absolute;
	top:45%;
	left:50%;
	display:none;
}
/* everybody should know about RGBA colors. */
.next, .prev, .info {
	background:#333 !important;
	background:rgba(0, 0, 0, 0.6) url(images/h80.png) repeat-x;
}

HTML Coding

Now the HTML holder

<!-- overlay element -->
<div class="simple_overlay" id="gallery">
<!-- "previous image" action -->
<a class="prev">prev</a>
<!-- "next image" action -->
<a class="next">next</a>
<!-- image information -->
<div class="info"></div>
<!-- load indicator (animated gif) -->
<img class="progress" src="images/ajax-loader.gif" />
<!-- end of overlay element -->
</div>

PHP Response

By now, you should already know how to do Ajax calls using JQuery, if you don’t please review it on JQuery’s site. What we are going to check is how is the PHP response in order to make our Image Gallery work after an Ajax call.

// ************************************
// Scenario: An ajax call to this PHP script was done and
// a POST variable has been sent in order to fill $pics from
// a database.
//
// pics == array of pictures
// ************************************
// loop the array
foreach($pics as $pic)
{
	// check the class attribute --> ibox
	// $pic is also an object with certain properties in this case
       $html .= '<div class="pic">
			<a href="'.$pic->imgPath.$pic->strName.'" class="ibox" title="'.$pic->strName.'">
			<img src="'.$pic->imgPath.$pic->strName.'" width="50" border="0" /></a>
			</div>';
}
//
// here I create the necessary javascript code to load the OVERLAY object of JQuery Tools
// please check the 'ibox' call
//
$html .= '
     <script type="text/javascript">
     //<![CDATA[
     $('.ibox').overlay({
    		target: '#gallery',
    		expose: '#f1f1f1'
		}).gallery({
		speed: 800 });
     //]]></script>';
//
// echo response
//
echo $html;

And that’s it, once your image gallery is loaded whereever you wish to from an Ajax call, the latest javascript will fire and create the Image Gallery.

Addendum

I don’t want to say that there aren’t other ways to do exactly what I did in this post. I just share what was, in my case, the solution that I implemented into my project and it worked. I will go deeper into JQuery Tools in future posts. Nevertheless, hope you find this post useful.



Tweet this!Tweet this!
 

Internet Video Search Engine

0

Picture 10In order to prove  the efficiency of my lightboxXL object and how it could be used, I created ANTCUT.COM.There you can search for videos that match your search among most of the internet video providers.

It was created as a demo but if anybody thinks that it could be used for something else than that let me know. Maybe I am not the only one who find this feature useful…



Tweet this!Tweet this!
Go to Top