Utilizing Ajax to fetch a div element from a web page

Hey there! I have a link set up that loads a page into a specific div ID, which is #ey_4col3.

The issue I'm facing is that it loads the entire page along with all its contents, but what I really want to load from that page is just the content within the ID: #page-contents

I've included the Ajax and JavaScript code below. I think I might not be using the correct method for achieving this, and I'm open to any suggestions on how to manipulate what I have or if there's a cleaner, simpler way to accomplish this task. Any help would be greatly appreciated:

var loadedobjects=""
var rootdomain="http://"+window.location.hostname

function ajaxpage(url, containerid){

    var page_request = false

    if (window.XMLHttpRequest) // if Mozilla, Safari etc
        page_request = new XMLHttpRequest()
    else if (window.ActiveXObject){ // if IE
        try {
            page_request = new ActiveXObject("Msxml2.XMLHTTP")
        } 
        catch (e){
            try{
                page_request = new ActiveXObject("Microsoft.XMLHTTP")
            }
            catch (e){}
        }
    }
    else
        return false

    page_request.onreadystatechange=function(){
        loadpage(page_request, containerid)
    }

    page_request.open('GET', url, true)
    page_request.send(null)
}

function loadpage(page_request, containerid){
    if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1))
        document.getElementById(containerid).innerHTML=page_request.responseText
}

function loadobjs(){
    if (!document.getElementById)
        return
    for (i=0; i<arguments.length; i++){
        var file=arguments[i]
        var fileref=""
        if (loadedobjects.indexOf(file)==-1){ //Check to see if this object has not already been added to page before proceeding
            if (file.indexOf(".js")!=-1){ //If object is a js file
                fileref=document.createElement('script')
                fileref.setAttribute("type","text/javascript");
                fileref.setAttribute("src", file);
            }
            else if (file.indexOf(".css")!=-1){ //If object is a css file
                fileref=document.createElement("link")
                fileref.setAttribute("rel", "stylesheet");
                fileref.setAttribute("type", "text/css");
                fileref.setAttribute("href", file);
            }
        }

        if (fileref!=""){
            document.getElementsByTagName("head").item(0).appendChild(fileref)
            loadedobjects+=file+" " //Remember this object as being already added to page
        }
    }
}

Thank you in advance!

Answer №1

Utilize the jQuery .load() function to load specific page fragments. Update your function like this:

function loadPage(url, containerID) {
    $('#' + containerID).load(url + ' #page-contents');
}

The $('#' + containerID) creates a jQuery object linked to the DOM element with an id matching the value of containerID. Then, .load(url + ' #page-contents') instructs jQuery to make an AJAX request to url and then set the HTML content of the #page-contents element in the returned HTML as the content for the selected element.

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

Navigating the scope set by a specific string

Is there a more efficient method than iterating through child objects to access the value at a specific location in the $scope, identified by the attribute "Calendar.Scheduling.field.Appointment.ApptDateTime_Date"? I was hoping for a solution similar to an ...

What is the importance of using mb_convert_encoding in order to display the characters correctly?

My website and MySQL database are both set to use UTF-8 encoding. An issue I am encountering is that when retrieving text from the MySQL database to display on the website, I need to utilize the PHP function mb_convert_encoding(@db_field,'utf-8' ...

Updating a document using the nano module in CouchDB is not supported

I am currently utilizing the Node.js module known as nano Why is it that I am unable to update my document? I need to set crazy: true and then change it back to false. This is the code I have: var nano = require('nano')('http://localhost ...

Creating a grid cell that spans the entire grid width

Snippet of CSS Code: .wrapper { display: grid; position: relative; grid-template-columns: repeat(4, 1fr); grid-auto-rows: 25vh; width: 100%; } .prova { border: 1px solid; } .wrapper div:nth-child(2) { grid-column: 3; grid-row: 2 / 4; ...

What could be causing the appearance of a mysterious grey box hovering in the upper left portion of my image and why is the code only adjusting the size of the grey box instead of the entire

I've been working on embedding some JavaScript into my Showit website to create a drag-and-drop feature that displays a collage/mood board effect. Everything is functioning correctly, but I'm running into issues with resizing the images. There&a ...

Steps to completely eliminate all elements from an object using specific keys

I have been pondering the most efficient method to delete all elements of an object through an onClick function. The goal is for the handler to remove all elements. Despite attempts with methods like the delete keyword and filtering, clicking the clear all ...

Struggling with IE7 compatibility issues regarding tables inside a div? Seeking a reliable resource to gain insights and strategies for effectively resolving IE7 problems

I am currently in the process of revamping this website: but I am facing a challenge with repeating a gradient within a div (cnews). The problem arises when the gradient is repeated on IE7, as it distorts the color. It appears as though the blue in the im ...

Setting Authorization with username, password, and domain in Angular 2 HTTP Request

I am facing an issue with calling an API method hosted on another machine using Angular 2 component with Http. When accessing the API from a browser, I can connect by entering a username and password as shown below: https://i.stack.imgur.com/JJqpC.png Ho ...

The jQuery AJAX call is successful in Firefox, but unfortunately, it is not working in Internet Explorer

I've encountered a perplexing issue with an AJAX call. It's functioning perfectly fine in Firefox, but for some reason, it's not working in IE. Curiously, when I include an alert() specifically for IE, I can see the returned content, but the ...

Vuejs unstyled content flash

I encountered an issue while loading a page with Vue. Initially, I am able to access variables like @{{ value }} but once the page is fully loaded, the variable becomes invisible. How can I resolve this issue? I have already included Bootstrap and all scri ...

Steps for inserting events in gridview with Jquery

Incorporating search functionality into a gridview using Jquery has been quite effective, following guidance provided in this informative article: http://www.aspsnippets.com/Articles/Search-GridView-with-Paging-on-TextBox-KeyPress-using-JQuery-in-ASPNet.as ...

Adding incremental values to a variable using JavaScript within the framework of jQuery and AJAX

In my JavaScript code that utilizes jQuery and AJAX, I have created a dynamic array containing multiple values for AJAX requests. The array is structured as follows: <script type="text/javascript> var array = Array("y", "y", "x", "y", "y", "y"); fu ...

Different conversations are taking place concurrently. How can we determine which one is currently being attended to

In my application, multiple dialogs are open simultaneously, each with its own set of shortcuts. It is important to ensure that these shortcuts work correctly based on the focused dialog. Is there a way to determine which dialog is currently in focus? Ed ...

Having a problem with Node.js and async.eachSeries? Want to figure out how to configure the callback function to generate a JSON file for each element in an array of

Currently, I am utilizing async.eachSeries to repeatedly call a function that generates an array called pointsForFormating. Each time this function is called, I format the pointsForFormating array and store the result in another array named pointsFormate ...

Expanding box geometry from a single side in Three.js

Just starting out with three.js and my first task was to create a box geometry that could be increased from only one side. Issue : When increasing the width or height of an object, both sides automatically expand. Check out this jsFiddle Example I waste ...

What is the best way to remove an active class by clicking in my specific situation?

I was working on creating a gallery of Unsplash images that would display a full-screen image when the user clicked on a small image. I implemented a modal window that should appear when the user clicks on the small image, and I wanted it to close when the ...

Preserving input data based on click and change events

Upon form submission, I encounter an issue with displaying only the divs that contain fields with saved values. The form saves user-entered values using PHP, where some of the fields are initially hidden within div elements until an onclick or onchange eve ...

NodeJS closes the previous server port before establishing a new server connection

During my development and testing process, whenever I make changes, I find myself having to exit the server, implement the updates, and then start a new server. The first time I run the command node server.js, everything works perfectly. However, when I m ...

Exploring the Benefits of Using AJAX with Single or Multiple JavaScript Files

Here's a question for best practices. I'm working on building an AJAX application where the main page loads everything through AJAX into the content section. Should I merge all my javascript files into one that is loaded on the main page, or spli ...

Display issue with Google Chart

Could someone please help me identify why these charts are not showing up? This code was functioning properly in a previous project. I copied the same code to a new project, only adding the master page. However, now the charts are not appearing. All I can ...