skip to Main Content

I am trying to redirect my php page to another php page without page load.

And these jQuery methods i have tried

1.This returns me alert but not redirecting to the page

<script type="text/javascript">
  
$('a').click(function (event) 
{ 
   event.preventDefault(); 

   var url = $(this).attr('href');
 
   $.get(url, function(data) {
     alert(data);

    });

 });
</script>
<!DOCTYPE html>
<html>
<head>
	<title>AJax</title>
	<script
  src="https://code.jquery.com/jquery-3.4.1.min.js"
  integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
  crossorigin="anonymous"></script>
</head>
<body>


<a href="http://localhost:8001/Test/redirect.php"><h1>Click Here</h1></a>

</body>
</html>

2.This method is redirecting to the page but its getting load

$('a').click(function (event) 
{ 
   event.preventDefault(); 

   var url = $(this).attr('href');
   $.get(url, function(data) {
window.location.href="http://localhost:8001/Test/redirect.php"
    });

 });

I want a simple solution to redirect my page without getting load using jQuery and AJAX.
Guide me to achive this 🙂

2

Answers


  1. Your question is not very clear about what you want to achieve, but as I understood

    • You want to load data to a page without changing the page
    • You want to change the URL in the browser address bar without loading another page

    If I’m right about your intention, then you have to

    1. Use AJAX to get the data (like $.get(): https://api.jquery.com/jquery.get/)
    2. Use window.history.pushstate() (more on this: https://developer.mozilla.org/en-US/docs/Web/API/History/pushState)

    So, implementing it with your functions may look like this:

    $('a').click(function (event) { 
       event.preventDefault(); 
    
       var url = $(this).attr('href');
    
       $.get(url, function(data) {
         // alert(data);
          window.history.pushState('stateObject', 'New Title', '/newpage')
    
          // code to display/render your new page content
          // supposing data holds valid HTML
          document.getElementById('content-container').innerHTML = data
        });
     });
    

    In a sense you would like to create a router that loads your data, so I would point you towards using a jQuery router: https://www.npmjs.com/package/jqueryrouter

    Login or Signup to reply.
  2. if you mean change URL without refreshing, you can try this :

    window.history.pushState('data','title','/test')
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search