Posts

Home Lists+

I’m Making Some Simple But Useful Online Tools for Developers

Hey guys! How are you? Today I’m sharing these three simple but useful (well, at least for me) online tools for developers like you.

I developed it using Bootstrap to have a decent user interface, .htaccess for clean URL location, PHP for input processing and of course, jQuery AJAX requests to prevent reloading the whole page get what you want faster. It’s really fun to built knowing that other developers might find it useful too.

simple online tools for developers

For now we only have three tools, but I’m planning to make more. But first, let’s take a look!

Read more

Home Android

Saying Goodbye to Google Blogger

Hey guys! How are you? I’m so happy today. I’m almost done re-creating this website. Why? I switched from Blogger to WordPress! Yes, you read it right.

I love WordPress!

Read more

Home jQuery

jQuery UI Autocomplete Example

We, the developers, want to help our users search for the data they are looking for – in an easy manner. This jQuery UI autocomplete tutorial will help you achieve it!

Having an autocomplete feature in our search box is really good for the user experience, it is like having a user assistant while he is trying to search.

Our code for today will make use of a textbox where the user can type his search term. The sample data we use are person names (firstname and lastname).

So, when the user types a name, our program will suggest some names that might be what the user is looking for.

Contents:

1.0 Project Files
2.0 Database
3.0 The User Interface
4.0 Getting Search Results
4.1 JSON Data
5.0 Adding Some Style
6.0 Download Source Code

1.0 Project Files

Our code for today includes the following files:

libs/db_connect.php
images/ajax-loader.gif
css/style.css
index.php
results.php

2.0 Database

The table structure used and some sample data were provided below:

--
-- Table structure for table `users`
--

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `firstname` varchar(32) NOT NULL,
  `lastname` varchar(32) NOT NULL,
  `gender` varchar(6) NOT NULL,
  `email` varchar(32) NOT NULL,
  `username` varchar(32) NOT NULL,
  `password` varchar(32) NOT NULL,
  `created` datetime NOT NULL,
  `modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=76 ;

--
-- Dumping data for table `users`
--

INSERT INTO `users` (`id`, `firstname`, `lastname`, `gender`, `email`, `username`, `password`, `created`, `modified`) VALUES
(49, 'Justine', 'Bongola', 'Male', 'justine@coanmail.com', 'jaja', 'jaja123', '0000-00-00 00:00:00', '2013-03-03 14:06:03'),
(51, 'Lourd', 'De Veyra', 'Male', 'lourd@coanmail.com', 'lourd', 'lourd123', '0000-00-00 00:00:00', '2013-03-03 14:06:03'),
(73, 'Mike', 'Dalisay', '', '', 'ninjazhai', 'allisfine', '0000-00-00 00:00:00', '2013-05-12 06:39:04'),
(74, 'Darwin', 'Dalisay', '', '', 'dada', 'dada123', '0000-00-00 00:00:00', '2013-05-12 06:39:24'),
(75, 'Marykris', 'Dalisay', '', '', 'mary143', 'mary123', '0000-00-00 00:00:00', '2013-05-13 16:51:14');

Here’s how we connect to the database, just change the variable values that will make you connected to your database.

<?php
$host = "yourHost";
$db_name = "yourDatabaseName";
$username = "yourDatabaseUsername";
$password = "yourPassword";

try {
    $con = new PDO("mysql:host={$host};dbname={$db_name}", $username, $password);
}catch(PDOException $exception){ //to handle connection error
    echo "Connection error: " . $exception->getMessage();
}
?>

3.0 The User Interface

index.php – this is where the user can find the textbox, tries to type on it and our system suggests some keywords as autocomplete, and this is also where we include our jQuery UI theme and jQuery scripts.

<!DOCTYPE HTML>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>jQuery UI auto-complete tutorial live demo</title>

		<!-- include the jquery ui theme css and your own css -->
		<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.0/themes/smoothness/jquery-ui.css" />
		<link rel="stylesheet" href="css/style.css" />

    </head>
<body>

<!--
	-this is our text box, we didn't use type='text' but type='search' instead
	 to have a clear (x) function in case a user wants to easily remove what's in the textbox
	-placeholder='Search firstname or lastname' - is an HTML5 attribute the can give your
	 users a clue on what to search or type in the textbox
-->
<div>Try to type "dalisay" below:</div>
<input type='search' id='nameSearch' placeholder='Search firstname or lastname' />

<!--
	-now we'll include the jQuery and jQuery UI libraries
-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.0/jquery-ui.min.js"></script>

<script type="text/javascript">
$(document).ready(function(){

	// this is how to add autocomplete functionality in a textbox
	// source:'results.php' - where it will pass the search term and generates the JSON data
	// minLength:1 - how many characters user enters in order to start search
	$('#nameSearch').autocomplete({

		source:'results.php',
		minLength:1,
		select: function(event, ui){

			// just in case you want to see the ID
			var accountVal = ui.item.value;
			console.log(accountVal);

			// now set the label in the textbox
			var accountText = ui.item.label;
			$('#nameSearch').val(accountText);

			return false;
		},
		focus: function( event, ui ) {
			// this is to prevent showing an ID in the textbox instead of name
			// when the user tries to select using the up/down arrow of his keyboard
			$( "#nameSearch" ).val( ui.item.label );
			return false;
		},

   });

});
</script>

</body>
</html>

4.0 Getting Search Results

results.php – this is where the search term were passed, queries the database and generates the JSON data needed to show the autocomplete terms in the user interface.

<?php
// connect to the database
include "libs/db_connect.php";

// get the search term
$search_term = isset($_REQUEST['term']) ? $_REQUEST['term'] : "";

// write your query to search for data
$query = "SELECT 
            id, firstname, lastname 
        FROM 
            users 
        WHERE 
            firstname LIKE "%{$search_term}%" OR 
            lastname LIKE "%{$search_term}%" 
        LIMIT 0,10";

$stmt = $con->prepare( $query );
$stmt->execute();

// get the number of records returned
$num = $stmt->rowCount();

if($num>0){ 

    // this array will become JSON later
    $data = array();

    // loop through the returned data
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
        extract($row);

        $data[] = array(
            'label' => $firstname . " " . $lastname,
            'value' => $id
        );
    }

    // convert the array to JSON
    echo json_encode($data);

}

//if no records found, display nothing
else{
    die();
}
?>

4.1 Wondering how the returned JSON data looks like?

[
  {
    "label": "Mike Dalisay",
    "value": "28"
  },
  {
    "label": "Darwin Dalisay",
    "value": "40"
  }
]

You can also take a look at your own JSON data by browsing your results.php?term=your_search_term

5.0 Adding Some Styles

style.css – this is where you can change the loading GIF image and add some style to our textbox.

.ui-autocomplete-loading {
    /* you can replace ajax-loader.gif with another gif image you want for your design */
    background: white url('images/ajax-loader.gif') right center no-repeat;
}

/* some style for our textbox */
#nameSearch{
    padding:.5em;
    width:20em;
}

6.0 Download Source Code

You can download all the code used in this tutorial for only $9.99 $5.55!

THANK YOU!

has been added to your cart!

Powered by Easy Digital Downloads

Thank you!

have been added to your cart!

Powered by Easy Digital Downloads

Congratulations! Now you can make your users happier by this search assistant feature, and as always, thanks for reading!

Home PHP

Generating JSON String with PHP

Today I’m going to share this code I used to generate a JSON string with data from MySQL database.

For those not yet familiar, JSON is a lightweight data interchange format (like XML but it is lightweight).

It has been used by companies like Google and Facebook in their APIs.

Recently, I needed a JSON string to get data from the web to the Android app I’m working on.

The PHP file gets a parameter company_id to select few data related to a company.

Please note that this is not a production ready code, but is very useful to get you started and can serve as quick reference.

Read more

Home jQuery

jQuery UI Dialog Example with Source Code Downloads

jquery-ui-tutorial
Dialog boxes, modals, confirm boxes can also be done with awesomeness in jQuery UI. In this post we are going to take a look at the three jQuery UI dialog code examples I commonly use in my projects. Live demos and code download button links were also provided below. Keep on reading!

jquery ui dialog example

In this post we will cover the following:

1. jQuery UI Basic Modal
2. jQuery UI Confirm Dialog
3. jQuery UI Load Content from URL
3.1 Save the loaded URL content
3.2 Destroy or remove the loaded URL content
4. Download Source Code

Our jQuery, jQuery UI and jQuery UI theme are hosted by Google. You can choose your jQuery UI theme here.

1. jQuery UI Basic Modal

I love modals, or a “modal window” or “modal dialog”, it is a child window that pops up in your application that requires a user interaction. It can display information, gives you choices or even contain an HTML form!

In jQuery UI, when you set modal: true parameter, it will be able to dim the background of your page when showing the dialog. If it is set to false, the background will remain as is.

This is useful when a client (like mine) did not like dimming the background. But I like dimming the background when showing a dialog, so in our code below, we’ll set the modal to true.

basic-dialog.html code:

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>jQuery UI Dialog Modal Example by codeofaninja.com</title>
        
        <!-- include you jquery ui theme -->
        <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/smoothness/jquery-ui.css" />
        
        <!-- you can have your own style -->
        <style>
        body {
            font-family: "Trebuchet MS", "Helvetica", "Arial",  "Verdana", "sans-serif";
            font-size: .8em;;
        }
        
        /* dialog div must be hidden */
        #basicModal{
            display:none;
        }
        </style>
        
    </head>
<body>

<!-- sample content in your page -->
<div>You can click the button to show the basic jQuery UI dialog box.</div>
<input type='button' value='Show basic dialog!' id='showDialog' />

<!-- 
    -this is the actual dialog, yes, it is included in your html body, it is just hidden
    -you can set the dialog title via the 'title' tag 
-->
<div id="basicModal" title="A message from codeofaninja.com">
    Thank you for visiting codeofaninja.com!
</div>

<!-- include the jquery library -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<!-- include the jquery ui library -->
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>

<script>
// show the dialog on click of a button
$( "#showDialog" ).click(function(){

    /* -select the div you want to be a dialog modal, in our case it is 'basicModal'
       -you can add parameters such as width, height, title, etc. */
    $( "#basicModal" ).dialog({
        modal: true,
        height: 300,
        width: 400
    });
    
});
</script>

</body>
</html>

2. jQuery UI Confirm Dialog

Instead of the old JavaScript confirm dialog box, I use jQuery UI. This is for a better user interface and to control the number of buttons and their labels, instead of just “ok” and “cancel”.

confirm-dialog.html code:

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>jQuery UI Confirm Dialog Example by codeofaninja.com</title>
        
        <!-- include you jquery ui theme -->
        <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/smoothness/jquery-ui.css" />
        
        <!-- you can have your own style -->
        <style>
        body {
            font-family: "Trebuchet MS", "Helvetica", "Arial",  "Verdana", "sans-serif";
            font-size: .8em;;
        }
        
        /* dialog div must be hidden */
        #basicModal{
            display:none;
        }
        </style>
        
    </head>
<body>

<!-- sample content in your page -->
<div>You can click the button to show the basic jQuery UI dialog box.</div>
<input type='button' value='Show confirm dialog!' id='showDialog' />

<!-- 
    -this is the actual dialog, yes, it is included in your html body, it is just hidden
    -we did not set the dialog 'title' here, we set it in the js parameter
-->
<div id="basicModal">
    Go to codeofaninja.com?
</div>

<!-- include the jquery library -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<!-- include the jquery ui library -->
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>

<script>
// show the dialog on click of a button
$( "#showDialog" ).click(function(){

    /* select the div you want to be a dialog, in our case it is 'basicModal'
    you can add parameters such as width, height, title, etc. */
    $( "#basicModal" ).dialog({
        modal: true,
        title: "Are you sure?",
        buttons: {
            "YES": function() {
                window.open("https://codeofaninja.com/", '_blank');
            },
            "NO": function() {
                $( this ).dialog( "close" );
            }
        }
    });
    
});
</script>

</body>
</html>

3. jQuery UI Load Content from URL

URL to be loaded must be in the same domain or subdomain name. If you really want to load from different domain, use iframes, example code here.

In this example, we will use sample_page.php as the file of URL to be loaded, it has the following contents:

<?php
echo "Here's the sample page loaded.<br /><br />";
echo "Only a page from the same domain/subdomain can be loaded using this technique.<br /><br />";
echo "If you really want to load a page from another domain/subdomain, use an iframe.<br /><br />";
echo "<a href='http://stackoverflow.com/a/14570255/903298' target='_blank'>Example code here</a>";
?>

3.1 Save the loaded URL content

Here’s is the default behaviour of the jQuery UI dialog, it appends the URL content to the HTML body.

load-url-dialog.html code:

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>jQuery UI Dialog Example by codeofaninja.com</title>
        
        <!-- include you jquery ui theme -->
        <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/smoothness/jquery-ui.css" />
        
        <!-- you can have your own style -->
        <style>
        body {
            font-family: "Trebuchet MS", "Helvetica", "Arial",  "Verdana", "sans-serif";
            font-size: .8em;;
        }
        
        /* dialog div must be hidden */
        #basicModal{
            display:none;
        }
        </style>
        
    </head>
<body>

<!-- sample content in your page -->
<div>You can click the button to show the basic jQuery UI dialog box.</div>
<input type='button' value='Show basic dialog!' id='showDialog' />

<!-- 
    -this time, we don't have the dialog html in the body, it is in another url
    -we use the image loader to add some good effect when the system loads the url (after user click)
 -->
<img src="images/ajax-loader.gif" id="imgLoader" style="display:none;" />

<!-- include the jquery library -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<!-- include the jquery ui library -->
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>

<script>
// show the dialog on click of a button
$( "#showDialog" ).click(function(){

    /* here you can specify the url */
    var url = "sample-page.php";
    
    /* container of the content loaded from a url */
    var tag = $("<div></div>");
    
    console.log("url: " + url);
    
    /* show the image loader */
    $('#imgLoader').show();
    
    $.ajax({
        url: url,
        success: function( data ) {
        
            tag.html(data).dialog({
                modal: true,
                title: "Content is loaded from a URL!",
                width: 600,
                height: 450
            }).dialog('open');

            /* hide the image loader */
            $('#imgLoader').hide();
            console.log("success!");
        }
    });
    
});
</script>

</body>
</html>

To prove that the URL contents will be appended in the body of your HTML document, see the screenshot below, I used Google Chrome’s inspect element to view this live source code of the current page.

jquery ui dialog not destroyed or removed

LIVE DEMO

3.2 Destroy or remove the loaded URL content

By default, the jQuery UI append the URL contents in your HTML body, if you want to prevent it, we can we add the close parameter on the dialog and use the jQuery remove() method.

load-url-destroy-dialog.html code:

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>jQuery UI Dialog Example by codeofaninja.com</title>
        
        <!-- include you jquery ui theme -->
        <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/smoothness/jquery-ui.css" />
        
        <!-- you can have your own style -->
        <style>
        body {
            font-family: "Trebuchet MS", "Helvetica", "Arial",  "Verdana", "sans-serif";
            font-size: .8em;;
        }
        
        /* dialog div must be hidden */
        #basicModal{
            display:none;
        }
        
        </style>
        
    </head>
<body>

<!-- sample content in your page -->
<div>You can click the button to show the basic jQuery UI dialog box.</div>
<input type='button' value='Show basic dialog!' id='showDialog' />

<!-- 
    -this time, we don't have the dialog html in the body, it is in another url
    -we use the image loader to add some good effect when the system loads the url (after user click)
-->
<img src="images/ajax-loader.gif" id="imgLoader" style="display:none;" />

<!-- include the jquery library -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<!-- include the jquery ui library -->
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>

<script>
// show the dialog on click of a button
$( "#showDialog" ).click(function(){

    /* here you can specify the url */
    var url = "sample-page.php";
    
    /* container of the content loaded from a url */
    var tag = $("<div></div>");
    
    /* show the image loader */
    $('#imgLoader').show();
    
    $.ajax({
        url: url,
        success: function( data ) {
        
            tag.html(data).dialog({
                modal: true,
                title: "Content is loaded from a URL!",
                width: 600,
                height: 450,
                close: function(){
                     tag.dialog('destroy').remove()
                }
            }).dialog('open');

            /* hide the image loader */
            $('#imgLoader').hide();
            console.log("success!");
        }
    });
    
});
</script>

</body>
</html>

To prove that the URL content did not append in the HTML body, see the screenshot of the live source code below.

jquery ui dialog was destroyed and removed

4.0 Download Source Code

You can download all the code used in this tutorial for only $9.99 $5.55!

THANK YOU!

has been added to your cart!

Powered by Easy Digital Downloads

Thank you!

have been added to your cart!

Powered by Easy Digital Downloads

If you think of any other jQuery UI dialog example, please drop it in the comments section below, we’ll try our best to add it in this post. Thanks!

Home jQuery

jQuery AJAX Post Example with PHP and JSON

RELATED TUTORIAL: PHP, MySQL and AJAX CRUD Tutorial – Step by Step Guide!

Today I’m gonna give you some code examples on how you can post a form and JSON data using jQuery AJAX.

A PHP file will receive the posted data and print the response.

I think this is one of the most useful code when you’re coding with jQuery, especially if you’re building a web app with modules that deals with so many forms or post request in one page.

Why use jQuery for AJAX requests?

I think it is to make things easier, have shorter more readable code. You can see some code examples of doing an AJAX request without jQuery here and here.

As you can see on those links, some tasks include creating a catch for different browser XMLHttpRequest, opening the url, checking if the request is in ready state and setting the request header.

jQuery solves this by having a short, more readable syntax.

Let’s code!

Alright, now we’ll get straight to the code examples. We’re gonna have three example below, continue to read!

1. jQuery post form data using .ajax() method

This is a great way to show someone that you are now an AJAX programmer. Because of this .ajax() piece of code in your HTML page, you may now face the world with confidence and with a beautiful smile in your face.

Just kidding. But seriously, this piece of code is useful.

<html>
    <head>
        <title>jQuery post form data using .ajax() method by codeofaninja.com</title>
        
    </head>
<body>

<h1>jQuery post form data using .ajax() method</h1>
<div>Fill out and submit the form below to get response.</div>

<!-- our form -->   
<form id='userForm'>
    <div><input type='text' name='firstname' placeholder='Firstname' /></div>
    <div><input type='text' name='lastname' placeholder='Lastname' /></div>
    <div><input type='text' name='email' placeholder='Email' /></div>
    <div><input type='submit' value='Submit' /></div>
</form>

<!-- where the response will be displayed -->
<div id='response'></div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js "></script>
<script>
$(document).ready(function(){
    $('#userForm').submit(function(){
    
        // show that something is loading
        $('#response').html("<b>Loading response...</b>");
        
        /*
         * 'post_receiver.php' - where you will pass the form data
         * $(this).serialize() - to easily read form data
         * function(data){... - data contains the response from post_receiver.php
         */
        $.ajax({
            type: 'POST',
            url: 'post_receiver.php', 
            data: $(this).serialize()
        })
        .done(function(data){
            
            // show the response
            $('#response').html(data);
            
        })
        .fail(function() {
        
            // just in case posting your form failed
            alert( "Posting failed." );
            
        });

        // to prevent refreshing the whole page page
        return false;

    });
});
</script>

</body>
</html>

2. jQuery post form data using .post() method

.post() method has a more descriptive syntax, it is a shorthand of .ajax() method above. See how it was commonly used with the code below:

<html>
    <head>
        <title>jQuery post form data using .post() method by codeofaninja.com</title>
        
    </head>
<body>

<h1>jQuery post form data using .post() method</h1>
<div>Fill out and submit the form below to get response.</div>

<!-- our form -->   
<form id='userForm'>
    <div><input type='text' name='firstname' placeholder='Firstname' /></div>
    <div><input type='text' name='lastname' placeholder='Lastname' /></div>
    <div><input type='text' name='email' placeholder='Email' /></div>
    <div><input type='submit' value='Submit' /></div>
</form>

<!-- where the response will be displayed -->
<div id='response'></div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js "></script>
<script>
$(document).ready(function(){
    $('#userForm').submit(function(){
    
        // show that something is loading
        $('#response').html("<b>Loading response...</b>");
        
        /*
         * 'post_receiver.php' - where you will pass the form data
         * $(this).serialize() - to easily read form data
         * function(data){... - data contains the response from post_receiver.php
         */
        $.post('post_receiver.php', $(this).serialize(), function(data){
            
            // show the response
            $('#response').html(data);
            
        }).fail(function() {
        
            // just in case posting your form failed
            alert( "Posting failed." );
            
        });

        // to prevent refreshing the whole page page
        return false;

    });
});
</script>

</body>
</html>

3. jQuery post JSON data using .post() method

Sometimes you don’t want to post data from an HTML form. You can do it by creating a JSON string, and here’s how you’ll be able to post it.

<html>
    <head>
        <title>jQuery post JSON data using .post() method by codeofaninja.com</title>
        
    </head>
<body>

<h1>jQuery post JSON data using .post() method</h1>
<div>Click the button below to get response.</div>

<!-- our form -->   
<input type='button' value='Post JSON' id='postJson' />

<!-- where the response will be displayed -->
<div id='response'></div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js "></script>
<script>
$(document).ready(function(){

    $('#postJson').click(function(){
    
        // show that something is loading
        $('#response').html("<b>Loading response...</b>");
        
        /*
         * 'post_receiver.php' - where you will pass the form data
         * $(this).serialize() - to easily read form data
         * function(data){... - data contains the response from post_receiver.php
         */
        $.post('post_receiver.php', { user_id: "143", username: "ninjazhai", website: "https://codeofaninja.com/" }, function(data){
            
            // show the response
            $('#response').html(data);
            
        }).fail(function() {
        
            // just in case posting your form failed
            alert( "Posting failed." );
            
        });

        // to prevent refreshing the whole page page
        return false;

    });
});
</script>

</body>
</html>

Posting a JSON string using the .ajax() method is also possible, you can just replace the serialize() part with your JSON string.

Posted Data

Where did the posted data go? To the file where you want the posted data to be processed! But in our example, we just print the posted data. post_receiver.php has the following code

<?php
echo "<pre>";
    print_r($_POST);
echo "</pre>";
?>

Download Source Code
You can download all the code used in this tutorial for only $9.99 $5.55!

THANK YOU!

has been added to your cart!

Powered by Easy Digital Downloads

Thank you!

have been added to your cart!

Powered by Easy Digital Downloads

If you want to learn how to create, read, update and delete data with AJAX, go ahead and learn from our AJAX CRUD Tutorial Using jQuery, JSON and PHP – Step by Step Guide!.

Related Tutorials

Thank you for learning our post about jQuery AJAX Post Example with PHP and JSON!

RELATED TUTORIAL: PHP, MySQL and AJAX CRUD Tutorial – Step by Step Guide!

Home Lists+

12 jQuery Questions and Answers You Should Be Reading on StackOverflow

Hi guys! Below are twelve of the jQuery related questions and answers on StackOverflow that I found very useful during development. I opted to compile them here because I feel good reading those brilliant questions and answers by coders from around the world. Enjoy!

  1. How would I know if an element is hidden?
  2. Sometimes you want some elements of your page to be visible, and if it is not visible, you want to tell the user about it. For example, a user must have a selection of data first before proceeding to new operation. If he has no selection (div is hidden), you can do a prompt that he must select something.

  3. How do I get selected text in select box?
  4. Ah, a drop-down list? Link # 2 above shows you how to get the user drop down list selection.

  5. How to redirect a page?
  6. Useful if you want to your users to see a page after an AJAX request, or you just want them to be redirected. I’ve written another example here, jQuery: Redirect onClick

  7. How would I know if a checkbox is checked or unchecked?
  8. For example, you want to enable a delete button if the user selected at least one data to delete, else, the delete button is disabled. I’ve written another example here: Check or Uncheck Checkboxes with jQuery And Get Selected with PHP

  9. How to select a child element?
  10. Teaches us how to select a child element and do it with faster performance (see the comment by Paul Irish).

  11. event.preventDefault() vs. return false
  12. I use return false; when I want to prevent a page refresh after clicking a submit button and doing an AJAX request.

  13. Example of using jQuery .closest() method.
  14. I use jQuery .closest() method on selecting an element within a table with several rows. I probably have to write an example in another blog post, ha!

  15. How would I know the existence of an element?
  16. Useful if you want to perform something if an element exists in your page. The faster way is using if ($(selector).length) {}

  17. How would I know which radio button is selected?
  18. This is how you will know if a user is a male or female, using jQuery!

  19. How to select multiple classes?
  20. Sometimes you want to to something to multiple classes at once. There’s another example here.

  21. How to select an element by its name, not by class or id?
  22. If you’re more familiar with an element’s name or don’t want to add a class or id name, you can use this cool technique.

  23. What if Google hosted jQuery is blocked?
  24. In some countries, Google’s domain name is banned. So if you are using a Google hosted jQuery library, you’re site won’t work. Link # 12 above shows you the fall back.

This can be the first part of the list, you can add more in the comments section below, or on our Facebook, Twitter or Google+!
And as always, thanks for reading!

Home PHP

Email Activation Code in PHP

Email Activation Code in PHP

Email activation or verification is one requirement when you’re building an app with a membership feature. Our Email Activation Code in PHP will help you with that!

This is one way to detect if there’s really a person behind the submitted email address. An email address is considered invalid if no person was able to open it and click the activation link.

Although nowadays, there are some alternative ways to verify the validity of an email address or user. Some systems prefer the old school method, like what this post covers.

OAuth

The alternative way I was talking about is by using a social network login. Facebook, Twitter, Google+ and even Microsoft is providing something called an OAuth (Open Authorization) login.

In simple scenario, have you ever seen a “Login with Facebook” button? We see one in StackOverflow login:

oauth-login-email-validation

Unfortunately, we don’t cover OAuth login in this post.

Basic Flow

The following steps shows the basic flow how email activation works.

  1. User fills up your sign up or registration form and submit it to the system.
  2. System generates unique activation code which acts like a “key”
  3. System sends a link with the activation code to the email provided during the sign up form.
  4. User opens his email inbox, found the system email and click the link with the activation code. This is like using the “key” to “unlock the door” which represents your application.
  5. User was sent to a link saying ‘email was activated’

Where are these happening?

To give you a clearer picture where in our code the steps above happens:

Steps 1 to 3 happens in sign_up.php.

Step 4 happens in the user’s email provider such as GMail, Y! Mail, etc. User should receive something like this:

email-verification-link-sent

Step 5 happens in our activate.php

Let’s Code!

Alright, so the technologies used in this code are mostly PHP and MySQL.

Create your database and name it ’email_activation_db’. Here’s the database table structure that can be used, we name it as the ‘users’ table.

CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `nickname` varchar(32) NOT NULL,
  `email` varchar(264) NOT NULL,
  `verified` int(11) NOT NULL COMMENT '0=no, 1=yes',
  `verification_code` varchar(264) NOT NULL,
  `created` datetime NOT NULL,
  `modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `users` (`id`, `nickname`, `email`, `verified`, `verification_code`, `created`, `modified`) VALUES
(135, '', 'ninjazhai30@gmail.com', 1, '2e729fe3ded03c139b289213db2b3159', '2016-08-13 16:42:28', '2016-08-13 08:42:46');

libs/db_connect.php – for database connection, this file has the following code:

<?php
$host = "localhost";
$db_name = "email_activation_db";
$username = "root";
$password = "";

try {
	$con = new PDO("mysql:host={$host};dbname={$db_name}", $username, $password);
}catch(PDOException $exception){ //to handle connection error
    echo "Connection error: " . $exception->getMessage();
}
?>

sign_up.php – where the sign up form and processing of user input is located. The following code is inside sign_up.php file.

<?php
// if the sign up form was submitted
if($_POST){

	$email = isset($_POST['email']) ? $_POST['email'] : "";

	// posted email must not be empty
	if(empty($email)){
		echo "<div>Email cannot be empty.</div>";
	}

	// must be a valid email address
	else if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
		echo "<div>Your email address is not valid.</div>";
	}

	else{

		include 'libs/db_connect.php';

		// check first if record exists
		$query = "SELECT id FROM users WHERE email = ? and verified = '1'";
		$stmt = $con->prepare( $query );
		$stmt->bindParam(1, $email);
		$stmt->execute();
		$num = $stmt->rowCount();

		if($num>0){
			echo "<div>Your email is already activated.</div>";
		}

		else{

			// check first if there's unverified email related
			$query = "SELECT id FROM users WHERE email = ? and verified = '0'";
			$stmt = $con->prepare( $query );
			$stmt->bindParam(1, $email);
			$stmt->execute();
			$num = $stmt->rowCount();

			if($num>0){

				// you have to create a resend verification script
				echo "<div>Your email is already in the system but not yet verified.</div>";
			}

			else{

				// now, compose the content of the verification email, it will be sent to the email provided during sign up
				// generate verification code, acts as the "key"
				$verificationCode = md5(uniqid("yourrandomstringyouwanttoaddhere", true));

				// send the email verification
				$verificationLink = "https://codeofaninja.com/demos/php-examples/email-activation-php-script/activate.php?code=" . $verificationCode;

				$htmlStr = "";
				$htmlStr .= "Hi " . $email . ",<br /><br />";

				$htmlStr .= "Please click the button below to verify your subscription and have access to the download center.<br /><br /><br />";
				$htmlStr .= "<a href='{$verificationLink}' target='_blank' style='padding:1em; font-weight:bold; background-color:blue; color:#fff;'>VERIFY EMAIL</a><br /><br /><br />";

				$htmlStr .= "Kind regards,<br />";
				$htmlStr .= "<a href='https://codeofaninja.com/' target='_blank'>The Code of a Ninja</a><br />";


				$name = "The Code of a Ninja";
				$email_sender = "no-reply@codeofaninja.com";
				$subject = "Verification Link | The Code Of A Ninja | Subscription";
				$recipient_email = $email;

				$headers  = "MIME-Version: 1.0\r\n";
				$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
				$headers .= "From: {$name} <{$email_sender}> \n";

				$body = $htmlStr;

				// send email using the mail function, you can also use php mailer library if you want
				if( mail($recipient_email, $subject, $body, $headers) ){

					// tell the user a verification email were sent
					echo "<div id='successMessage'>A verification email were sent to <b>" . $email . "</b>, please open your email inbox and click the given link so you can login.</div>";


					// save the email in the database
					$created = date('Y-m-d H:i:s');

					//write query
					$query = "INSERT INTO
								users
							SET
								email = ?,
								verification_code = ?,
								created = ?,
								verified = '0'";

					$stmt = $con->prepare($query);

					$stmt->bindParam(1, $email);
					$stmt->bindParam(2, $verificationCode);
					$stmt->bindParam(3, $created);

					// Execute the query
					if($stmt->execute()){
						// echo "<div>Unverified email was saved to the database.</div>";
					}else{
						echo "<div>Unable to save your email to the database.";
						//print_r($stmt->errorInfo());
					}

				}else{
					die("Sending failed.");
				}
			}


		}

	}

}

// show your sign up or registration form
echo "<form action='" . $_SERVER['PHP_SELF'] . "' method='post'>";
	echo "<input type='email' name='email' placeholder='Enter your email address to subscribe' required />";
	echo "<input type='submit' value='Subscribe' />";
echo "</form>";
?>

For sending the verification email, we used the PHP mail() function but you can also use a library like PHPMailer if you want to use SMTP such as of GMail.

activate.php – it has one job, update the the unverified to verified email address.

<?php
include 'libs/db_connect.php';

// check first if record exists
$query = "SELECT id FROM users WHERE verification_code = ? and verified = '0'";
$stmt = $con->prepare( $query );
$stmt->bindParam(1, $_GET['code']);
$stmt->execute();
$num = $stmt->rowCount();

if($num>0){

	// update the 'verified' field, from 0 to 1 (unverified to verified)
	$query = "UPDATE users
				set verified = '1'
				where verification_code = :verification_code";

	$stmt = $con->prepare($query);
	$stmt->bindParam(':verification_code', $_GET['code']);

	if($stmt->execute()){
		// tell the user
		echo "<div>Your email is valid, thanks!. You may now login.</div>";
	}else{
		echo "<div>Unable to update verification code.</div>";
		//print_r($stmt->errorInfo());
	}

}else{
	// tell the user he should not be in this page
	echo "<div>We can't find your verification code.</div>";
}
?>

Live Demo

Please note that this demo is live. If you enter your email and click the subscribe button, you will receive an email with the activation link. If you click it, you will be subscribed here in our code blog.

Download Email Activation Code in PHP

You can get the source code by following the whole, well detailed tutorial above.

But isn’t it more convenient if you can just download the complete source code we used, and play around it?

The source code of this tutorial is part of our 30+ useful Web Programming source code package. Each item in the package has its own tutorial like the one above.

If you are just starting out to learn web programming and serious about learning more, this is the right package for you. Click green button below to see the what is included in the package and download it there.


Need email activation code only? But the code now using the green button below.

Related Source Code

You can download our PHP Login System & User Management Module as well. This source code is about PHP Login System.

It will help you understand how to login and logout functionality works. Sign up email verification, user registration, and forgot password features are included as well.

Thanks for studying our email activation code in PHP!