Tuesday, 1 May 2018

Django chat application

This article is about how to create a chat application or chat server using Django 2.0. This chat system depends Python 3 and Django restframework to create rest apis. Jquery ajax is using to call the api from the client side. I am using Ubuntu 16.04 to create this tutorial.

You can download the example source code from here:- https://dl.dropboxusercontent.com/s/obt4u4udlt30k8w/chatproj.zip

After download completed, extract the folder to somewhere on your computer, then open a terminal window inside the extracted project directory. Then run the following commands to create a virtual environment and activate.

virtualenv -p python3 env

source env/bin/activate


For complete details about create a virtual environment read this article:- http://newprograminglogics.blogspot.com/2018/02/install-python-3-and-set-up-local.html

Then install Django by run this command
pip install django


Then install Django rest framework
pip install djangorestframework


Then run these commands to create migrations
python manage.py makemigrations chatapp

python manage.py migrate


All configurations completed. Now start the server using this command
python manage.py runserver


To check the functionality open http://127.0.0.1:8000/index in any browser
For reduce complexity I am not using a user login. You can simply login to chat by using your name or nickname without any log up process.

Enter your name like John , Peter in the From text box. Open the same url http://127.0.0.1:8000/index in another tab, type another name in it.
You can see the online users in the right column. Click one of the Names, you can see a chat box is opened. You can write messages in it and send to the selected user.

Watch the video tutorial (Click the gear icon and select video quality to 1080p HD, then click the full screen button for good quality)



Tuesday, 6 March 2018

Load static files in django 2.0

This article is about how to serve static files in Django 2.0. Static files means javascript libraries like jquery, css files or images.
Jquery is an essential part of modern web development. When we use the templating system of django we need to do some steps to include jquery to it.
Sometimes you may try to access the static files by some methods it may not work properly and ends up in a 404 error.

I am explaining the process with an example application. This example includes a button. When click in it it will show an image.

This tutorial assumes that you have created a virual enviorment and django 2 project with mysite and app with myapp were created.
To read about how to create a virtual enviornment and install django go this link:- Install Python 3 and Set Up a Local Programming Environment

Open mysite/mysite/settings.py. Paste following line in the INSTALLED_APPS section
'myapp.apps.MyappConfig'


Then check following line is included in the INSTALLED_APPS section
'django.contrib.staticfiles'


Then check this line is exist in the same settings.py file
STATIC_URL = '/static/'


Then create a folder named static in myapp folder.
Create a folder named myapp inside it.
Download jquery and an image in this folder.

Then in the myapp folder create a folder named templates
Create another folder named myapp in it
Then create a file named index.html in it
Then paste the following code in it
{% load static %}
<!DOCTYPE html>
<html>
<body>
<img width="400px" height="300px" style="display:none;" id="img" src="{% static 'myapp/flower.jpg' %}"/>
<br/>
<input type="button" value="Show Image" id="btn"/>
<script src="{% static 'myapp/jquery-3.3.1.min.js' %}"></script>
<script>
$(document).ready(function(){
$('#btn').click(function(){
        $('#img').show();
});
});
</script>
</body>
</html>

Don't forget to add the line  {% load static %} in the top of the page.
In this code {% static 'myapp/flower.jpg' %} flower.jpg can replace with the image you downloaded in the static folder.
Also in {% static 'myapp/jquery-3.3.1.min.js' %} jquery-3.3.1.min.js can replace with your jquery version.

Open the file myapp/views.py
Paste the following code in it
def index(request):
    return render(request, 'myapp/index.html')


Create a file named urls.py in myapp folder
Then paste the following code in it
from django.urls import path

from . import views

urlpatterns = [
    path('', views.index, name='index')
]


Next open Open mysite/mysite/urls.py.
Add an include keyword in the line
from django.urls import path

Now it will look like
from django.urls import path,include


Add this line in the urlpatterns section
path('myapp/', include('myapp.urls'))


Then run the command in mysite folder
python manage.py runserver

Note that you must restart the development server in order to access static files.
Now open the url http://127.0.0.1:8000/myapp in any browser.It will show a button saying Show Image. Click it will show the image.

Watch the video tutorial (Click the gear icon and select video quality to 1080p HD, then click the full screen button for good quality)



You can download the example app from here: https://dl.dropboxusercontent.com/s/zjssc3xgpzmxqnd/mysite.zip

Sunday, 11 February 2018

Install Python 3 and Set Up a Local Programming Environment then install Django locally on Ubuntu 16.04

This article is about installing python 3 virtual environment on Ubuntu 16.04. If you are looking to set up a python 3 development environment, this  tutorial will help you.

First install python 3 by run these commands in the terminal
sudo apt-get install python3.5

Then install pip3 the python package manager by running
sudo apt-get install python3-pip

Then install virtualenv package
sudo pip3 install virtualenv

Then create a directory named my_proj which is our project name in your home directory. Then open a terminal window in that directory. Run the following command to create a virtual environment
virtualenv -p python3 env

Then run this command to activate the virtual environment
source env/bin/activate

Our virtual environment is activated now. To check it run
which python3

It will give the result    /home/sukesh/sukesh/python/my_proj/env/bin/python3

To install Django 2 run this
pip install Django

Note that pip, and python commands can be used in our virtual environment instead of pip3 and python3.

 Run this to check django
python -m django --version

It will give result   2.0.5

Create a sample project by run this. Don't forget the trailing dot(.)
django-admin startproject my_proj .

Our project is created now. Run this to create an app
django-admin startapp my_app

Now we need to add the created app to our project. For that open my_proj/my_proj/settings.py, then add 'my_app' to the INSTALLED_APPS section. Our INSTALLED_APPS will looks like this
INSTALLED_APPS = [
         'django.contrib.admin',
         'django.contrib.auth',
         'django.contrib.contenttypes',
         'django.contrib.sessions',
         'django.contrib.messages',
         'django.contrib.staticfiles',
         'my_app'
]


You have finished. To start the development server run
python manage.py runserver

Our server has started now. To check this open this url in any browser:-  http://127.0.0.1:8000

Watch this video tutorial (Click the gear icon and select video quality to 1080p HD, then click the full screen button for good quality)

Thank You

Wednesday, 31 January 2018

Chat application using a database table in PHP - Part 3

This is the third update of Chat application using a database table in PHP.
This article is the continution of a simple chat application in PHP or web chat application using live chat rest api.

Previous articles were solution to your doubts like how to create a php chat room or php chat server, or php chat app or php chat box or php chat system. This time I have created rest api for chat.Rest apis using json so now I can call it a json chatbot, json chat server, json chat room or collectively json chat php script.

By using rest api we can separate back end and front end into separate sections. So implement this chat to other platforms like android will become easy.

Before going through my php chat application source code you can see this PHP chat application demo here.

Please open this same page in another tab or another browser to test the chat application.
For reduce complexity I am not using a user login. You can simply login to chat by using your name or nick Name without any log up process.

Enter your name like Xwe , Yrt , Zty  in the From text box.You can see the online users in the right column. Click one of the Names, you can see a chat box is opened. You can write messages in it and send to the selected user.
You can download the complete zip file from this link:-
https://dl.dropboxusercontent.com/s/8jsal21eo73xrl6/openchat_part3.zip

To know how to install and use watch this video.  (Click the gear icon and select video quality to 1080p HD, then click the full screen button for good quality)
Here is the source code for chat application in php
Here have two files index.php and back.php

 code
 index.php

<html>
<head>

</head>
<body>
<table width="100%" height="100%" border="1" align="center" valign="center">
<tr><td colspan="2" height="6%"><h3>Chat Window</h3></td></tr>
<tr><td colspan="2" height="6%"> From(Your Name or Id):&nbsp;&nbsp;<input type="text" name="sender" id="sender"><br></td></tr>
<tr><td width='85%'>
<div id="chat_view" >

&nbsp;
</div>
</td>
<td>
<div>Online Users</div>
<ul id="users">                   
</ul>
</td>
</tr>
</table>
<div id="chat_list"></div>
<style type="text/css">
.chat_box{
border-style:solid;
border-width:medium;
width:200px;
height:310px;
float:left;
margin-left:2px;

}
#msg{
width:200px;
height:200px;
overflow:auto;
}
#new_msg_text
{
width:200px;
height:50px;
resize: none;
}
#close_button{
width:20px;
height:20px;
padding-left:2px;
}
#users{
list-style: none;
padding:0px;
}
</style>

<script type="text/javascript" src="./jquery.1.11.1.js"></script>
<script type="text/javascript">
$(document).ready(function(){
window.setInterval(function() {
viewMsg();
viewOnlineUsers();
createNewChatBox();

},1000);
});

function creatNewBox(receiver)
{
var newbox ="<div class='chat_box' id='chat_box_"+receiver+"'>"+
"<div id='chat_header'><input type='text' style='width:180px;' name='receiver[]' READONLY value='"+receiver+"' id='receiver'><span onclick='closeWindow($(this))'>X</span></div>"+
"<div  height='20%' id='msg' >"+
"<br><br><br></div>"+
"<div id='newmsg'><textarea rows='4' cols='10' id='new_msg_text'>&nbsp;</textarea></div>"+
"<div><input type='button' value='Send' id='btn' onclick='saveMsg($(this))'></div>"+
"</div>";

return newbox;
}

function createNewChatBox()
{
var sender=$("#sender").val();
$.ajax({
type: 'GET',
url: 'back.php?opt=get_chat&sender='+sender,
success: function(data){
if(data.status==true)
{
$('#chat_list').html('');
data.data.users.forEach(function(user,index){
if(user.sender!='')
{
$('#chat_list').append("<input type='text' name='chat_users[]' value='"
+user.sender+"'>");
viewBox(user.sender);
}   
});

}
}          
});

}

function viewBox(receiver)
{
if($.trim($("#sender").val())==$.trim(receiver))
return;
$(document).ready(function(){
var flag=false;
$("input[name='receiver[]']").each(function(){

if($(this).val()==receiver)
{flag=true;}
});
if(flag==false)$("#chat_view").append(creatNewBox(receiver));         
});
}

function viewOnlineUsers()
{
var sender=$("#sender").val();
$.ajax({
type: 'GET',
url: 'back.php?opt=view_users&sender='+sender,
success: function(data){
if(data.status==true)
{
$('#users').html('');
data.data.users.forEach(function(user,index){
if(user.user_id!='')
{
$('#users').append("<li><a onclick=\"viewBox('"+user.user_id+"')\">"
+user.user_id+"</a></li>");
}   
});

}
}

});

}
function closeWindow(obj)
{
obj.parent().parent().remove();
}

function viewMsg()
{
var sender=$("#sender").val();
$("input[name='receiver[]']").each(function(){
var receiver=$(this).val();
$.ajax({
type: 'GET',
url: 'back.php?opt=view_msg&sender='+sender+"&receiver="+receiver,
success: function(data){
if(data.status==true)
{
$("#chat_box_"+receiver).find("#msg").html('');
data.data.messages.forEach(function(message,index){
if(message.user_id!='' && message.msg!='')
{
$("#chat_box_"+receiver).find("#msg").append("<table<tr>"
+"<td>"+message.user_id+": "+message.msg+"</td>"
+"</tr></table>");
}   
});

}
}

});
});
}

function saveMsg(obj)
{

var receiver=obj.parent().parent().find("#receiver").val();

var sender=$("#sender").val();
if(sender=='') return false;
var msg=obj.parent().parent().find("#new_msg_text").val();

$.ajax({
type: 'POST',
url: 'back.php?opt=save',
data: {"receiver":receiver,"sender":sender,"msg":msg},
success: function(){
obj.parent().parent().find("#new_msg_text").val('');
}

});
}
</script>

</body>
</html>


back.php

<?php
extract($_POST);
extract($_GET);
$con = new mysqli('localhost', 'root', 'password','chat_db');

switch ($opt)
{
    case "save":     
    $stmt = $con->prepare("INSERT INTO chat (sender,receiver,msg,time) values(?,?,?,NOW())");
    $stmt->bind_param("sss", $sender, $receiver, $msg);
    $stmt->execute();
    break;

    case "view_msg":
    $result=array('status'=>false,'data'=>array()); 
    $stmt = $con->prepare("SELECT chat.*,users.user_id FROM chat  LEFT JOIN users ON users.user_id=chat.sender"
        ." WHERE (receiver= ? AND sender= ? )"
        ." OR (receiver= ? AND sender= ? ) ORDER BY time");
    $stmt->bind_param("ssss", $sender, $receiver, $receiver, $sender);
    $stmt->execute();
    $r = $stmt->get_result();
    $messages=array();
    while ($row = $r->fetch_assoc()) {
        $messages[]=$row;
    }
    $result['status']=true;
    $result['data']['messages']=$messages;
    header('content-type:application/json');
    echo json_encode($result);
    break;
 
    case "get_chat":
    $result=array('status'=>false,'data'=>array());     
    $stmt = $con->prepare("SELECT DISTINCT  sender from chat ".
        "  WHERE receiver= ? AND AddTime(time, '00:00:15')>=NOW()");
    $stmt->bind_param("s", $sender);     
    $stmt->execute();
    $r = $stmt->get_result();
    $users=array();
    while ($row = $r->fetch_assoc()) {
        $users[]=$row;
    }
    $result['status']=true;
    $result['data']['users']=$users;
    header('content-type:application/json');
    echo json_encode($result);
    break;
 
    case "view_users":
    $result=array('status'=>false,'data'=>array());
    $stmt = $con->prepare("SELECT count(*) as count FROM users WHERE user_id= ?");
    $stmt->bind_param("s", $sender);     
    $stmt->execute();
    $r = $stmt->get_result();
    $row = $r->fetch_assoc();
    if($row['count']>0)
    {
        $stmt = $con->prepare("UPDATE users SET last_visit=NOW() WHERE user_id= ?");
        $stmt->bind_param("s", $sender);           
    }
    else
    {
        $stmt = $con->prepare("INSERT INTO users (user_id,last_visit) values(?,NOW())");
        $stmt->bind_param("s", $sender);
    }
 
    $stmt->execute();
    $stmt = $con->prepare("SELECT * FROM users WHERE AddTime(last_visit, '00:00:15')>=NOW()");
    $stmt->execute();
    $r = $stmt->get_result();
    $users=array();
    while ($row = $r->fetch_assoc()) {       
        $users[]=$row;
    }
    $result['status']=true;
    $result['data']['users']=$users;
    header('content-type:application/json');
    echo json_encode($result);
 
    break;
}
?>

Here I am using two Mysql tables namely chat and users

chat








users





The query to make this tables
chat
CREATE TABLE IF NOT EXISTS `chat` (
  `sender` varchar(255) DEFAULT NULL,
  `receiver` varchar(255) DEFAULT NULL,
  `msg` text,
  `time` datetime DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

users
CREATE TABLE IF NOT EXISTS `users` (
  `user_id` varchar(255) NOT NULL,
  `last_visit` datetime NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

You can also read :- Chat application using a database table in PHP - Part 1
Chat application using a database table in PHP - Part 2

Saturday, 13 January 2018

Chat application using a database table in PHP - Part 2

This is the second update of Chat application using a database table in PHP.
This article is to describe a simple chat application in PHP or web chat application.

This article will be a solution to all your doubts like how to create a php chat room or php chat server, or php chat app or php chat box or php chat system. I wrote a php chat script in previous blog now improving that php chat example with prepared statements.

As you know using prepared statements it will become more secure. Because it can prevent SQL injection attacks.

Before going through my php chat application source code you can see this PHP chat application demo here.
Please open this same page in another tab or another browser to test the chat application.
For reduce complexity I am not using a user login. You can simply login to chat by using your name or nick Name without any log up process.


Enter your name like Xwe , Yrt , Zty  in the From text box.You can see the online users in the right column. Click one of the Names, you can see a chat box is opened. You can write messages in it and send to the selected user.
You can download the complete zip file from this link:-
https://dl.dropboxusercontent.com/s/7td2j2jiahfpfw3/openchat_part2.zip
To know how to install and use watch this video.  (Click the gear icon and select video quality to 1080p HD, then click the full screen button for good quality)
Here is the source code for chat application in php
 Here have two files index.php and back.php

 code
 index.php

<html>
    <head>
     
    </head>
    <body>
        <table width="100%" height="100%" border="1" align="center" valign="center">
            <tr><td colspan="2" height="6%"><h3>Chat Window</h3></td></tr>
            <tr><td colspan="2" height="6%"> From(Your Name or Id):&nbsp;&nbsp;<input type="text" name="sender" id="sender"><br></td></tr>
            <tr><td width='85%'>
                    <div id="chat_view" >
     
       &nbsp;
                    </div>
                </td>
                <td>
                    <div id="users" name="users">Online Users</div>
                </td>
            </tr>
        </table>
        <div id="chat_list"></div>
        <style type="text/css">
            .chat_box{
border-style:solid;
border-width:medium;
width:200px;
height:300px;
float:left;

}
#msg{
width:200px;
height:200px;
overflow:auto;
}
#new_msg_text
{
width:200px;
height:50px;
}
#close_button{
width:20px;
height:20px;
}
.user_list{

}
        </style>
     
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function(){
                window.setInterval(function() {
                   viewMsg();
                   viewOnlineUsers();
                   createNewChatBox();
                 
                },1000);
            });
         
            function creatNewBox(receiver)
            {
            var newbox ="<div class='chat_box' id='chat_box_"+receiver+"'>"+
            "<div id='chat_header'><input type='text' name='receiver[]' READONLY value='"+
            receiver+"' id='receiver'><span onclick='closeWindow($(this))'>X</span></div>"+
            "<div  height='20%' id='msg' >"+
                "<br><br><br></div>"+
             "<div id='newmsg'><textarea rows='4' cols='10' id='new_msg_text'>&nbsp;</textarea></div>"+
             "<input type='button' value='Send' id='btn' onclick='saveMsg($(this))'>"+
        "</div>";
     
        return newbox;
            }
         
            function createNewChatBox()
            {
             var sender=$("#sender").val();
    $("#chat_list").load('back.php?opt=get_chat&sender='+sender);
    $("input[name='chat_users[]']").each(function(){
 
viewBox($(this).val());
});
            }
            function viewBox(receiver)
            {
                if($.trim($("#sender").val())==$.trim(receiver))
                return;
               $(document).ready(function(){
               var flag=false;
              $("input[name='receiver[]']").each(function(){
           
if($(this).val()==receiver)
{flag=true;}
});
        if(flag==false)$("#chat_view").append(creatNewBox(receiver));         
               });
            }
         
            function viewOnlineUsers()
            {
                var sender=$("#sender").val();
                $("#users").load('back.php?opt=view_users&sender='+sender);
             
            }
            function closeWindow(obj)
            {
            obj.parent().parent().remove();
            }
         
            function viewMsg()
            {
                var sender=$("#sender").val();
$("input[name='receiver[]']").each(function(){
var receiver=$(this).val();
$("#chat_box_"+receiver).find("#msg").load('back.php?opt=view_msg&sender='+sender+"&receiver="+receiver);
});
}
       
        function saveMsg(obj)
        {
            var receiver=obj.parent().find("#receiver").val();
                         
            var sender=$("#sender").val();
            var msg=obj.parent().find("#new_msg_text").val();
         
           $.ajax({
           type: 'POST',
           url: 'back.php?opt=save',
           data: {"receiver":receiver,"sender":sender,"msg":msg},
           success: function(){
              obj.parent().find("#new_msg_text").val('');
           }
         
           });
        }
        </script>
     
    </body>
</html>

back.php
<?php
extract($_POST);
extract($_GET);
$con = new mysqli('localhost', 'root', 'password','chat_db');

switch ($opt)
{
    case "save":     
        $stmt = $con->prepare("INSERT INTO chat (sender,receiver,msg,time) values(?,?,?,NOW())");
        $stmt->bind_param("sss", $sender, $receiver, $msg);
        $stmt->execute();
    break;

    case "view_msg":       
        $stmt = $con->prepare("SELECT chat.*,users.user_id FROM chat  LEFT JOIN users ON users.user_id=chat.sender"
        ." WHERE (receiver= ? AND sender= ? )"
        ." OR (receiver= ? AND sender= ? ) ORDER BY time");
        $stmt->bind_param("ssss", $sender, $receiver, $receiver, $sender);
        $stmt->execute();
        $r = $stmt->get_result();
        while ($row = $r->fetch_assoc()) {
            echo "<table><tr>";
            echo "<td>".$row['user_id'].": ".$row['msg']."</td>";
            echo "</tr></table>";
        }
    break;
     
    case "get_chat":       
        $stmt = $con->prepare("SELECT DISTINCT  sender from chat ".
        "  WHERE receiver= ? AND AddTime(time, '00:00:15')>=NOW()");
        $stmt->bind_param("s", $sender);     
        $stmt->execute();
        $r = $stmt->get_result();
        while ($row = $r->fetch_assoc()) {     
        echo "<input type='text' name='chat_users[]' value='".$row['sender']."'>";
        }
    break;
 
    case "view_users":
            $stmt = $con->prepare("SELECT count(*) as count FROM users WHERE user_id= ?");
            $stmt->bind_param("s", $sender);     
            $stmt->execute();
            $r = $stmt->get_result();
            $row = $r->fetch_assoc();
            if($row['count']>0)
            {
                $stmt = $con->prepare("UPDATE users SET last_visit=NOW() WHERE user_id= ?");
                $stmt->bind_param("s", $sender);           
            }
            else
            {
            $stmt = $con->prepare("INSERT INTO users (user_id,last_visit) values(?,NOW())");
            $stmt->bind_param("s", $sender);
            }
           
            $stmt->execute();
            $stmt = $con->prepare("SELECT * FROM users WHERE AddTime(last_visit, '00:00:15')>=NOW()");
            $stmt->execute();
            $r = $stmt->get_result();
            while ($row = $r->fetch_assoc()) {
            echo "<table><tr>";     
            echo "<td><a onclick=\"viewBox('".$row['user_id']."')\">".$row['user_id']."</a></td>";
            echo "</tr></table>";
        }
    break;
}
?>


Here I am using two Mysql tables namely chat and users
chat

users

The query to make this tables
chat
CREATE TABLE IF NOT EXISTS `chat` (
  `sender` varchar(255) DEFAULT NULL,
  `receiver` varchar(255) DEFAULT NULL,
  `msg` text,
  `time` datetime DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

users
CREATE TABLE IF NOT EXISTS `users` (
  `user_id` varchar(255) NOT NULL,
  `last_visit` datetime NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

You can also read :- Chat application using a database table in PHP - Part 1
Chat application using a database table in PHP - Part 3

Saturday, 31 May 2014

Human Computer Interface introduction with calculator example

human computer interaction,human computer interaction example,human computer interaction calculator ,artificial intelligence example,artificial intelligence calculator
This article is to demonstrate a human computer interaction system with a calculator example.
I am trying to reduce the GUI interface and make a human command mode to the system.Many of the researchers think that human speak  recognition is the basic step of Human Computer Interaction (HCI).   But I don't think so,because human speak recognition is a gigantic problem.
Because the  pronunciation and volume variation of each persion is varying and the slang are also different.

But the easy way to give HCI commands to computer is by text medium.That is we can simply type the commands and execute the command.
Here you can see the example HCI calculator:-

HCI Calculator

Enter command
Result


This is a basic calculator with addition,subtraction,multiplication and division.    But odd to regular calculators you can't see digit or operator buttons instead  a 'Enter command'   box and 'Calculate'   button. When you write commands in the box and click calculate button the result will display in the result text box.

The command should have one operator and two operands.

My first command is ' add 4 7 ' .    It mean find the sum of 4 and 7.
You can see the screenshot here:-







But the real beauty is where  the command 4 add 7 also give the same result.
Then  4 7 add give the same result.
 addition 4 7   and 4+7 has the same result

prod 4 3  give the result 12.
The clean ,   cls    commands clear the results.

Yes, more flexible than GUI and it is more related to real life communication.

These are the commands I included in the calculators vocabulary.
SumDifferenceProductQuoetientClear
adddifferenceproductquotientclear
additiondiffproddivclean
plusminusmultiplydivisionempty
+-*/cls
clrscr

You can see the code here:
calc.html 


<html>
<body>
<table>
<tr><td colspan="2" align="center"><h3>HCI Calculator</h3></td></tr>
<tr>
<td valign="top">
Enter command
</td>
<td>
<textarea cols="50" rows="10" id="command"></textarea>
</td>
</tr>
<tr>
<td>&nbsp;</td>
<td  align="center">
<input type="button" value="Calculate" onclick="evaluateComm();"/>
</td>
</tr>
<tr>
<td>&nbsp;</td>
</tr>
<tr>
<td>
Result
</td>
<td>
<input type="text" id="result"/>
</td>
</tr>
</table>
<script type="text/javascript">
var verb=Array();
verb[0]=Array('sum','add','addition','plus','+');
verb[1]=Array('difference','diff','minus','-');
verb[2]=Array('product','prod','multiply','*');
verb[3]=Array('quotient','div','division','/');
verb[4]=Array('clear','clean','empty','cls','clrscr');



function evaluateComm()
{
var command=new String(document.getElementById('command').value);
if(command=='') return;
var comm=Array();
var i,flag=0,op_index=0;

command=command.replace('+',' plus ');
command=command.replace('-',' minus ');
command=command.replace('*',' prod ');
command=command.replace('/',' div ');

comm=command.trim().split(/\s+/);
for(i=0;i<comm.length;i++)
{
res=analyseOne(comm[i]);
if(res>=0)
{
flag=1;
op_index=i;
break;
}
}
if(flag==1)
{
if(res!=4&&comm.length<3)
{
alert('Two operands and one operator required!!!!');
return;
}
var op=getOtherOperand(op_index);
var output;
switch(res)
{
case 0:
output=Number(comm[op[0]])+Number(comm[op[1]]);
break;
case 1:
output=Number(comm[op[0]])-Number(comm[op[1]]);
break;
case 2:
output=Number(comm[op[0]])*Number(comm[op[1]]);
break;
case 3:
output=Number(comm[op[0]])/Number(comm[op[1]]);
break;
case 4:
document.getElementById('result').value='';
document.getElementById('command').value='';
return;
break;
}
document.getElementById('result').value=output;
}
else
{
alert('Command does not match my occabulary.Please check spellings');
return;
}
}
function getOtherOperand(res)
{
var arr=Array();
switch(res)
{
case 0:
arr=Array(1,2);
break;
case 1:
arr=Array(0,2);
break;
case 2:
arr=Array(0,1);
break;
}
return arr;
}

function analyseOne(str)
{
if(str=='') return -1;
var i,j,flag=0,fflag=0;
for(i=0;i<verb.length;i++)
{
for(j=0;j<verb[i].length;j++)
{
if(verb[i][j]==str.toLowerCase())
{
flag=1;
break;
}
}
if(flag==1){ fflag=1;break;}
}
if(fflag==1)
return i;
else
return -1;
}
</script>
</body>
</html>

Hope that you enjoy this code.More stuff on artificial intelligence and HCI is coming soon.Keep reading....

Sunday, 8 September 2013

Encode form elements for ajax submit

Hi friends,
Today my description is about submit form elements through ajax.Submit form through javascript can done using submit() method .
But when  try to submit a form through ajax we need to provide the name of elements and its value as data parameter in jquery $.ajax();

We can done this like
var data='';
data+='name='+$('#name').val()+'&age='+$('#age').val();


But we can use jquery serialize() method we can do this all stuff in single step,like this:
var data=$('#frm').serialize();


Example:

<form id="frm">
<input type="text" name="name"/>
<input type="text" name="age"/>
<input type="button" onclick="submitFrm();"/>
</form>

<script type="text/javascript">
function submitFrm()
{
var data=$('#frm').serialize();
$.ajax({
url:'action.php',
data:data,
type:'post',
datatype:'html',
success:function(){
alert('success...');
},
error:function(){
alert('error...');
}
});
}
</script>


That is we can use serialize() to easy ajax form submit.
If we want to add some additional parameters  existing outside of the form,
add them easily by using '&' like this.
var data=$('#frm').serialize();
data+='&teacher_name='+$('#teach_name').val();

Thank you.

Search This Blog