Home Lists+

12 Animated Web Demos Made Only with HTML and CSS3

You guys seems to like the first one, so here’s another one for you! HTML and CSS are really amazing technologies that the humanity has to celebrate. Okay, that maybe exaggerated, but here are a dozen more amazing web demos with source code that might inspire you to be a better web developer, I was able to put them together while I was camping with a tent from Survival Cooking. I hope you guys get some help out of them. Just click the linked title of each item below, enjoy!

1. Melting Cube

12 Animated Web Demos Made Only with HTML and CSS3

2. Ironman Login Form

ironman-login-form

3. Acromantula

acromantula

4. Beach Ball of Death

beach-ball-of-death

5. CSS Balls

css-balls-css3

6. BoldMedia Logo Variation

boldmedia-logo

7. Become a Traveller Today

become-a-traveller

8. Color Picker

color-picker

9. Animated Atom

animated-atom

10. Funny Loading

funny-loading

11. Social Flip Cards

social-flip-cards

12. Beating Heart

beating-heart

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!

Home Facebook

Fixed: Cannot send session cache limiter – headers already sent

Okay, so many of you guys still ask me about how to fix these warning messages in our Facebook scripts. Today I'm going to give you two possible fixes that you can do. By the way, here's the warning message we want to remove:

Fix it by adding a session_start()

You can fix it by adding a session_start() on top of your PHP file, just right after your first line <?php tag. It looks like this:

Fix it by moving Facebook instance

You can fix it by moving the Facebook class and instance code on top of your PHP file. It would look like this:

If none of them worked, you can read more here.