How to Mimic the iGoogle Interface with Database

19 09 2009

James Padolsey wrote a great tutorial about «How to mimic the iGoogle interface» with jQuery. Thank you very much, James. I have used your code intensively.

The next step was a new article explaining how to save widgets configuration into a cookie. Very useful too. But the final part was to store that data in a database.

That’s what a have done: an example of the same code, but using a database. The changes are very easy to implement. I have just had to modify savePreferences and sortWidgets functions in inettuts.js file, and to write a new PHP file for saving and loading data.

I call jQuery post function to send the data using AJAX for savePreferences:

$.post("iNettuts_rpc.php","value="+cookieString);

As you can see, cookieString is the same variable stored into a cookie. Then iNettuts_rpc.php manages with the database. It’s a very simple PHP showing how to store the value for a user called John Doe:

header("Cache-Control: no-cache");
header("Pragma: nocache");

// User_id -> Should come from a session variable
$user_id="john doe";

// DB connect parameters
$server="localhost";
$user="root";
$password="";
$database="iNettuts";

$table="iNettuts";
$field="config";

// DB connect
mysql_connect($server,$user,$password);
@mysql_select_db($database);

if (isset($_REQUEST["value"])) {
 // SET value  

 $value=$_REQUEST["value"];

 $rs=mysql_query("SELECT * FROM $table WHERE user_id='$user_id'");
 if (mysql_numrows($rs)==0)
 mysql_query("INSERT INTO $table($field,user_id) VALUES('$value','$user_id')");
 else
 mysql_query("UPDATE $table SET $field='$value' WHERE user_id='$user_id'");
 echo "OK";

} else {
 // GET value 

 $rs=mysql_query("SELECT $field FROM $table WHERE user_id='$user_id'");
 if ($row=mysql_fetch_row($rs))
 echo $row[0];
 else
 echo "";
}

mysql_close();

And finally, the most difficult part: loading data to sort widgets:

sortWidgets : function () {
 var iNettuts = this,
 $ = this.jQuery,
 settings = this.settings;

 if(!settings.saveToCookie) {
 $('body').css({background:'#000'});
 $(settings.columns).css({visibility:'visible'});
 return;
 }

 $.post("iNettuts_rpc.php", "",
 function(data){

 var cookie=data;

 if (cookie=="") {
 $('body').css({background:'#000'});
 $(settings.columns).css({visibility:'visible'});
 iNettuts.addWidgetControls();
 iNettuts.makeSortable();
 return;
 }

 /* For each column */
 $(settings.columns).each(function(i){

 var thisColumn = $(this),
 widgetData = cookie.split('|')[i].split(';');

 $(widgetData).each(function(){
 if(!this.length) {return;}
 var thisWidgetData = this.split(','),
 clonedWidget = $('#' + thisWidgetData[0]),
 colorStylePattern = /\bcolor-[\w]{1,}\b/,
 thisWidgetColorClass = $(clonedWidget).attr('class').match(colorStylePattern);

 /* Add/Replace new colour class: */
 if (thisWidgetColorClass) {
 $(clonedWidget).removeClass(thisWidgetColorClass[0]).addClass(thisWidgetData[1]);
 }

 /* Add/replace new title (Bring back reserved characters): */
 $(clonedWidget).find('h3:eq(0)').html(thisWidgetData[2].replace(/\[-PIPE-\]/g,'|').replace(/\[-COMMA-\]/g,','));

 /* Modify collapsed state if needed: */
 if(thisWidgetData[3]==='collapsed') {
 /* Set CSS styles so widget is in COLLAPSED state */
 $(clonedWidget).addClass('collapsed');
 }

 $('#' + thisWidgetData[0]).remove();
 $(thisColumn).append(clonedWidget);
 });
 });

 /* All done, remove loading gif and show columns: */
 $('body').css({background:'#000'});
 $(settings.columns).css({visibility:'visible'});

 iNettuts.addWidgetControls();
 iNettuts.makeSortable();

 });
 }

I have used the same variable names to make it easier.

You can download the full example here.


Acciones

Information

53 responses

23 09 2009
mango

thanks for the writeup – very helpful.

i have one question though – how to set a widget’s editable attribute to true or false dynamically? i can see how it can be set in the inettus.js in the widgetIndividual section, but in my case, each widget’s setting is dynamic based on some user criteria. any pointers? i am totally struck and cannot proceed.

i post on James Padolseys blog and have no luck.

24 09 2009
jsabino

Hi mango

Insert this new function for iNettuts object in inettuts.js:

toggleEditable : function (id) {
        var $ = this.jQuery,
            settings = this.settings;
        iNettuts.getWidgetSettings(this.id).editable=!iNettuts.getWidgetSettings(this.id).editable;
        
        var w=$(settings.widgetSelector, $(settings.columns)).get(id);
        if (iNettuts.getWidgetSettings(this.id).editable)
          $(".edit",w).css({visibility:'visible'});
        else
          $(".edit",w).css({visibility:'hidden'});

        return ;
    }

Call it with the number of the widget you want to toggle editable property. For example: iNettuts.toggleEditable(2);
I can upload and example if you need.

21 07 2010
Zahar

Hello.
Can you please give me an example on this section.

Thanks
ELZahar

28 09 2009
Vincent

Hi,

II was looking on the website of James Paddolsy to see if anyone had solved de ‘database’ problem, but discoverd that the sit of Padolsy wasnt online anymore!

But reading your comment on the other site i became very enthousiastic, but i face a problem.

Your example, which i have downloaded, doesnt work in firefox, de loading icon just runs and runs but in never loads actually? What do i wrong?

Thanx in advance!

Vincent

30 09 2009
NIraj

Hey Vincent, If you Dont get code running please do little change in following lines :

Original lines :
if ($row=mysql_fetch_row($rs))
echo $row[0];
else
echo «»

}

Changed and working lines :

if ($row=mysql_fetch_row($rs))
{
echo $row[0];
return $row[0];
}
else
{
echo «»;
return $row[0];
}

i think here jsabino forgot to return the value to jquery ….

but atlast Good Work jsabino ..

just chill ….

3 10 2009
Vincent

Hi Niraj,

In which file i have to change these lines?

thnx in advance

3 10 2009
jsabino

Hi Nlraj

The return call you have inserted doesn`t do anything. The value passed to js throught jQuery ajax call is already done by echo. You don’t need to «return» anythings.

Vincent’s problem could be related to database.

Regards

28 09 2009
serd

Me estoy encontrando con un problema, si el index tiene menos de 6 widgets deja de funcionar, si tiene más en las pruebas que he realizado funciona, he estado repasando el código y no encuentro cual puede ser el problema.

28 09 2009
serd

Me respondo a mi mismo, el problema viene dado al conectar a la base de datos, si tenemos la configuración de 6 widgets grabada en la base de datos y hemos eliminado un widget manualmente en el codigo HMTL, entonces no se cargara la pagina.

2 10 2009
Andrew

Hi,

I need some help. Do you think you can make the version save a different type of widgets set for different users and let them add a widget ? I need this for a project i’m working for at school and would really like some help.

Thank you

3 10 2009
Vincent

I dont know what i do wrong but the downloadable example doesnt work, can anyone help me?

Vincent

3 10 2009
jsabino

Hi Vincent

The example works fine both in Explorer and Firefox. I am sure of that.

– Have you created a database called «iNettuts»? You can use other database but you should change $database variable in iNettuts_rpc.php file.

– Have you created the table in the database using the provided script «script.sql»?

– Have you checked the database connection variables ($server, $user, $password, $database…)?

Try to execute iNettuts_rpc.php file directly in your browser to check if there is an error.

Regards

7 10 2009
Danilo

Hello I setup all that is needed. Then open error console in firefox and it show me this errors:

Error: $(clonedWidget).attr(«class») is undefined
Source File: file:///D:/Program%20Files%20(x86)/Zend/Apache2/htdocs/testing/inettus/inettuts.js
Line: 255

and

Error: no element found
Source File: file:///D:/Program%20Files%20(x86)/Zend/Apache2/htdocs/testing/inettus/iNettuts_rpc.php
Line: 46, Column: 3
Source Code:
?>

4 05 2010
Agent

Hi Danilo

I am getting same error here ,

$(clonedWidget).attr(“class”) is undefined , at line 255 inettuts.js . I think this is something with mismatching cookie data at client side and one that comes from database.

Your help would be much appreciated!! Can you respond to this by email agentsas (at) gmail (dot) com

Thank you

7 10 2009
Danilo

I soloved above problem but when I delete some boxes and than refresh page the boxes are still on screen. How can I add this option?

31 10 2009
Prathyush

Hi Danilo

I am getting same error here ,

$(clonedWidget).attr(«class») is undefined , at line 255 inettuts.js . I think this is something with mismatching cookie data at client side and one that comes from database.

Your help would be much appreciated!! Can you respond to this by email prathyush (at) cre8tivebug (dot) net

Thank you

2 11 2009
Prathyush

can you tell how could you be able to fix above issue

7 11 2009
Ranga

Excellent work… Thanks…

14 11 2009
rulo

you write «// User_id -> Should come from a session variable »
is possible that evry user ged ID from his session?

6 02 2010
Eli

no and yes, what i did was use my session being made from my login script and just display the $_SESSION[‘id’] as the $user_id

14 11 2009
urorbit

nice work ..you save my day 🙂
i try make box with rss or twitter links editor , it make this script +1

7 12 2009
Padfoot

Can you give me an example of a widget picker? I have seen lots of examples for the cookie version but I can’t get them working with database.
I am also having trouble emptying the config field for a certain user so I can have a reset function

11 01 2010
Anand Selvaraj

i can delete the widget and updated in the db. but when i refresh the page that time all the widgets loading including deleted one.

what my need is once widgets deleted it will not show in the page.

5 02 2010
Eli

Hola!

I was able with trail and error store the users’ session ID as the table ID for the widgets. But I lost my configuration and I can’t reproduce my code! haha, but I was wondering I can only get this script to work if I put all the files into 1 parent folder. I tried to spread out my files to folders like /js/ and /css/ but the entire script breaks, even after setting the correct paths to all the files I moved.

Incidentally, does this script not work if the index.html is rename to index.php?

6 03 2010
keshav

hello, your tutorial is helpful. but i want to do in the asp.net. you worked in php page and i want to work with .aspx page.can you help me how can i get the value from cookie and save into database using asp.net.

its urgent please help me and mail me the answer

17 04 2010
Andreas

Hey, If you want to use it together with asp.net you must change the $.post command to post to an aspx file e.g.:

$.post(«iNettuts_rpc.aspx»,»value=»+cookieString);

and then you must look at the request you get at this aspx side. You’r page_load function could e.g. look like this:

protected void Page_Load(object sender, EventArgs e)
{
if (Request[«Value»] != null)
{
// Here you place the code to store the data in the database
Response.Write(«OK»);
}
else
{
// Here you place the code to retrieve the data from the database
Response.Write(» HERE YOU PLACE THE VALUE FROM THE DATABASE «);
}
}

30 04 2010
Jeet

Hay andres will you plz post the whole logic for asp.net application please i need it..

16 03 2010
basar

In IE7 it returns some errors for me,
line: 214
character: 1
code: 0
URI: http://localhost/tf2/test/gerekliler/move/inettuts.js

how can i solve that?

29 04 2010
Eli

I get this error when I run my page

POST http://helixagent.com/widget.php
POST http://helixagent.com/widget.php

500 Internal Server Error
77ms

in firebug. my widget.php doesn’t return an error so i know its connecting to my database.

hmmm, what could be the problem?

11 05 2010
A complete iGoogle like interface example with jQuery « El blog de Súper Mario

[…] complete iGoogle like interface example with jQuery 5 05 2010 After my previous post about how to mimic the iGoogle interface with database, I have been working in a new version. Now I have added all you need to build a simple page, with […]

28 06 2010
Eric Blue’s Blog » Weekly Lifestream for June 27th

[…] Shared How to Mimic the iGoogle Interface with Database « El blog de Súper Mario. […]

6 07 2010
grant

HI,

I converted it to asp but noticed the post is striping all spaces so if the widget name was ‘Widget panel 1’ after the post it is ‘Widgetpanel1’.

7 07 2010
grant

If anyone one else has the same problem with loosing spaces it seems a Ajax POST removes them.

To fix it go to +- line 202 in the inettuts.js file and replace

$.post(«dashboardmod.asp»,»value=»+cookieString);

with

$.post(«dashboardmod.asp»,»value=»+encodeURIComponent(cookieString));

Take from –
http://cksource.com/forums/viewtopic.php?f=6&t=7624&p=20304

22 07 2010
Goldy

Please post ASP code

5 11 2010
Maryam

Hi Jsabino,

Many thanks for this work ! It works perfectly on JQuery version «1.2.6.min.js» but I can’t make it work on latest Jquery versions. That is the blocks are not movable anymore. But they’re still editable. I was wondering if I did something wrong or if somebody else had encountered the same problem ? I can call the 1.2.6.min.js jquery, so I’m not cornered…:-). Have a nice day !

5 11 2010
Maryam

Hello again,

Actually, the blocks are movable, but the ajax query to php file is not called…
mystery….If I put your old jQuery version, it works…but creates conflicts with my other jQuery scripts….

31 12 2010
Marco Ribeiro

When I try do drag:
this.helper.scrollParent is not a function
[Break On This Error] this.scrollParent = this.helper.scrollParent();

4 02 2011
Shameer

the collapse button is not working if we use jquery 1.4.x .
any ideas??. t work fine if we are using google chrome or firefox.

8 05 2011
kroatien

It works perfect, chrome, ie8+9, firefox3+4

11 08 2011
taqman

I am getting same error here ,

$(clonedWidget).attr(“class”) is undefined , at line 255 inettuts.js
how to fix it

19 08 2011
1234

If you’re using a more recent version of jquery and the jquery-ui.

Example:
jquery-1.6.2.min.js with jquery-ui-1.8.16.custom.min.js the script will not work. Anyone knows what the problem could be?

Because I really need the newer version of jquery.

5 09 2011
jsabino

Hi

I have updated the code to the latest version of jQuery and jQuery UI as you suggest:

iGoogle interface updated to lastest version of jQuery

26 11 2011
free php scripts

great script….I was working to save in DB since last week today I found it thanks for sharing..

18 07 2012
Keelan

Thank you very much for this! I started to code this for myself from scratch but then i found the original then the cookie version then this version then your cookie and database version.

I integrated this with UserCake and changed the SaveToDB variable with a php variable which checks if a user is logged in or not.

If they are it saves it to the database if not it saves it to the cookie. Working like a charm.

Now i am just trying to list all my widgets and let a user pick which ones to insert and which ones to remove.

If they are removed they go to a «dock» where they can drag them back at a later date.

(right now in my testing i am using a select drop down box to insert specific widgets)

What i do have a question about is. How can i have a default view?

Basically once someone new, not logged in or no session stored. Will have default widgets displayed. Then they can proceed to edit them. Either by logging or using a sesson.

Right now when a user visits the site it is just blank and that isn’t very appealing. Ideally i would like it to copy the admins widget layout.

I tried to play with the sql in the get value in iNettuts_rpc.php by changing the $user_id depending whether the user is logged in or not but that didn’t seem to work correctly.

Could anyone point me in the right direction?

I hope this is semi active still.

Once again thank you for this it saved me weeks or work!

13 09 2012
jsabino

Hi Keelan

I think I have already anwered that question in another post in my blog… The best way to do is in iNettuts_rpc.php. Instead of returning an empty string (echo «»;) when the user is not registered in the DB (line 46 in my example), return a valid widget config string, for example:

$rs=mysql_query("SELECT $field FROM $table WHERE user_id='$user_id'");
  if ($row=mysql_fetch_row($rs)) 
    echo $row[0];
  else
    echo "widget1,color-blue,widget 1,not-collapsed|widget2,color-red,widget 2,not-collapsed|widget3,color-blue,widget 3,not-collapsed";

The easiest way to build this string is to make the changes in the page (add the widgets you need) and then copy the string from the config field in the DB.

13 09 2012
keelan

Hey, in the end I just turned my js file into php so I could change a variable, when a user logs in it changes to use database else use cookie, then outputs the php file as js witha header.

I pushed a cookie to them when they first visit if they are not logged in, with user 1 widgets from the database.

Works pretty good, when they first register it takes their cookie and writes it to the database.

Then when they visit they and not logged in they will see user 1 untill they login and it pulls there settings from the database.

7 12 2012
recif (@recif67)

Doesn’t work in IE9!

23 12 2012
shahzeb

Great Post, but it doesn’t work with IE 9. I’d appreciate if you could help me.

27 12 2012
jsabino

Hi Shahzeb and Recif

Please check my updated version here:

iGoogle interface updated to lastest version of jQuery

It works fine with IE 9.

31 12 2012
shahzeb

Thanks for reply, One more thing, when i drag left to right any div its add new row, could you tell me how do i add replacement functionality, like A1, A2, B1, B2, C1, C2, if i move A2 to C1 then C1 should move to the A2 place and A2 move to the C2 place.

15 04 2013
vacation reply

Hi, just wanted to mention, I liked this post.
It was inspiring. Keep on posting!

25 04 2013
Jeffry

I have been browsing online more than 3 hours today, yet
I never discovered any attention-grabbing article like yours.
It’s pretty value enough for me. In my opinion, if all site owners and bloggers made just right content material as you did, the web might be much more helpful than ever before.

25 04 2013
jsabino

Hi Jeffry and «vacation reply»

Thank you very much for your encouragement!!!

Replica a jsabino Cancelar la respuesta