Ruby Mysql Connectivity

This post shows you how you can connect to MySQL in Ruby.   I’m assuming that you already aware with basic SQL Operation like how to create database, table and insert, delete, update statement. So I’m directly dive in coding part, as I believe that more theory can confuse us. so I gonna explain you straight to the point.

okay so first we try to connect to the MySQL server and fetch all rows from table “test”.

require 'mysql'
con = Mysql.new('localhost', 'root', 'root', 'test')  
rs = con.query('select * from demo')
rs.each_hash do |row|
    puts row['uid'] + " " + row['name']
end
con.close

to run this basic example you need to use following command

ruby fetchallrow.rb

for insert statement you can use following code.

con.query("INSERT INTO demo values('"+id+"','"+name+"','"+mno+"')")

now you can able to perform basic insert,update and delete statement in same way.

That’s It.!

Enjoy d code.. 🙂

Designing a RESTful API with Python and Flask

In recent years REST (REpresentational State Transfer) has emerged as the standard architectural design for web services and web APIs.

if you are new to Flask please go to Flask Docs and get basic concept of flask.  let’s dive in to coding part. I am going to explain very basic example of designing RESTful API with Flask.    let’s start with hello world application.

#!flask/bin/python
from flask import Flask

app = Flask(__name__)

@app.route('/')

def index():
return "Hello, World!"

if __name__ == '__main__':
app.run(port=5662, debug=True)

now you need to run this hello world application.

python helloworld.py

above command used to run python application.

okkY , now lets go ahead..

next, i gonna explain you how to create RESTful Web application.

Before creating Dynamic Web Application with Flask, you must need to understand the directory structure of flask.

/templates :  you must need to put all your template files (.html) inside this folder

/static: you can put all your static files usually JavaScript and CSS files

you need to use this syntax to include css or js files from static folder.

url_for('static', filename='style.css')

lets go for very basic web app

#!flask/bin/python
from flask import Flask, render_template
#from flask import Flask, jsonify, render_template, request
app = Flask(__name__)

@app.route('/')
def index():
    return render_template('main.html')

if __name__ == '__main__':
       app.run(port=5662, debug=True)

you need to put main.html file inside templates folder as mentioned above.

main.html file contain simple hello world. that you can do it urself.

=== now lets create dynamic application which return JSON data to front end html file and i will show you how to send ajax request to REST API. ===

This application provides facility to make addition of two numbers. so html file contain two inputs and while submitting form using JQuery it will request to Rest API (_add_numbers)

Python Code:

from flask import Flask, jsonify, render_template, request
app = Flask(__name__)

@app.route('/')
def index():
return render_template('index.html')

@app.route('/_add_numbers')
def add_numbers():
"""Add two numbers server side, ridiculous but well..."""
a = request.args.get('a', 0, type=int)
b = request.args.get('b', 0, type=int)
return jsonify(result=a + b)

if __name__ == '__main__':
app.run(port=5662, debug=True)

HTML Code

create layout.html

<!doctype html>
<title>jQuery Example</title>
<script type=text/javascript
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type=text/javascript>
var $SCRIPT_ROOT = {{ request.script_root|tojson|safe }};
</script>
{% block body %}{% endblock %}

create index.html

{% extends "layout.html" %}
{% block body %}
<script type=text/javascript>
$(function() {
var submit_form = function(e) {
$.getJSON($SCRIPT_ROOT + '/_add_numbers', {
a: $('input[name="a"]').val(),
b: $('input[name="b"]').val()
}, function(data) {
$('#result').text(data.result);
$('input[name=a]').focus().select();
});
return false;
};
$('a#calculate').bind('click', submit_form);
$('input[type=text]').bind('keydown', function(e) {
if (e.keyCode == 13) {
submit_form(e);
}
});
$('input[name=a]').focus();
});
</script>
<h1>jQuery Example</h1>
<p>
<input type=text size=5 name=a> +
<input type=text size=5 name=b> =
<span id=result>?</span>
<p><a href=# id=calculate>calculate server side</a>
{% endblock %}

 

————————————————————————————————-

hope you all like this .. congrats now you can develop beautiful RESTful Dynamic Application on Flask.  🙂

Dealing with bootstrap alert

hello guys,

I got some problem while dealing with bootstrap alert.

How to show bootstrap alert div again

when we close alert div box, then if again we can’t show that div box. even if we write jquery show() function.

solution:

checkout  <a> tag there you got data-dismiss=”alert” , this will remove div from dom so that’s why we can’t show that div again. so just remove that and bind your function to that div

code:

<a id=”lieclose” onclick=”general_close(this.id)”>×</a>

jquery code:

function general_close(id)
{
	var current_id = "#"+id;
	$(current_id).parent().hide();
}

above function will work for any alert div. just change your id in a tag.

How to redraw bootstrap-error message

$('#loginerrbox').empty();
$('#loginerrbox').append("Please enter valid credentials. 
<a id='crdlogerr' class='close' onclick='general_close(this.id)'>×</a>");					
$('#loginerrbox').show();

above code demonstrate how to redraw new error message on alert div.

hope you like above Tips 🙂

jquery datatable simple n effective example

hello guys,

let’s go for very simple DataTables example which is filled by jquery ajax call.

Import bellow file in your html heading section

!!! note :–  just replace &gt; with > (end tag)

<link rel=”stylesheet” type=”text/css” href=”http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables_themeroller.css”&gt;
<link rel=”stylesheet” type=”text/css” href=”http://datatables.net/media/blog/beautiful_tables/complete.css”&gt;
<script type=”text/javascript” charset=”utf8″ src=”http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/jquery.dataTables.min.js”&gt;
</script>

JQuery function

$.ajax({
        	type: "GET",
		data: {data: pass ur data},
           	url:  "give your php file url here",
            	contentType: "application/json; charset=utf-8",
            	success: function(data) {
		$('#table').append("<tr><td>YOUR DATA HERE</td></tr>"); 
                $('#table').dataTable({
                   "sScrollY": 200,
                   "bJQueryUI": true,
               }); 
            } 
 });

HTML code for table

<table cellpadding=”0″ cellspacing=”0″ border=”0″ id=”ausgroup” width=”80%”>
<thead>
<tr>
<th>Your Heading </th>
</tr>
</thead>
<tbody>
</tbody>
</table>

Note

some important option listed bellow

“bJQueryUI”: true,       — for UI css of Table
“bPaginate”: false,        — for Pagination
“bLengthChange”: false,
“bFilter”: true,                — for filter
“bSort”: true,                 — for sorting

Redraw Datatable with fresh data

     $.ajax({
	            type: "GET",
	            url: "your url",
        	    success: function(data) {
		       if (typeof oTablelb != 'undefined') 
		        oTablelb.fnClearTable();
		        $('#lbtable').append("<tr><td>your data</td></tr>"); 
                        oTablelb=$('#lbtable').dataTable({ 
                                  "bDestroy": true, 
                                  "sScrollY": 200, 
                                  "sScrollX":400, 
                                  "bJQueryUI": true, 
                               }); 
                    } 
        });

just set bellow property

1) if (typeof oTablelb != 'undefined') oTablelb.fnClearTable();

2) "bDestroy": true,

now run your file,  DataTable will reload fresh data based on ajax call.  🙂

hope you like it!!