I would like to embed the HTML page within the specified div element

When attempting to load a HTML page inside the div, I encountered the following issue:

<a href="#1" title="" class="base-banner" page="www.google.com for example">

<img src="images" alt=""></a> <div id="landingpage"> </div>

Here is the JavaScript code being used:

$(document).ready(function() {
            $(".base-banner").on("click", function(){  
                $("#landingpage").show().load($(this).attr("page"));

                return false;
            });
        });

The loading works properly when trying to load a local page, but fails when attempting to load a live page. Any insights on where I went wrong and what needs to be corrected would be greatly appreciated.

Thank you in advance for your help.

Answer №1

It is not possible to query pages across domains due to AJAX policy restrictions.

However, a workaround solution can be implemented using the following code snippet:

<div id="siteloader"></div>


$.ajaxSetup({
    scriptCharset: "utf-8", //possibly "ISO-8859-1"
    contentType: "application/json; charset=utf-8"
});

$.getJSON('http://whateverorigin.org/get?url=' + 
    encodeURIComponent('http://google.com') + '&callback=?',
    function(data) {
        console.log("> ", data);
        //If the expected response is text/plain
        $("#target").html(data.contents);
        //If the expected response is JSON
        //var response = $.parseJSON(data.contents);
        //console.log("> ", response);
});

http://jsfiddle.net/SsJsL/2011/

Answer №2

If you're trying to embed an html file within a div, there are a few ways to achieve this – one option is using Ajax or iframe. Below is a sample code snippet for loading the content using an iframe:

function load_home (e) {
    (e || window.event).preventDefault();
    var con = document.getElementById('content')
    ,   xhr = new XMLHttpRequest();

   xhr.onreadystatechange = function (e) { 
    if (xhr.readyState == 4 && xhr.status == 200) {
      con.innerHTML = xhr.responseText;
    }
   }

xhr.open("GET", "http://www.yoursite.com/home.html", true);
xhr.setRequestHeader('Content-type', 'text/html');
xhr.send();
}

Answer №3

This question may be old, but for those facing the same issue, I discovered that if you haven't opened the page in your browser first, nothing will display when trying to load the file into your div.

To solve this, simply open the page in your browser by typing the page's name (e.g., "http://localhost/myPage.html"). If it displays correctly, then it will load inside your div.

I'm not entirely sure why this is necessary, perhaps it has to do with loading the page onto the server or something similar.

I hope this explanation helps.

Answer №4

Due to the CORS policy, content from pages on different domains may be restricted by the browser.

To bypass this restriction, you can use a third-party proxy like .

To implement this, simply add the cors-anywhere link before your URL as shown below:

$(document).ready(function() {
  $(".base-banner").on("click", function() {
    // Use the cors-anywhere link provided below.
    $("#landingpage").show().load('https://cors-anywhere.herokuapp.com/' + $(this).attr("page"));

    return false;
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="#1" title="" class="base-banner" page="https://www.google.com">

  <img src="images" alt=""> click here </a>
<div id="landingpage"> </div>

Check out this Demo Link.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Discover the magic of creating a navigation menu with jQuery toggle - let me show

Recently, I managed to create a side navigation using the target function in CSS3. However, I am curious about how I can achieve the same result using jQuery without disrupting the layout. Any assistance would be greatly appreciated. Here is the code sni ...

Comparing the special features of jQuery Sortable+Droppable and Draggable functionality

Trying to implement a feature where a draggable list of items (left column) can be dragged onto a sortable list (right column), but with a twist. The sortable list should behave like a droppable list, maintaining the order only when dragging new items and ...

Enable the feature for users to upload images to a specific folder within the Chrome extension without the need for

I need to implement a feature in my Chrome extension that allows users to upload images directly to a specific folder named "upload" without needing a submit button. <form action="/upload"> <input type="file" name="myimages" accept="image/*"> ...

Initiating a conversation from deep within a conversation using JQuery Mobile

I've been attempting to open a Dialog from within another Dialog, but so far no success. Take a look at the HTML code below: <a href="#popupDialog" data-rel="popup" data-position-to="window" data-role="button" data-inline="true" data-transition=" ...

The servlet is notified of a request with no data being sent from

I have encountered an issue with my JavaScript program that is attempting to send an AJAX request to a Java HTTPServlet. The servlet, which listens on the specific URL pattern "/users", is expected to return XML data. However, when the request is made to t ...

Is there a way to modify certain parameters of a plugin without the need to directly edit the

Is there a way to modify certain parameters of a plugin without directly editing it? You can find the link to the plugin here: . Can we include an additional script to override specific parameters of the above script, such as setting displayTime to 1000 ...

JavaScript/CSS memory matching game

Just starting out in the world of programming and attempting to create a memory game. I've designed 5 unique flags using CSS that I want to use in my game, but I'm feeling a bit stuck with where to go next. I understand that I need some function ...

Tips for preserving the status of a sidebar

As I work on developing my first web application, I am faced with a navigation challenge involving two menu options: Navbar Sidebar When using the navbar to navigate within my application, I tend to hide the sidebar. However, every ti ...

Unspecified origins of Js in Chrome Extension

console.log(chrome.runtime.sendMessage({from:"script2",message:"hello!"})); However, attempting to send the message from a background script to a content script is proving to be unsuccessful. https://i.stack.imgur.com/ERgJB.png ...

Display a spinning wheel or progress bar while the website is in the process of loading

Looking to construct a treeview using the jquery-treeview plugin but noticing it's quite time-consuming (about 5-7 seconds). I'm interested in adding a spinning wheel or progress bar to indicate loading while the page is processing. Any suggestio ...

Using the MVC framework, showcase a collection of images in real-time using AJAX and JQUERY

Managing a website where I fetch and display a list of thumbnail images from the database has proven to be a bit slow. The main issue lies in the time it takes to load each image using Url.Action, which goes through the entire MVC pipeline. To tackle this ...

Looking to display or conceal a text box with a date picker based on the selection of a specific value from a drop-down menu

I have a dropdown with two options: Indian and Others. When I select Others, I want to display three textboxes - two with date pickers and one with a simple text input field. I have tried writing the following HTML code but I am unable to get the date pick ...

Steps for implementing a datepicker in a dynamically generated element

Snippet of jQuery code that adds an element to a container $(container).append( '<label class="control-label col-md-3">Join Duration</label>' + '<div class="col-md-4">' + '<input type="text" name="join_dura ...

Using JQuery and PHP to make an Ajax request and handle JSON response

I'm attempting to complete a straightforward exercise: The task involves entering two numbers in separate inputs, clicking a button, and seeing the result appear in a third input. sum.html: <html> <head> <title>Sum</tit ...

Event follows activation of trigger click

I've already gone through this post on Stack Overflow about triggering an action after a click event, but none of the solutions I've tried so far have worked. Let's say I have a menu on my webpage like this: <ul class="nav nav-tabs"&g ...

Tips to prevent redirection in a JavaScript function

When a user clicks on a specific link, the HideN function is triggered. Here's an example: <a href="<?php echo $dn5['link']; ?>" onclick="HideN('<?php echo $dn5['id'];?>','<?php echo $dn5['fro ...

Validate and send a Django form using Ajax while utilizing django-crispy-forms

My experience with django and web development is very new to me. I am seeking guidance on how to submit a Django form using Ajax while utilizing django-crispy-forms. Specifically, I need assistance with the following: validating input submitting with ...

Difficulty navigating through pages on an iPad due to slow scrolling with JavaScript

My operation is executed within a scroll function, like this: Query(window).scroll(function(){ jQuery('.ScrollToTop').show(); // my operation. }); While my web page responds quickly to the operation, it seems slo ...

Display the accurate duration based on the dates selected in an HTML form automatically

If someone has office hours on Monday, Wednesday, and Friday from 7:00 am to 7:00 pm, and on Tuesday and Thursday from 10:00 am to 9:00 pm, the dropdown menu should display only the timings of 7:00 AM to 7:00 PM if the selected date is a Monday, Wednesda ...

Ways to manage the order of RequestExecutor execution

I have recently developed an intranet site using SharePoint Office 365. Within the master page file, there is a menu bar that utilizes a List to store the URL and name. My goal is to control the visibility of the "Admin" button based on whether the user ...