Posts

Home jQuery

jQuery Redirect onClick Event (New or Same Window)

jQuery Quick Tip: This time I'm gonna show you how to redirect a page to another page or website when a user selected a value from a dropdown list and clicked a button.

We have two buttons here, the first one will redirect you to a website in the same page and the second one will redirect you in new tab (or window, in safari.)

jquery redirect onclick event to a page

Here's the live demo and code:

jQuery Redirect onClick Step by Step

Step 1: Prepare basic HTML page code.

<!doctype html>
<html>
   <head>
      <title>jQuery Redirect OnClick</title>
   </head>
<body>

</body>
</html>

Step 2: Put a drop down list of URLs you want your page to redirect.

<!--
  Here are our form elements,
  we have the select box / dropdown list
  which contains our URLs or links
-->
<select id="websites" style="width:200px;">
  <option value="http://demos.codeofaninja.com/tutorials/jQuery/get_dynamic_div_height.php">Get Dynamic</option>
  <option value="http://google.com">Google</option>
  <option value="https://codeofaninja.com">Blog</option>
  <option value="http://apple.com">Apple</option>
</select>

Step 3: Put the buttons for opening the URL in the same window or another window or tab.

<!--
  And our buttons, the first one is "Open In Same Window"
  which opens the link selected on the dropdown in the same window.
 
  The other button is the "Open In New Tab" which opens the link in
  new tab (or window in safari)
-->
<input type="button" value="Open In Same Window" id="open_same_window" />
<input type="button" value="Open In New Tab" id="open_new_tab" />

Step 4: Include jQuery library and basic jQuery code.

<!-- include our library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type='text/javascript'>
$(document).ready(function() {

});
</script>

Step 5: Inside the basic jQuery code $(document).ready(function() {..., put the button click event triggers.

//this will be triggered when the first button was clicked
$("#open_same_window").click(function(){
  //this will find the selected website from the dropdown
  var go_to_url = $("#websites").find(":selected").val();
 
  //this will redirect us in same window
  document.location.href = go_to_url;
});

//this will be triggered when the second button was clicked
$("#open_new_tab").click(function(){
  //this will find the selected website from the dropdown
  var go_to_url = $("#websites").find(":selected").val();
 
  //this will redirect us in new tab
  window.open(go_to_url, '_blank');
});

Complete jQuery Redirect onClick Page

 <html>
   <head>
      <title>jQuery Redirect OnClick</title>
   </head>
<body>

<div style="margin:200px 200px;">
   <!--
      Here are our form elements,
      we have the select box / dropdown list
      which contains our URLs or links
   -->
   <select id="websites" style="width:200px;">
      <option value="http://demos.codeofaninja.com/tutorials/jQuery/get_dynamic_div_height.php">Get Dynamic</option>
      <option value="http://google.com">Google</option>
      <option value="https://codeofaninja.com">Blog</option>
      <option value="http://apple.com">Apple</option>
   </select>
 
   <!--
      And our buttons, the first one is "Open In Same Window"
      which opens the link selected on the dropdown in the same window.
     
      The other button is the "Open In New Tab" which opens the link in
      new tab (or window in safari)
   -->
   <input type="button" value="Open In Same Window" id="open_same_window" />
   <input type="button" value="Open In New Tab" id="open_new_tab" />
</div>

<!-- include our library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type='text/javascript'>
$(document).ready(function() {

   //this will be triggered when the first button was clicked
   $("#open_same_window").click(function(){
      //this will find the selected website from the dropdown
      var go_to_url = $("#websites").find(":selected").val();
     
      //this will redirect us in same window
      document.location.href = go_to_url;
   });
 
   //this will be triggered when the second button was clicked
   $("#open_new_tab").click(function(){
      //this will find the selected website from the dropdown
      var go_to_url = $("#websites").find(":selected").val();
     
      //this will redirect us in new tab
      window.open(go_to_url, '_blank');
   });
 
});
</script>

</body>
</html>

Redirecting a page using JavaScript is fun. If you have any other techniques of doing this jQuery redirect onClick event, please drop it in the comments section below! Thanks!

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

Related Tutorials

Thank you for learning from our post about jQuery Redirect onClick Event (New or Same Window)!

Home jQuery

jQuery: Get Dynamic Div Height

jQuery quick tip: I’m going to show you how to get the height of a dynamic div.

I was in a situation when I have to animate a div by maintaining/grabbing/pausing its current height first but it’s height is not specified in the CSS and is dynamic.

Anyway, this tutorial will focus on how to get the dynamic div’s height.

Here’s a live demo and script:

View Live Demo here

<html>
    <head>
        <title>jquery get dynamic div height</title>
        <!– just some styles –>
        <style type=‘text/css’>
        #div_1{
           width:150px;
            border:thin solid red; 
            float:left;
        }
        .btn{
            padding:10px; 
        }
        </style>
    </head>
<body>

<!– the div with some contents in which we will get the height –>
<div id=‘div_1′>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis
dapibus, mauris ac feugiat bibendum. 
</div>

<!– onClick of this button, some text will be added and display the div_1 height –>
<input type=‘button’ class=‘btn’ id=‘add_text’ value=‘Add Text and Get New Height’ />

<!– This will display the current height –>
<div id=‘result’></div>

<script src=“https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js”>
</script>
<script type=‘text/javascript’>
$(document).ready(function() {
    //load the current height
    get_div_height();

    $(“#add_text”).click(function(){
        //append the some text to change current height
        $(“#div_1″).append(“The Code of a Ninja.”);
        
        //load the new height
        get_div_height();
    });

    //function to get current div_1 height
    function get_div_height(){
        var div_height = $(“#div_1″).height();
        $(“#result”).html(“div height is: “ + div_height + ” px”);
    }
    
});
</script>

</body>
</html>

You can also get your browser’s current window height by doing:

    $(window).height()

and your document’s height (height of html document) by:

    $(document).height()

more info on this link. :)

Transfer WordPress Site From Local Computer to Server Without Reinstalling

Recently, I had to develop a website with a famous CMS - WordPress. I have version 3.2.1. I'm so happy with it, the last time I worked with WordPress was about 3 years ago, and I didn't appreciate it the way I appreciate it today.

Transfer WordPress Site From Local Computer to Server Without Reinstalling
From your computer to your server.

So here's what I went through, I have WAMP on my computer and so I downloaded WordPress, installed it locally and tried to play around with it. I downloaded free WordPress themes, modified them, saved articles, etc. So now, I thought that the WordPress site I worked on my computer is good enough to be online. I never thought setting up a website with WordPress is this easy.

So I uploaded my files to the server and exported the SQL database. I tried to browse the site and guess what, tons of errors were shown. I didn't want to do a new WordPress installation on my server. So I had to hack some WordPress settings. Here's what I did:

1. Export SQL from local PhpMyAdmin to online PhpMyAdmin (If you're using PhpMyAdmin)

2. Copy WordPress files from localhost to server using Filezilla (or any FTP software)

3. Login and then create your online database with the same database name you have locally

4. Browse wp_options table

5. The first row (siteurl) contains your local url, probably http://localhost/YouSiteName, you have to change that to your online domain such as http://YourSiteName.com/

6. So now you can login to your online admin panel http://YourSiteName.com/wp-admin/

7. After logging in, Go to Settings &gt; General

8. Change the site address (URL) to http://YourSiteName.com/, then hit save button

9. Again, Go to Settings &gt; Permalinks

10. At the bottom part of it, you will see the correct .htaccess code.

Transfer WordPress Site From Local Computer to Server Without Reinstalling
Click to enlarge.

11. Copy it and access your current online .htaccess file and then paste the new .htaccess code, save and re-upload

That's it! Now you have successfully transferred a WordPress site from your computer to Online server without reinstalling!

Home PHP

How To Customize reCAPTCHA

Have you ever received unsolicited (Spam) messages, comments or notifications in your email, facebook account, or to other services you are using online? Probably yes. I think almost all people using the internet experienced it already. There are trillions of spam messages sent every year.

One effective way to prevent those spam messages to your form is using a “Completely Automated Public Turing test to tell Computers and Humans Apart” or CAPTCHA in short. Google, Facebook, Yahoo, and other big internet companies uses this method. So today we are going to do a script that uses Google reCAPTCHA for our form. This tool by Google is widely used in the internet, maybe you’re familiar with the red box image below:

Home>PHP How To Customize reCAPTCHA

Customizing your Google Recaptcha

DOWNLOAD SOURCE CODE LIVE DEMO

Step 1: Download the recaptcha library here.

Step 2: We’re going the have the following code on our index.php file.

<html>
<head>
<title>https://www.codeofaninja.com/ - Customized reCAPTCHA For Your Form using PHP</title>
<style type='text/css'>    
/*
the customization of our recaptcha field
recaptcha_widget id is what we're customizing
*/

#recaptcha_widget{
    magin: 0;
}

#recaptcha_widget a{
    color: #000;
    text-decoration: none;
    font-family: Arial, Helvetica, sans-serif;
    font-weight: bold;
    margin: 15px 0 0 0;
    padding: 2px 4px 2px 4px;
    background-color: #F5DEB3;
}

#recaptcha_widget a:hover{
    background-color: #DEB887;
}

.text{
    margin: 0 0 5px 0;
}

/*
just some message box style
when form is submitted
*/
#error-box{
    border: 4px solid #FF0000; 
    background-color: #FA8072;
    color: #fff;
    font-family: Arial, Helvetica, sans-serif;
    width: 430px;
    margin: 0 0 5px 0;
    padding: 4px;
}

#success-box{
    border: 4px solid #32CD32; 
    background-color: #00FF7F;
    color: #000;
    font-family: Arial, Helvetica, sans-serif;
    width: 430px;
    margin: 0 0 5px 0;
    padding: 4px;
}
</style>
</head>
<body>
<?php
//defining indexes
isset( $_REQUEST['action'] ) ? $action = $_REQUEST['action'] : $action = '';
isset( $_REQUEST['email'] ) ? $email = $_REQUEST['email'] : $email = '';
isset( $_REQUEST['user_password'] ) ? $user_password = $_REQUEST['user_password'] : $user_password = '';
isset( $_REQUEST['recaptcha_challenge_field'] ) ? $recaptcha_challenge_field = $_REQUEST['recaptcha_challenge_field'] : $recaptcha_challenge_field='';
isset( $_REQUEST['recaptcha_response_field'] ) ? $recaptcha_response_field = $_REQUEST['recaptcha_response_field'] : $recaptcha_response_field='';

require 'recaptcha/recaptchalib.php'; 
/* ---------------------------recaptcha code----------------------- */
//use your own private key here
$privatekey = "6LdUOcYSAAAAAGT-EbCqOldQ54GJhqG3ZdMkwLBG";
$resp = recaptcha_check_answer ($privatekey,
                        $_SERVER["REMOTE_ADDR"],
                        $recaptcha_challenge_field,
                        $recaptcha_response_field);

if (!$resp->is_valid) {
    $recaptcha = 'wrong';
} else {
    $recaptcha = 'correct';
}
/* ---------------------------recaptcha code----------------------- */
    
//when the form is submitted
if( $action == "signup" ){

$error_msg = '';

//if( empty($email) || empty($user_password)){
if( $email == '' || $user_password == ''){
    $error_msg .= "<div>-{$email}{$user_password}Field cannot be empty.</div>";
}

if( $recaptcha == 'wrong' ){
    $error_msg .= "<div>-You should enter characters that match the word verification.</div>";
}

if( $error_msg != '' ){
    echo "<div id='error-box'>";
        echo $error_msg;
    echo "</div>";
}else{
    echo "<div id='success-box'>";
        echo "Form successfully submitted.";
    echo "</div>";
}

}

?>

<!-- 
-this script is needed since we
are customizing recaptcha 
-it comes first before the form tag - always
-->
<script type="text/javascript">
var RecaptchaOptions = {
    theme : 'custom',
    custom_theme_widget: 'recaptcha_widget'
};
</script>

<!-- form tag comes first before table tag - always. -->
<form action='#' method='post' class='form'>
<table>
    <tr>
        <td align='right'>Email:</td>    
        <td><input type='text' name='email' /></td>
    </tr>
    <tr>
        <td align='right'>Password:</td>
        <td><input type='text' name='user_password' /></td>
    </tr>
    <tr>
        <td valign='top'>Word Verification.: </td>
        <td>
        
<div style='margin: 0px auto; text-align: center; width: 360px;'>
    

        <div class="field-space" style='text-align: left;'>
        
<!-- the id recaptcha_widget is what we're customizing -->
<div id="recaptcha_widget" style="display:none">

    <div id="recaptcha_image"></div>
    <div class="recaptcha_only_if_incorrect_sol" style="color:red">Incorrect, please try again</div>

    <div class="recaptcha_only_if_image" style='margin-bottom: 10px;'>Enter the words above : </div>
    <span class="recaptcha_only_if_audio">Enter the numbers you hear:</span>

    <div><input type="text" id="recaptcha_response_field" name="recaptcha_response_field" size='30' class='text' /></div>
    
    <span><a href="javascript:Recaptcha.reload()">Get Another Challenge</a>  </span> 
    <span class="recaptcha_only_if_image"><a href="javascript:Recaptcha.switch_type('audio')">Try Audio</a>  </span>
    <span class="recaptcha_only_if_audio"><a href="javascript:Recaptcha.switch_type('image')">Try Image</a>  </span>

    <span><a href="javascript:Recaptcha.showhelp()">Help</a></span>

</div>

<!-- user your own public key after "k="-->

<script type="text/javascript" src="http://www.google.com/recaptcha/api/challenge?k=6LdUOcYSAAAAALa38Uxegl8owzKXGomiSkV498n_"></script>
<noscript>
    <iframe src="http://www.google.com/recaptcha/api/noscript?k=6LdUOcYSAAAAALa38Uxegl8owzKXGomiSkV498n_" height="300" width="500" frameborder="0"></iframe>
    <br>
    <textarea name="recaptcha_challenge_field" rows="3" cols="40"></textarea>
    <input type="hidden" name="recaptcha_response_field" value="manual_challenge">
</noscript>

        </td>
    </tr>
    <tr>
        <td></td>
        <td>
            
        <!-- our hidden field and submit button here -->
        <div class="submit" style='float: left;'>
                <input type='hidden' name='action' value='signup' />
                <input type='submit' value='Sign Up!' />
        </div>
        
        </td>
    </tr>
</table>
</form>

</body>
</html>

That’s it! :)

display-facebook-events-on-website

How To Display Facebook Page Events on Website using PHP?

Before we start coding, you might be someone NOT interested in coding. If that's the case, you should use a website plugin like SociableKIT. Watch the following video.

Need to embed a single Facebook page event on your website? Watch this tutorial.

What's next? You can try SociableKIT now, view a live demo here and here or continue with the code tutorial below.

Let's code!

Do you have an event manager on your website? Do you create events on your Facebook page? If your answer is both YES, you're wasting a lot of time managing your brand's events information online.

What if there's a way to create an event ONCE, and then let it appear both on your Website and Facebook page? Will you be happy saving your precious time? Our code for today will make you happy then, just like we are!

Today we're gonna talk about how to display publicly available Facebook Page EVENTS on your website. This one is great if you want your Facebook page events to be shown in your website in a synchronized way.

Once you created or updated an event on Facebook, it will be automatically reflected on your website too. The advantages and risks of this is almost the same with what I discussed in my first post  related to this one.

Read more

Home jQuery

Check and Validate Username in jQuery

Hi there developer! Today we are going to do a code snippet that:

  1. Checks if a username is available or not (in the database).
  2. If the username is available, the program will output “[your_username] is available!”
  3. Then if it is not available, “Username already taken” will be printed.
  4. This code also has a simple validation that states whether the inputted username is too short or is empty.

All those tasks will be performed via AJAX, so it is without page refresh. You can expand its validation though.

In this code, we need a sample data from the database table and four (4) files which includes: config_open_db.php, index.php, check.php and the jQuery library file.

database – you could have this table structure and data:

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `firstname` varchar(32) NOT NULL,
  `lastname` varchar(32) NOT NULL,
  `username` varchar(32) NOT NULL,
  `password` varchar(32) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

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

INSERT INTO `users` (`id`, `firstname`, `lastname`, `username`, `password`) VALUES
(1, 'John', 'Doe', 'johnny', 'john'),
(2, 'Albert', 'Minston', 'albert', 'albert');

config_open_db.php – this file is for database connection so that we’ll be able to load usernames from the database. You should have something like this: (Please supply the variables with YOUR settings.)

<?php
$host = "localhost";
$db_name = "your_db_name";
$username = "your_db_username";
$password = "your_db_password";

//connect to mysql server
$mysqli = new mysqli($host, $username, $password, $db_name);

//check if any connection error was encountered
if(mysqli_connect_errno()) {
    echo "Error: Could not connect to database.";
    exit;
}
?>

index.php – this file makes our user interface for this tutorial. jQuery library is of course included in this file.

<html>
	<head>
		<title>Username checker and validator</title>
	</head>
<body>

<p>
	<div id = "feedback"></div>
	<form name = 'form'>
		<input type = 'text' id = 'username_input' name = 'username' >
	</form>(try 'johnny', 'albert', 'chris' or 'james')
</p>

<div class='back-link'>
	<a href='https://www.codeofaninja.com/2011/06/check-and-validate-username-without.html'>Back to tutorial page</a>
</div>

<script type = "text/javascript" src = "js/jQuery.js"></script>
<script type = "text/javascript">

	// when the document is ready, run the jquery script
	$(document).ready(function(){
		$('#feedback').load('check.php').show();

		/* We use keyup so that everytime the user type in the keyboard, it'll check the database and get results however,
		  you can change this to a button click which is I think, more advisable.
          Sometimes, your server response is slow but just for this demo, we'll use 'keyup' */
		$('#username_input').keyup(function(){

			$.post('check.php', { username: form.username.value },
				function(result){
					$('#feedback').html(result).show();
				});

		});
	});
</script>

</body>
</html>

check.php – this file makes the request to the database, to check the inputted value.

<?php
include_once("config_open_db.php");

isset( $_POST['username'] ) ? $username = $username = $mysqli->real_escape_string( $_POST['username'] ) : $username = "";
if($username == null){
	echo "Please enter a username.";
}

elseif(strlen($username) < 5){
	echo "Username is too short.";
}

else{
	$sql = "SELECT *
			FROM users
			WHERE username = \"{$username}\"";

	$result = $mysqli->query($sql);
	$num = mysqli_num_rows($result);
	if($num == 1 ){
		while($row = mysqli_fetch_array($result)){
			$fn = $row['firstname'];
			$ln = $row['lastname'];
			echo "<div style='color: red; font-weight: bold;'>Username already taken.</div>";
		}
	}else{
		echo "<span style='font-weight: bold;'>$username</span> is available!";
	}
}
?>

Download jQuery Code Examples

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

Related Tutorials

Thank you for learning from our post about Check and Validate Username in jQuery.

display-facebook-photos-on-website-1

How To Display Facebook Page Photo Albums on Website Using PHP?

Before we start coding, you might be someone NOT interested in coding. If that's the case, you should use a website plugin like SociableKIT. Watch the following video.

Need to embed a single Facebook page photo album on your website? Watch this tutorial.

What's next? You can try SociableKIT now, view a live demo here and here or continue with the code tutorial below.

Let's code!

Do you have a photo manager on your website? Do you upload photos on your Facebook page as well?

If your answer is both YES, you're wasting a lot of time managing your brand's photos online.

What if there's a way to upload your photo albums ONCE, and then let it appear both on your Website and Facebook page?

Will you be happy saving your precious time?

Read more

How To Parse RSS Feeds with MagpieRSS

Using MagpieRSS is one of the simplest ways to parse RSS feeds. One use of this is when you want to display updated contents from a site to your website. In this post, we are going to get the Top Stories news of "The Worldwide Leader in News", the CNN. We will just use one of their RSS feed links: http://rss.cnn.com/rss/cnn_topstories.rss. CNN provides all of their RSS feeds links, you can find them in this link http://edition.cnn.com/services/rss/. We just have to agree to their terms of use listed on that page.

How To Parse RSS Feeds with MagpieRSS
Want some feeds?

Step 1: Download MagpieRSS on sourceforge (I got magpierss-0.72) and place it in your web directory. I got the following files:



Step 2: Coding.

index.php

<html>
<head>
<title>Parsing RSS feeds with MagPie RSS</title>
</head>
<body>
<?php

require_once('rss_fetch.inc');

//Specify the URL of RSS feeds
$rss = fetch_rss("http://rss.cnn.com/rss/cnn_topstories.rss");

foreach ( $rss->items as $item ) { //loop through the $rss array which contains the feeds
    echo "<div style='margin: 5px 0 5px 0;'>";
    echo "<div style='font-weight: bold;'>{$item['title']}</div>";
    echo "<div style=''>{$item['description']}</div>";
    echo "</div>";
}
?>
</body>
</html>

If we will take a look at http://rss.cnn.com/rss/cnn_topstories.rss, we have:


On our index.php code, title and description inside $item variable are from the XML tags of RSS feed. If you will view-source http://rss.cnn.com/rss/cnn_topstories.rss, you will see:

Please Click to enlarge

This is an item in our RSS feed. The values between title and description tags are echoed in our program. You can also echo the link, pubDate, etc. since those tags are there too.

Step 3: Run the program. The ouput of our code would be something like:



You may want to:


That's it! Now you can embed some contents from an RSS feeds to your website!