Initiating Ajax to trigger the body's onLoad event

Whenever I use an ajax call to load a div, the entire page refreshes. It seems that the 'body onload=init()' event is triggered on ajax response causing all the initialization to repeat, which is not desired. Is there a way to only load the div through the ajax call?

<body onload="init()">
.....
.....
<div>...<a href="" onclick="saveView('more')"><b>More</b></a></div>
</body>

main.js

function saveView(arg){
    if(arg=="more"){
            ajaxGet(baseRef+"all.html", loadList);

    }else{
            ajaxGet(baseRef+"all-A.html", loadList);

    }
function init(){
.....
}

function ajaxGet(url, responseHandler)
{
    var page_request = false;

    if (window.XMLHttpRequest && !(window.ActiveXObject && window.location.protocol == "file:")) { 
                // use this only if available, and not using IE on a local filesystem
        page_request = new XMLHttpRequest();
        }
    else if (window.ActiveXObject) { // older versions of IE, or IE on a local filesystem
        try {
            page_request = new ActiveXObject("Msxml2.XMLHTTP");
        } 
        catch (e){
            try{
                page_request = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e){
            }
        }
    }
    else {
        alert("Your browser does not support XMLHTTP.");
        return false;
    }


    page_request.onreadystatechange=function() {
        if(page_request.readyState==4) {
                        // on local machines the status for success is 0. on web servers it is 200
            if(page_request.status==200 || page_request.status==0) {
                responseHandler(page_request);
            }
        }
    }

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

function loadList(page_request){
    document.getElementById("list").innerHTML=page_request.responseText;
    Loaded = true;    
    try{
        if(pLoaded) 
            doFilterStateChange1();
        }catch(e)
        {
        }
    setTimeout("restoreScrollTop()", 1000);
}

Answer №1

The onLoad event of the body is not being triggered by Ajax in this case. By noticing that there was no value assigned to href="" in the anchor tag, I realized it was causing the page to reload unnecessarily. Simply removing it resolved the issue.

Answer №2

If you're experiencing problems with page reloading, there could be a script error causing it. It's best to check your code using tools like Firebug to identify any errors that might not be easily noticeable if the page is refreshing quickly.

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

The markers on Google Maps are currently displaying in the wrong position, despite the latitude and longitude being correct

Utilizing the Google Maps API, I have implemented a system to dynamically add map markers tracking 2 of our company's vehicles. The website is developed in asp.net c# mvc with bootstrap 4.3.1. An ajax request retrieves the latest marker location from ...

Navigating Sockets with Navigator in React Native

Every time I encounter the error message undefined is not an object (evaluating this.props.socket.on). In my code, I define the socket in the index.ios.js file as shown below: class Main extends Component { constructor(props) { super(props); ...

Trigger click functions sequentially to display elements after specific actions are taken

Is there a way to make jQuery listen for clicks only at specific times? It seems that when I add event listeners, like $("#box").click(function(){, they are executing before the code above them finishes running. Let's say I have two boxes that should ...

XMLHttpRequest Error: The elusive 404 code appears despite the existence of the file

This is the organization of my project files: The folders Voice, Text, and Template are included. https://i.stack.imgur.com/9un9X.png When I execute python app.py and navigate to localhost http://0.0.0.0:8080/, the index.html page is displayed with conte ...

What is the best way to dynamically change the main content based on the sidebar option chosen in a React application?

Currently, I am in the process of creating the layout for the page similar to the image provided. When a user selects option A from the sidebar, my goal is to display the corresponding content on the same page without navigating to a new one. This projec ...

Creating a javascript variable in c#

Currently, I am working on incorporating the selected index text from a DropDownList into a JavaScript string. My approach involves storing the text in a hidden field and retrieving it through C# to ensure the JavaScript variable retains its value even aft ...

Clickable Angular Material card

I am looking to make a mat-card component clickable by adding a routerlink. Here is my current component structure: <mat-card class="card" > <mat-card-content> <mat-card-title> {{title}}</mat-card-title> &l ...

What is the importance of including parentheses when passing a function to a directive?

Hello, I'm currently a beginner in Angular and I am experimenting with directives. Here is the code snippet that I am using: HTML <div ng-app="scopetest" ng-controller="controller"> <div phone action="callhome()"> </div> </div ...

What steps can be taken to ensure that AngularJS does not detach a form input's value from its model if it is invalid?

While working on a form implementation in AngularJS, I encountered a baffling behavior that has left me puzzled. It seems that whenever I set ng-minlength=5 as an input attribute, AngularJS disconnects the value until it meets the length requirement. Thi ...

Using Promise.all within an async function to handle variables inside of Lambda functions

I've spent the past couple of days trying to find a solution to this issue. I've simplified my code to mostly pseudo code for ease of understanding. What I'm struggling with is creating an async function that acts as a trigger for an SQS qu ...

When I try to access localhost, it directs me to http://localhost:3000/myprofile%20 instead of localhost:/3000/myprofile

Every time I try to log into my profile page with the correct login credentials, I get redirected to http://localhost:3000/myprofile%20, but then receive a 404 error. This is what my code looks like: // Login Route router.post('/login', functi ...

conditional statement for manipulating data in javascript/html

I am working on appending results in an object as options in a datalist dropdown. While it is functioning correctly, the issue arises when not all elements have a specific level in the object consistently, impacting which results are added to the list. $( ...

Transforming JSON data into a visually appealing pie chart using highcharts

I'm having trouble loading my JSON string output into a highcharts pie chart category. The chart is not displaying properly. Here is the JSON string I am working with: var json = {"{\"name\":\"BillToMobile\"}":{"y":2.35},"{\ ...

Adjust index starting from 0 in JavaScript

Struggling with setting a consistently unique index that increments by one. Here is an example of my array: const originalArr = [ { name: 'first parent array', childArray: [ { name: '1 / first child' }, ...

"Exploring the world of mocking module functions in Jest

I have been working on making assertions with jest mocked functions, and here is the code I am using: const mockSaveProduct = jest.fn((product) => { //some logic return }); jest.mock('./db', () => ({ saveProduct: mockSaveProduct })); ...

What could be causing me to receive no results?

Currently, I am expanding my knowledge in JavaScript, Ajax, and NodeJs. My current project involves creating a webpage that can display a string retrieved from the server. The server-side code is as follows: var express = require('express'); v ...

Are there any similar tools to Graphstream in Java that can be used with HTML5 using canvas and JavaScript?

GraphStream is a revolutionary graph library created in Java that offers Java developers a simple way to visually represent dynamic graphs either in memory, on screen, or in files. Check out this demo video. With GraphStream, you can effectively handle th ...

Troubleshooting problem with image loading in AngularJS using ng-repeat

Recently delving into using AngularJS in my projects has presented a rather significant issue when utilizing ngRepeat to load thumbnails from a dynamic array into a DIV. While I won't dive deep into the entire application's details here, let me ...

Go to a different webpage containing HTML and update the image source on that particular page

I am facing an issue with my html page which contains multiple links to another page. I need to dynamically change the image references on the landing page based on the link the user clicks. The challenge here is that the link is inside an iframe and trigg ...

Exploring methods to retrieve data from the web3 platform through Node.js

Is there a way to retrieve token information such as name, symbol, and decimals using Nodejs in conjunction with web3js? ...