A different approach to making ajax requests

I'm currently conducting some experiments involving AJAX calls using pure JavaScript, without relying on JQuery. I am curious if it's possible to populate a DIV element in the following way:

<script type="text/javascript">
 function call_test() {
   document.getElementById("myId").innerHTML = ajax_call("example.php?id=1") ;
 }
</script>
<body>

<input type="button" onClick="call_test()" value"Test">

<div id="myId">Result will be displayed here</div>

The issue lies in how to return the result from the ajax_call function. The current code is as follows, but it doesn't seem to work:

function ajax_call(remote_file)
{
    var  $http, 
    $self = arguments.callee ;
    if (window.XMLHttpRequest) {
        $http = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        try {
            $http = new ActiveXObject('Msxml2.XMLHTTP');
        } catch(e) {
            $http = new ActiveXObject('Microsoft.XMLHTTP');
        }
    }
    if ($http) {
        $http.onreadystatechange = function()  {
            if (/4|^complete$/.test($http.readyState)) {
                return http.responseText ; // This only returns undefined
            }
         };
         $http.open('GET', remote_file , true);
         $http.send(null);
    }
}

Content of remote file:

<?php
  echo "<h1>Just an experiment</h1>";
?>

Answer №1

This situation arises due to the way AJAX requests are handled asynchronously. The ajax_call function will complete its execution before the server responds with the HTML content, resulting in a return value of undefined.

To address this issue, it is recommended to utilize a callback function for processing the AJAX response as illustrated below.

function ajax_call(url, callback) {
    var xhr, $self = arguments.callee;
    if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        try {
            xhr = new ActiveXObject('Msxml2.XMLHTTP');
        } catch (e) {
            xhr = new ActiveXObject('Microsoft.XMLHTTP');
        }
    }
    if (xhr) {
        xhr.onreadystatechange = function() {
            if (xhr.readyState === 4 && xhr.status === 200) {
                if (callback)
                    callback(xhr.responseText);
            }
        };
        xhr.open('GET', url, true);
        xhr.send(null);
    }
}

Additionally,

function call_test() {
    ajax_call("example.php?id=1", function(response) {
        document.getElementById("myId").innerHTML = response;
    });
}

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

How to access v-model from a separate component in Vue.js

How can I access a v-model that is located in a different component? The search field is within the App.vue file and I am trying to activate the :search='search' property in the Datatable.vue component. Code in App.vue: <v-text-field ...

Exploring JSON objects in React for improved search functionality

Hey there! I'm working on implementing a search bar that updates the list of JSON entries based on user queries. Below is the code snippet that displays the video list (<Videos videos={this.state.data}/>). Initially, when the page loads, I have ...

How to combine two tables in Sequelize using a one-to-many relationship

I'm currently working with two models: User and Foto. In my application, each User can have multiple fotos, and each foto is associated with only one user. My challenge lies in using the include function. I am able to use it when querying for the us ...

Resolved: Flask route failing to receive Ajax request

I am encountering an issue while attempting to gather 2 inputs from my HTML Form and send them to my @app.route("/sell") using Ajax. Despite following the same method for other routes without any problems, I seem to be facing a unique challenge this time. ...

When NextJS calls a dynamic page in production, it redirects to the root page

My Desired Outcome When a user inputs https://www.example.com/test, I want them to receive the content of the NextJS dynamic route /test/index.js. This functionality is successful in my local environment. The Current Issue Despite a user entering https:/ ...

Seamless Exploration with Google StreetView

Google uses a special effect on StreetView images to transition smoothly between them. You can see an example of this effect in the images below, with the second image showing it being applied. My question is: How can I incorporate this same effect into m ...

Can I transfer a variable from JavaScript to Python in a seamless way?

Here's a straightforward query: Is it possible to include a JavaScript variable (varExample) in the data.py line while preserving the functionality of the JSONP Python callback code (?callback=? part)? The objective is to seamlessly integrate varExamp ...

conversion of text to number using JavaScript

After pulling values from an XML file using JavaScript, I face the challenge of converting a string to an integer in order to perform calculations. To extract data from the XML file, I use the following snippet: var pop = JSON.stringify(feature.attribute ...

Bidirectional data binding in AngularJS for <option> elements generated from an AJAX request

I have built a Controller called WebsiteController with the following functionality: JApp.controller('WebsiteController', function($scope, $resource) { var UsersService = $resource('/auth/users', {}); $scope.adding = false; ...

How can we use response.render in Express.js to render HTML on the client side?

I have set up a simple Express.js application with the following routes: router.get('/', function(req, res){ res.render('login'); }); Everything is working fine - when I log into the main page on my localhost, the HTML fro ...

Guide to crafting an effective XHR request using AJAX

Here's a snippet of my basic web page: <!DOCTYPE html> <html> <head> </head> <body onload="start()"> </body> </html> Below is the XMLHttpRequest function I've implemented: function start(){ / ...

Retrieving information selectively using useSWRImmutable

Having issues fetching data using useSWRImmutable. The problem arises when attempting to display the fetched data inside the UserRow component. Even though I can successfully print the data outside of the UserRow component, any console.log() statements wi ...

Top Method for Initiating AJAX Request on WebForms Page

Looking for the best way to execute an AJAX call in a WebForms application? While ASP.NET AJAX components are an option, some may find them a bit heavy compared to the cleaner approach in MVC. Page Methods can be used, but they require static methods ...

Decode PDF417 barcode images with ease using HTML and JavaScript on both desktop and mobile web browsers

Looking to utilize JavaScript to decode PDF417 type barcode images? If you're encountering Zxing plugin issues in mobile browsers but it works well on desktop browsers with https://github.com/PeculiarVentures/js-zxing-pdf417, consider alternative sol ...

Building a dynamic form using React Material-UI Autocomplete and integrating it with react

I'm encountering an issue where the MUI Autocomplete is not displaying the selected fields even though the react-hook-form values have been updated. Here is the code snippet import { useForm, Controller, FormProvider } from "react-hook-form" ...

Tips for saving an array from the server into a script variable

I'm currently working with the express js framework along with Handlebarsjs as the templating engine. My aim is to pass an array from the router to the view, and then store this array within a script tag. //users is an array res.render('chatRoom ...

JavaScript code snippet for detecting key presses of 3 specific arrow keys on the document

For this specific action, I must press and hold the left arrow key first, followed by the right arrow key, and then the up arrow key. However, it seems that the up arrow key is not being triggered as expected. It appears that there may be some limitations ...

Tips for managing numerous Axios requests in JavaScript

I have a scenario where I need to send 3 axios calls simultaneously from the frontend to the backend using the axios.all function to modify a MONGO DB database. The challenge I am facing is ensuring that if one of the requests fails, none of the other requ ...

"An error message stating 'Express: The body is not defined when

I'm encountering an issue while trying to extract data from a post request using express. Despite creating the request in Postman, the req.body appears empty (console.log displays 'req {}'). I have attempted various solutions and consulted s ...

AngularJS $scope variable can be initialized only once using an HTTP GET request

I'm facing an issue with fetching data from an API in a separate AngularJS application. There's a button that triggers the retrieval of data from the API. Upon clicking, it executes the $scope.getApiData function, which is connected to $scope.pr ...