Using remote_function
This wonderful built-in function is a great way to make easy Ajax calls. In this example I will show you how to use remote_function with the onClick call, and also within a JavaScript function.
First, lets make a checkbox called finish; this link will send the id of the item to the database to be updated. The item will be a todo and we will be using the list.html.erb and the todo_controller.rb.
In the view named: list.html.erb
remote_function(:url => {:action => 'finish', :controller => 'todo',
:id => todo.id})
Now once the checkbox is clicked it will them make the Ajax call to the todo_controller.rb with the method finish.
In the controller: todo_controller.rb
def finish
@todo = Todo.update(params[:id], :status => '1')
if @todo.save
render :update do |page|
page.replace_html 'thedivID' + params[:id], 'Finished!'
end
end
end
The above code will first update the database setting the status from 0 to 1 (1 = finished and 0 = unfinished). Next we check if the update was successful, after that we render the update to the page. By using render :update, we can replace the html in side of the div or other element with the text ‘Finished’.
Note you can use remote_function in any way you see fit, ie: onclick, onload and others.
Passing another var with remote_function. lets say i want to pass the user id, list id and, the todo id. How would we do this with the remote function?
We know know the link should look like this: /todo/finish/17?todoid=72&userid=100, but how do we do this with rails? Below is how to do just that;
remote_function(:url => {:action => 'finish', :controller => 'todo',
:id => list.id, :todoid => todo.id, :userid => @user.id})
Database Class
The latest version 1.1.2 of the database class is now available for download! Check out the project page for info on how to use and download this class.
Grant access to your MySQL
One of the best tools i have ever used in my whole life for database management and design has to be Navicat. That application is just so useful and easy to get the hang of. So when i get a new server granting access is one of the first things i hit. How do i forget this every time, i have no idea. How it starts is i open up Aptana and start my application then start building, the next thing i do is open Navicat and try to connect and duhh! The server is refusing the connection from my IP! So i open up a terminal and login to the server then open mysql. Next i will grant access to all databases on my IP for my username and password. See below…
# Granting remote access to your mysql database
mysql> GRANT ALL ON * TO user@'192.168.1.1' IDENTIFIED BY 'PASSWORD';
Yes, replace “user” with your username and replace “192.168.1.1″ with your real IP and “PASSWORD” with a real one! Hope that helps save someone some time!
New Product: Winn Tracker
Something i have been working on for about three or four weeks now is something called “Winn Tracker”. This new product will have the ability to track page views, downloads and user information in your own custom application or website. Winn Tracker will allow you to make a call to the database to track info 3 ways.
1. Direct Link (http://your domain.tld/pathto/tracker…)
2. PHP Class link ($a->hit(‘info to send’,['userName' => 'Bob']);)
3. Ajax link, out of the three this is the preferred method of communication. I have build a new Javascript function on top of prototype to build the call and then use the Ajax.Request function. (Winnjs.Hit(’send info’,['username:Bob']))
The first launch of this will be in just a few short days and then the full release will be in about a month. The first release of this will not have a backend tool for the admin area. Version 2 will have a full admin area where you can create the three above calls with options, with little programing experience.
This system will come light with only about 1.5 megs of files and only 3 tables to install to your mysql database. Version 2 will come with a full install script along with many more options for non developers to use.
I will keep you posted on new changes to this and when it will launch.
Create a database on the fly
In some recent work I needed to have databases created with a back end application. Once the database was created from this online application it was pre filled with tables and data from another script that ran right after the database was made. To create a database with PHP we first need to connect as a user that has the ability to create new databases. Note that we are not connecting to a database but we are connecting to MySQL as a user.
[php]
$link = mysql_connect(‘localhost’, ‘mysql_user’, ‘mysql_password’);
if (!$link) {
die(‘Could not connect: ‘ . mysql_error());
}
[/php]
After we have the connection we can simply call the following:
[php]
$dbname = $_POST['databasename']
// Your able to use a string here like: $dbname = ‘test_database’
// I am showing how you can get it from the POST.
// Also would be smart to check if the data sent is not empty with: if ( empty($dbname) ) {…
$sql = ‘CREATE DATABASE ‘ . $dbname;
if (mysql_query($sql, $link)) {
echo “Database my_db created successfully\n”;
} else {
echo ‘Error creating database: ‘ . mysql_error() . “\n”;
}
[/php]
This can become dynamic if you use it in conjunction with a text filed that allows the user to set the database name.
Changing data in RoR
I needed to change some data that was not being submitted by my form. Your asking, what? Well say you have a form for account signups. The form has fields for: full name, email, and password. Now your database has columns for: full name, email, password, signupdate, and status. I needed to send the database some data for the account to be valid.
I could use hidden fields to submit the data but I need something more practical. Ruby on Rails makes this easy, just add what you’re missing to your controller and send your form on its way! Below is an example of what we just talked about.
[ruby]
def create
@account = Account.new(params[:signup])
@account.signupdate = Date.today
@account.stat = 1
if @account.save
flash[:notice] = ‘Your Account was successfully created.’
redirect_to :action => ‘index’
else
render :action => ‘index’
end
end
[/ruby]
Winn Framework
Currently in development is a framework that I have been using for some time. I am looking at making it cleaner and more usable for any project. I will be releasing the first version on this framework very shortly! With this version (0.10) you can make calls to get individual form elements or full login forms. This version is manly for authentication to a MySQL database, more options available later on but for now just some basics! Keep an eye out the Winn Framework download coming soon!
[php]$winn->login($user, $pass);
//This will also set cookies, change in the config.php file[/php]
Authenticate a user from a MySQL database.
Authentication is important when building a web application, you don’t want others seeing information that does not belong to them. When you build an app that has “accounts” this is the login to your account. Just like going to Google and logging in to your account, it holds all your changes and settings.
To follow this we will need PHP and MySQL, you may find and install PHP and MySQL just by simply doing a search for them on Google, AOL, MSN or Yahoo. Once installed and working you may start on the next area of the tutorial. Note; this tutorial is assuming you know basic PHP, HTML, and MySQL.
First let’s start with your MySQL database and create a table called (admins). Then create 3 columns and name them as follows; ‘id’ -> (int, key), ‘user’ -> (text), ‘password’ -> (text). Once done add a row with a user and password, such as; (Mike) and the password is (1234).
Let’s move on to the PHP document and start the form fields. Below I am building a login form, this has two fields. One is the username field which is text, next we have the password field and the type is password.
[html]
[/html]
Great, now we have our form so if you view it online you will see two fields and one login button. You may format the look as you like but when you’re done let’s move on.
Now let’s do the validation of the fields and then check is the user is in the database. Let’s start by opening PHP, then we will do a (if isset) we will check for the var ($_POST['submit']). After that we need to check to see if the user left the fields blank. To do so we will use the PHP built in function empty(), just place the empty in an if statement and spit out an error stopping the query from checking the user. Take a look below, I am just checking if the form was submit. If yes, I am checking if the fields where empty, if the fields or field was empty I am stopping the query with the var $error.
[php]
if( isset($_POST['submit']) ) {
if( empty($_POST['username']) ) {
$error[] = “User is empty”;
}
if( empty($_POST['password']) ) {
$error[] = “Password is empty”;
}
if( empty($error) ) {
THE MySQL QUERY
print “Error!”;
}
[/php]
Now we can start the query to your MySQL database, let’s include the database connection (in this case I am using my db_class found here, it has everything you need to connect to your database). Ok, let’s make the call to the database and see if the user and password matches the ones submitted. Make a query asking for the user that matches the data submitted, by asking if user = $_POST[‘username’] and if password = $_POST[‘password’]. Then let’s count the number of rows returned, if we come back with 0 then we know the data submitted was wrong so let’s spit out an error. Or if the count returns more than 0 we know the data submitted was correct and we should now let them login to the account.
[php]
if( empty($error) ) {
include('/db_class.php');
$select_user = "SELECT * FROM account WHERE user='$_POST['username']' AND password='$_POST['password']'";
if( $run = mysql_query($select_user) ) {
$num_acc = mysql_num_rows($run);
if( $num_acc < 1 ) {
$showerror = "Sorry No account here!";
}else{
header("location: /account.php");
}
[/php]
It’s all up to you on how the errors come out, but be sure to let the user know if an error exists so they can try again or get help. If you need help with this tutorial contact me and I can help! Greg [at] winn [dot] ws, thanks for reading!
Save time with Queries
In developing the June Project and JuneLite I came up with something that was saving me a lot of time. This php class is calling the queries for me all I need to do is write the guts of the query, and if updating provide the record id. This class can connect to your database and then all you need to do is make calls to it below I show you how. In this version of the DB Class I have “Update, Insert and Delete”, I will be working on a method to pull selects out soon, but for now you will have to add your own select queries.
[php]
//==> how to call this
$db = new dbcon();
$db->update(‘table’, ‘row=your data’, ‘id’);
[/php]
The next section of code is how to insert into the database.
[php]
//==> how to call this
$db = new dbcon();
$db->insert(‘table_name’, ‘row=your info’);
[/php]
Categories
Pages
- contact
- Contact Form V1.8
- FlickrHelper
- Guestbook V1.01 ASP
- Guestbook V2.4.7
- iFrame Loader
- Scriptatype:PHP
- Winn Cal
- Winn Tracker
