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:
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.
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:
http://jsabino.wordpress.com/2011/09/05/igoogle-interface-updated-to-lastest-version-of-jquery/
great script….I was working to save in DB since last week today I found it thanks for sharing..