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.
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.
Hi mango
Insert this new function for iNettuts object in inettuts.js:
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.
Hello.
Can you please give me an example on this section.
Thanks
ELZahar
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
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 ….
Hi Niraj,
In which file i have to change these lines?
thnx in advance
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
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.
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.
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
I dont know what i do wrong but the downloadable example doesnt work, can anyone help me?
Vincent
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
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:
?>
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
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?
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
can you tell how could you be able to fix above issue
Excellent work… Thanks…
you write «// User_id -> Should come from a session variable »
is possible that evry user ged ID from his session?
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
nice work ..you save my day 🙂
i try make box with rss or twitter links editor , it make this script +1
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
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.
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?
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
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 «);
}
}
Hay andres will you plz post the whole logic for asp.net application please i need it..
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?
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?
[…] 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 […]
[…] Shared How to Mimic the iGoogle Interface with Database « El blog de Súper Mario. […]
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’.
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
Please post ASP code
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 !
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….
When I try do drag:
this.helper.scrollParent is not a function
[Break On This Error] this.scrollParent = this.helper.scrollParent();
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.
It works perfect, chrome, ie8+9, firefox3+4
I am getting same error here ,
$(clonedWidget).attr(“class”) is undefined , at line 255 inettuts.js
how to fix it
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.
Hi
I have updated the code to the latest version of jQuery and jQuery UI as you suggest:
great script….I was working to save in DB since last week today I found it thanks for sharing..
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!
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:
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.
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.
Doesn’t work in IE9!
Great Post, but it doesn’t work with IE 9. I’d appreciate if you could help me.
Hi Shahzeb and Recif
Please check my updated version here:
It works fine with IE 9.
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.
Hi, just wanted to mention, I liked this post.
It was inspiring. Keep on posting!
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.
Hi Jeffry and «vacation reply»
Thank you very much for your encouragement!!!