jquery load url in same window

jQuery Load URL in Same Window

If you want to load a URL in the same window using jQuery, you can use the .load() method. This method loads data from a server and puts the returned HTML into the selected element.

Method 1: Using .load() Method


$(document).ready(function(){
  $("#target").click(function(){
    $("#content").load("https://www.example.com/");
  });
});
  • $(document).ready(function(){...}); ensures that the code inside it will only execute once the page Document Object Model (DOM) is ready for JavaScript code to execute.
  • #target is the ID of the element that will trigger the load event.
  • #content is the ID of the element where the loaded content will be displayed.
  • .load("https://www.example.com/"); loads the content from the specified URL and places it inside the #content element.

Method 2: Using .get() Method

You can also use the .get() method to load data from a server using an HTTP GET request.


$(document).ready(function(){
  $("#target").click(function(){
    $.get("https://www.example.com/", function(data){
      $("#content").html(data);
    });
  });
});
  • $.get("https://www.example.com/", function(data){...}); sends an HTTP GET request to the specified URL and retrieves the response as HTML.
  • function(data){...} is a callback function that is executed once the request is completed successfully.
  • $("#content").html(data); sets the HTML content of the #content element to the retrieved data.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe