In this article, I will explain to you how to change content and URL without refreshing page using ajax – jquery. All website owner wants their site to run very speedily. So for decrease website loading speed, I have created one script which includes PHP, jquery and ajax code.
Due to the slow website speed, I have created this script for all of the users. Website speed is now the main factor in SEO. So you have to try this script if your website taking a long time to load. If you don’t have a knowledge of Ajax and jquery, Please learn the basics first.
I have created one demo also for your better understanding. Also, you can find the source code link at the bottom of the page. Let’s start now.
View Demo
Change content and URL without refreshing page using ajax – jquery – php
Here is the core part of the code. I have divided it into two parts. First is jQuery portion and second is ajax portion.
Part 1: jQuery Code (It is used to change the url of the website)
$(function(){ $("a[rel='tab']").click(function(e){ pageurl = $(this).attr('href'); $.ajax({url:pageurl+'?rel=tab',success: function(data){ $('#content').html(data); }}); if(pageurl!=window.location){ window.history.pushState({path:pageurl},'',pageurl); } return false; }); });
Part 2: Ajax Code (It is used to fetch data of other pages)
$(window).bind('popstate', function() { $.ajax({url:location.pathname+'?rel=tab',success: function(data){ $('#content').html(data); }}); });
Let’s take a review of full script step by step
I have created six files for the whole script and create a demo.
(1) Create “header.php” file then copy below code and paste it.
(2) Create “footer.php” file then copy below code and paste it.
(3) Create “index.php” file then copy below code and paste it.
";} ?>This Is Home Page
(4) Create “home.php” file
";} ?>This Is Home Page
(5) Create “about-us.php” file then copy below code and paste it.
";} ?>This Is About Us Page
(6) Create “contact-us.php” file then copy below code and paste it.
";} ?>This Is Contact Us Page
That’s it finally you can run the code and execute it in your browser. As a result, you will see the URL and content is change when you click links without page refresh.
Also, you can download the source code from below link and view the demo.
Releated Post
I hope you will like this tutorial and enjoyed it. If you have any questions then please comment below your question or contact me by contact us form. Please share this post with your friends.