Wednesday, 2 April 2014

Ajax image upload without form submit and without page refresh

If You are looking for upload an image without submitting the form and with out refresh the page using jQuery, then this tutorial will usefull for you. I had implemented this ajax image upload program using 'ajaxfileupload' plugin, 'jquery' and PHP code for uploading images. By using following code you can upload image to the server. Click here to download "Ajax Image Upload" code.

Step 1:

Include Jquery plugin and ajaxfileupload plugin You can these plugins here. Example:
 
 <script src="js/jquery.min.js"></script>
 <script src="js/ajaxfileupload.js" type="text/javascript"></script>
 

Step 2:

Create form and input type 'file' and call a user defined function (showPreviewImage()) onchange action of that input type file. Example:
  
<form action="index.php" method="post" enctype="multipart/form-data"> <input type="file" name="photo" id="photo" onchange="showPreviewImage('photo')" /><br /> <span id="loader" style="display:none;"><img src="spinner.gif"></span> <div id="preview"></div> </form>

Step 3:

This is the important step.Create a function e.g showPreviewImage() this function will fired on chage of input type file . Here we will call a php file using jquery ajax e.g (upload.php) and write php image upload code there. Example:
 function showPreviewImage(imgId){                               
 $('#loader').show();
 var imgName=$('#photo').val();
 prevUrl="upload.php"      
 $.ajaxFileUpload({
  url:prevUrl,
  secureuri:false,
  fileElementId:imgId,
  dataType: 'json',
  complete: function (data, status){
   var z=data.responseText.replace(new RegExp("
"),''); if(z.indexOf('.')>0){ $('#loader').hide(); $("#preview").html("<img src='images/"+z+"' width='100'>"); }else{ $('#loader').hide(); $("#preview").html(z); } } }); }


To get complete code click here.

Thursday, 13 February 2014

Custom Database Table with image upload plugin for wordpress

In this plugin we'll be looking at creating custom database tables and insert data into that table with custom image upload functionality . We'll cover how to create, maintain and remove the table, as well as how to safely, and efficiently, add, remove and query data along with custom image uploaded functionality.


WordPress provides "$wpdb" class using that we can interact with database like creating , maintain custom tables ,fetch data and insert data into database. 

  Download Custom Table Example.

Create Custom Table

function custom_table_example_install()
{
    global $wpdb;
    global $custom_table_example_db_version;

    $table_name = $wpdb->prefix . 'cte'; 

    
    $sql = "CREATE TABLE " . $table_name . " (
      id int(11) NOT NULL AUTO_INCREMENT,
      name tinytext NOT NULL,
      email VARCHAR(100) NOT NULL,
   image VARCHAR(255) NULL,
      age int(11) NULL,
      PRIMARY KEY  (id)
    );";

    // we do not execute sql directly
    // we are calling dbDelta which cant migrate database
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql);

    // save current database version for later use (on upgrade)
    add_option('custom_table_example_db_version', $custom_table_example_db_version);
}
register_activation_hook(__FILE__, 'custom_table_example_install');

In the above code we create a function says "custom_table_example_install()" and call this function at the time of activation of the plugin by the help of "register_activation_hook()". In "custom_table_example_install()" function we declare sql query and exaecute that query by using "dbDelta()" .

When write sql to create your table remember following points:

  • each field MUST be in separate line
  • There must be two spaces between PRIMARY KEY and its name
    Like this: PRIMARY KEY[space][space](id)
    otherwise dbDelta will not work
After creating the database table we define "defining the custom table list".In this part we are define custom table list class,that will display our database records in nice looking table .




For download this plugin Click here.


Monday, 27 January 2014

Jquery Add More Input fields


These days a very frequent requirement from customers is to have input fields dynamically added to a form while typing in it. This should happen without refreshing the page because the user shouldn't be submitting the form before all their information is completed. Here  is a simple example of such interface.


If you are looking to add and remove more input fields, here’s a jQuery example below to do the task for you. This jQuery snippet adds more input fields dynamically with the validation .


Here we start with 1 row of  input field and let user add more fields . Same process goes to delete button, when clicked, it removes current text field by removing the parent element, which is '<tr>' (you can use <div> also) element.

We start with single row of  Input fields and a “Add more ” link to allow user to add more fields with blank validation. The text input field is wrapped in '<tr>' element, as explained above, on 'delete' link click, it finds parent element, which is '<tr>' and removes it.

Download Code Here

Friday, 18 October 2013

Sending Emails with PHP

PHP must be configured correctly in the php.ini file with the details of how your system sends email.

Now you are ready to go:

Sending plain text email:

 

PHP makes use of mail() function to send an email. This function requires three mandatory arguments that specify the recipient's email address, the subject of the the message and the actual message additionally there are other two optional parameters.


mail( to, subject, message, headers, parameters );

 Here is the description for each parameters.

Parameter Description
to Required. Specifies the receiver / receivers of the email
subject Required. Specifies the subject of the email. This parameter cannot contain any newline characters
message Required. Defines the message to be sent. Each line should be separated with a LF (\n). Lines should not exceed 70 characters
headers Optional. Specifies additional headers, like From, Cc, and Bcc. The additional headers should be separated with a CRLF (\r\n)
parameters Optional. Specifies an additional parameter to the sendmail program



As soon as the mail function is called PHP will attempt to send the email then it will return true if successful or false if it is failed.
Multiple recipients can be specified as the first argument to the mail() function in a comma separated list.

Example:

Following example will send an HTML email message to xyz@somedomain.com. You can code this program in such a way that it should receive all content from the user and then it should send an email.





<html>
<head>
<title>Sending email using PHP</title>
</head>
<body>
<?php
   $to = "xyz@somedomain.com";
   $subject = "This is subject";
   $message = "This is simple text message.";
   $header = "From:abc@somedomain.com \r\n";
   $retval = mail ($to,$subject,$message,$header);
   if( $retval == true )  
   {
      echo "Message sent successfully...";
   }
   else
   {
      echo "Message could not be sent...";
   }
?>
</body>
</html>


Sending HTML email:

When you send a text message using PHP then all the content will be treated as simple text. Even if you will include HTML tags in a text message, it will be displayed as simple text and HTML tags will not be formatted according to HTML syntax. But PHP provides option to send an HTML message as actual HTML message.
While sending an email message you can specify a Mime version, content type and character set to send an HTML email.

Example:

Following example will send an HTML email message to xyz@somedomain.com copying it to afgh@somedomain.com. You can code this program in such a way that it should recieve all content from the user and then it should send an email.


<html>
<head>
<title>Sending HTML email using PHP</title>
</head>
<body>
<?php
   $to = "xyz@somedomain.com";
   $subject = "This is subject";
   $message = "<b>This is HTML message.</b>";
   $message .= "<h1>This is headline.</h1>";
   $header = "From:abc@somedomain.com \r\n";
   $header = "Cc:afgh@somedomain.com \r\n";
   $header .= "MIME-Version: 1.0\r\n";
   $header .= "Content-type: text/html\r\n";
   $retval = mail ($to,$subject,$message,$header);
   if( $retval == true )
   {
      echo "Message sent successfully...";
   }
   else
   {
      echo "Message could not be sent...";
   }
?>
</body>
</html>


Sending attachments with email:

To send an email with mixed content requires to set Content-type header to multipart/mixed. Then text and attachment sections can be specified within boundaries.
A boundary is started with two hyphens followed by a unique number which can not appear in the message part of the email. A PHP function md5() is used to create a 32 digit hexadecimal number to create unique number. A final boundary denoting the email's final section must also end with two hyphens.
Attached files should be encoded with the base64_encode() function for safer transmission and are best split into chunks with the chunk_split() function. This adds \r\n inside the file at regular intervals, normally every 76 characters.
Following is the example which will send a file /tmp/test.txt as an attachment. you can code your program to receive an uploaded file and send it.


<html>
<head>
<title>Sending attachment using PHP</title>
</head>
<body>
<?php
  $to = "xyz@somedomain.com";
  $subject = "This is subject";
  $message = "This is test message.";
  # Open a file
  $file = fopen( "/tmp/test.txt", "r" );
  if( $file == false )
  {
     echo "Error in opening file";
     exit();
  }
  # Read the file into a variable
  $size = filesize("/tmp/test.txt");
  $content = fread( $file, $size);

  # encode the data for safe transit
  # and insert \r\n after every 76 chars.
  $encoded_content = chunk_split( base64_encode($content));
  
  # Get a random 32 bit number using time() as seed.
  $num = md5( time() );

  # Define the main headers.
  $header = "From:xyz@somedomain.com\r\n";
  $header .= "MIME-Version: 1.0\r\n";
  $header .= "Content-Type: multipart/mixed; ";
  $header .= "boundary=$num\r\n";
  $header .= "--$num\r\n";

  # Define the message section
  $header .= "Content-Type: text/plain\r\n";
  $header .= "Content-Transfer-Encoding:8bit\r\n\n";
  $header .= "$message\r\n";
  $header .= "--$num\r\n";

  # Define the attachment section
  $header .= "Content-Type:  multipart/mixed; ";
  $header .= "name=\"test.txt\"\r\n";
  $header .= "Content-Transfer-Encoding:base64\r\n";
  $header .= "Content-Disposition:attachment; ";
  $header .= "filename=\"test.txt\"\r\n\n";
  $header .= "$encoded_content\r\n";
  $header .= "--$num--";

  # Send email now
  $retval = mail ( $to, $subject, "", $header );
  if( $retval == true )
   {
      echo "Message sent successfully...";
   }
   else
   {
      echo "Message could not be sent...";
   }
?>
</body>
</html>








Sending e-mail from localhost in Windows Environment by using PHP mail function

Have you ever been frustrating, why e-mail is not going from the localhost while using XAMPP or WAMP or any other PHP servers in windows environment? well in that situation i think i can help you.In this article i am going to tell you how to send e-mail from localhost in PHP.
  • Open the “php.ini“. You should know where it is located because it depends upon the particular server you’re running.
  • Search for the attribute called “SMTP” in the php.ini file.Generally you can find the line “SMTP=localhost“. change the localhost to the smtp server name of your ISP. And, there is another attribute called “smtp_port” which should be set to 25.I’ve set the following values in my php.ini file.

    SMTP = smtp.wlink.com.np
    smtp_port = 25
  • Restart the apache server so that PHP modules and attributes will be reloaded.
  • Now try to send the mail using the mail() function ,

    mail(“you@yourdomain.com”,”test subject”,”test body”);

    you might get the warning like this, Warning: mail() [function.mail]: “sendmail_from” not set in php.ini or custom “From:” header missing in C:\Program Files\xampp\htdocs\testmail.php on line 1
  • Now specify the following headers and try to send the mail again,


    $headers = ‘MIME-Version: 1.0′ . “\r\n”; 
    $headers .= ‘Content-type: text/html; charset=iso-8859-1′ . “\r\n”;
     $headers .= ‘From: sender@sender.com’ . “\r\n”;
     mail(“you@yourdomain.com”,”test subject”,”test body”,$headers);
That’s all, the mail is sent to “you@yourdomain.com” from the localhost.

Note: Some smtp server verifies the email address of the sender so the email address which is in the place of “sender@sender.com” should be a valid and existing email address otherwise mail might not be sent to the “you@yourdomain.com”.

Wednesday, 2 October 2013

Understanding Javascript Events

Events

javascript is used to create dynamic web pages but with out events javascript is meaningless. Events are actions that can be detected by JavaScript.In this tutorial I give an overview of what event handling is, who to handle events.

Every element on a web page (button,anchor tag,input type etc) has certain events which can trigger a JavaScript. For example, we can use the onclick event of a button element to indicate that a function will run when a user clicks on the button. We define the events in the HTML tags.

JavaScript is meant to add interactivity to your pages: the user does something and the page reacts. this only possibele by the help of an event.

Events are normally used  with functions, and the function will not be executed before the event occurs.

Example How to use event:

<html>
<head>
function test(){
alert('onclick event example.');
}
</head>
<body>
<input type="button" name="clickme" value="click me" onclick="test();" />
</body>
</html>

here in the input element we add an event onClick and call an user define function test();

when user click on this button the onclick even fire and call the userdefine function test() and the code in side the function execute for more about user define function click here.

List of some events

Window Event Attributes


Events triggered for the window object (applies to the <body> tag): the event's are applied to body tag only.

onload

Fires after the page is finished loading

example: <body onload="function_name();">

onunload

Fires once a page has unloaded (or the browser window has been closed)

example: <body onunload="function_name();">

Form Events

 

Events triggered by actions inside a HTML form (applies to almost all HTML elements, but is most used in form elements):

onblur

Fires the moment that the element loses focus

example: <input type="text" name="fname" onblur="function_name();">

onchange 

Fires the moment when the value of the element is changed

example: <input type="text" name="fname" onchange ="function_name();">


onfocus 

Fires the moment when the element gets focus

example: <input type="text" name="fname" onfocus ="function_name();">

onreset 

Fires when the Reset button in a form is clicked

example <input type="reset" name="rst" value="Reset it" onreset="function_name();" >

onselect 

Fires after some text has been selected in an element

example: <input type="text" name="fname" onselect="function_name();">

onsubmit

Fires when a form is submitted

examle: <form name="form1" action="your asction" onsubmit="function_name();">


Keyboard Events


Events triggered by a key, or similar user actions:

onkeydown 

Fires when a user is pressing a key


example: <input type="text" name="fname" onkeydown ="function_name();">


onkeypress

Fires when a user presses a key

 example: <input type="text" name="fname" onkeypress ="function_name();">

onkeyup  

Fires when a user releases a key

example: <input type="text" name="fname" onkeyup ="function_name();">

 

Mouse Events

Events triggered by a mouse, or similar user actions:

onclick  

Fires on a mouse click on the element

example: <input type="button" name="fname" value="click"  onclick ="function_name();" />

ondblclick 

Fires on a mouse double-click on the element

example: <input type="button" name="fname" value="click"  ondbclick ="function_name();" />

onmousedown 

Fires when a mouse button is pressed down on an element

example: <div  onmousedown ="function_name();" ><!-- Your content --></div>


onmousemove 

Fires when the mouse pointer moves over an element

example: <div  onmousemove ="function_name();" ><!-- Your content --></div>

onmouseout 

Fires when the mouse pointer moves out of an element

example: <div  onmouseout ="function_name();" ><!-- Your content --></div> 

onmouseover 

Fires when the mouse pointer moves over an element

example: <div  onmouseover ="function_name();" ><!-- Your content --></div>  

onmouseup

Fires when a mouse button is released over an element

example: <div  onmouseup ="function_name();" ><!-- Your content --></div> 



javascript programming basics

Programming Basics

As we know that javascript is a popular scripting language and it support variables. Programmers use variables to store values. A variable can hold several types of data. In JavaScript you don't have to declare a variable's data type before using it.

Javascript is not a strongly typed language which means you rarely have to concern yourself with
the type of data a variable is storing, only what the variable is storing and in Javascript, variables
can store anything, even functions.

 Any variable can hold any JavaScript data type, including:
  • String data
  • Numbers
  • Boolean values (T/F)

Variable Names

There are rules and conventions in naming variables in any programming language. It is good practice to use descriptive names for variables. The following are the JavaScript rules:
  • The variable name must start with a letter or an underscore. example:firstName or _myName
  • You can use numbers in a variable name, but not as the first character.Ex:name01 or tuition$
  • You can't use space to separate characters.Ex:userName not user Name
  • Capitalize the first letter of every word except the first. Ex. salesTax or userFirstName

 

Variables

 

  • To declare variables, use the keyword var and the variable name: Example:var userName 7 ;
  • To assign values to variables, add an equal sign and the value:Ex: var userName = "Smith"; var price = 100

 

Operators

 

Like other programming language javascript also support following Operators
  • Assignment Operators(=,+=,-=,*=,/=,%=)
  • Arithmetic Operators(+,-,*,/,%,++,--)
  • Comparison Operators(==,!=,<,<=,>,>=)
  • Logical Operators(&&,||,!)
  • Conditional Operator(variablename=(condition)?value1:value2)

Note:The + Operator Used on Strings example : 

txt1="What a very";
txt2="nice day";
txt3=txt1+txt2;
 
//output:What a very nice day


Statements

  • Conditional statement (if, if.. else, switch)
  • Loop ( for loop, while loop )
  • try...catch throw

Conditional Statements

 

Want perform different actions for different decisions. You can use conditional statements in your code to do this. In JavaScript we have the following conditional statements:

  • if statement
    • use this statement to execute some code • only if a specified condition is true
  • if...else statement
    • use this statement to execute some code if the condition is true and another code if the condition is false
  • if...else if....else statement
    • use this statement to select one of many blocks of code to be executed.
  • switch statement
    • Use this statement to select one of many blocks of code to be executed

example of If...else if...else Statement

<script type="text/javascript">
var d = new Date()
var time = d.getHours()
if (time<10)
{
document.write("<b>Good morning</b>");
}
else if (time>10 && time<16)
{
document.write("<b>Good day</b>");
}
else
{
document.write("<b>Hello World!</b>");
}
</script>

example of switch Statement
<script type="text/javascript">
//You will receive a different greeting based
//on what day it is. Note that Sunday=0,
//Monday=1, Tuesday=2, etc.
var d=new Date();
theDay=d.getDay();
switch (theDay)
{
case 5:
document.write("Finally Friday");
break;
case 6:
document.write("Super Saturday");
break;
case 0:
document.write("Sleepy Sunday");
break;
default:
document.write("I'm looking forward to this weekend!");
}
</script>


loops

 

Some time we need same block of code to run over and over again in a row. Instead of adding several almost equal lines in a script we can use loops to perform a task like this
In JavaScript, there are three different kind of loops:
  • for
  • while
  • do ..while

Exampel for loop:
 
The for loop is used when you know in advance how many times the script should run.
<html>
<body>
<script type="text/javascript">
var i=0;
for (i=0;i<=5;i++)
{
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
</html>

Exampel while loop:
 
Loops execute a block of code a specified number of times, or while a specified condition is true.

<html>
<body>
<script type="text/javascript">
var i=0;
while (i<=5)
{
document.write("The number is " + i);
document.write("<br />");
i++;
}
</script>
</body>
</html>

Exampel do...while Loop
 
The do...while loop is a variant of the while loop. This loop will execute the block of code ONCE, and then it will repeat the loop as long as the specified condition is true.

<html>
<body>
<script type="text/javascript">
var i=0;
do
{
document.write("The number is " + i);
document.write("<br />");
i++;
}
while (i<=5);
</script>
</body>
</html>

JavaScript Break and Continue Statements  

 


The break Statement
 
The break statement will break the loop and continue executing the code that follows after the loop (if any).

<html>
<body>
<script type="text/javascript">
var i=0;
for (i=0;i<=10;i++)
{
if (i==3)
{
break;
}
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
</html>


The continue Statement
 
The continue statement will break the current loop and continue with the next value.

<html>
<body>
<script type="text/javascript">
var i=0
for (i=0;i<=10;i++)
{
if (i==3)
{
continue;
}
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
</html>

JavaScript For...In Statement
 
The for...in statement loops through the elements of an array or through the properties of an object.
Note: The code in the body of the for...in loop is executed once for each element/property.
Note: The variable argument can be a named variable, an array element, or a property of an object.


<html>
<body>
<script type="text/javascript">
var x;
var mycars = new Array();
mycars[0] = "Saab";
mycars[1] = "Volvo";
mycars[2] = "BMW";
for (x in mycars)
{
document.write(mycars[x] + "<br />");
}
</script>
</body>
</html>
output:


JavaScript Try...Catch Statement


 
The try...catch statement allows you to test a block of code for errors.

Catching Errors
 
When browsing Web pages on the internet, we all have seen a JavaScript alert box telling us there is a runtime error and asking "Do you wish to debug?". Error message like this may be useful for developers but not for users. When users see errors, they often leave the Web page.

The try...catch Statement
 

The try...catch statement allows you to test a block of code for errors. The try block contains the code to be run, and the catch block contains the code to be executed if an error occurs.



<html>
<head>
<script type="text/javascript">
var txt="";
function message()
{
try
{
adddlert("Welcome guest!");
}
catch(err)
{
txt="There was an error on this page.\n\n";
txt+="Error description: " + err.description + "\n\n";
txt+="Click OK to continue.\n\n";
alert(txt);
}
}
</script>
</head>
<body>
<input type="button" value="View message" onclick="message()" />
</body>
</html>
output:

The Throw Statement

 
The throw statement allows you to create an exception. If you use this statement together with the try...catch statement, you can control program flow and generate accurate error messages.

Example
 
The example below determines the value of a variable called x. If the value of x is higher than 10, lower than 0, or not a number, we are going to throw an error. The error is then caught by the catch argument and the proper error message is displayed:

<html>
<body>
<script type="text/javascript">
var x=prompt("Enter a number between 0 and 10:","");
try
{
if(x>10)
{
throw "Err1";
}
else if(x<0)
{
throw "Err2";
}
else if(isNaN(x))
{
throw "Err3";
}
}
catch(er)
{
if(er=="Err1")
{
alert("Error! The value is too high");
}
if(er=="Err2")
{
alert("Error! The value is too low");
}
if(er=="Err3")
{
alert("Error! The value is not a number");
}
}
</script>
</body>
</html>


Functions

 

With functions, you can give a name to a whole block of code, allowing you to reference it from anywhere in your program. JavaScript has built-in functions for several predefined operations. Here are three some functions.
  • alert("message")
  • confirm("message")
  • prompt("message")

Function Example
 
<html>
<head>
<script type="text/javascript">
function show_prompt()
{
var name=prompt("Please enter your name","Harry Potter");
if (name!=null && name!="")
{
document.write("Hello " + name + "! How are you today?");
}
}
</script>
</head>
<body>
<input type="button" onclick="show_prompt()" value="Show prompt box" />
</body>
</html>
output:

User-Defined Functions
 
With user-defined functions, you can name a block of code and call it when you need it. You define a function in the HEAD section of a web page. It is defined with the function keyword, followed by the function name and any arguments.

function functionName(argument)
{
statements
 }
 Example:

<html>
<head>
<script type="text/javascript">
function displaymessage()
{
alert("Hello World!");
}
</script>
</head>
<body>
<form>
<input type="button" value="Click me!" onclick="displaymessage()" />
</form>
</body>
</html>


Output:


The return Statement
 
The return statement is used to specify the value that is returned from the function. So, functions that are going to return a value must use the return statement. The example below returns the product of two numbers (a and b):

<html>
<head>
<script type="text/javascript">
function product(a,b)
{
return a*b;
}
</script>
</head>
<body>
<script type="text/javascript">
document.write(product(4,3));
</script>
</body>
</html>
output:


The Scope of JavaScript Variables (Life time of variable)

If you declare a variable within a function, the variable can only be accessed within that function.
When you exit the function, the variable is destroyed. These variables are called local variables. You
can have local variables with the same name in different functions, because each is recognized only
by the function in which it is declared.

If you declare a variable outside a function, all the functions on your page can access it. The lifetime
of these variables starts when they are declared, and ends when the page is closed.

Explore more about java script events here.