What appears to be the issue with this AJAX code snippet?

I am new to programming and currently working on a code that involves retrieving text data from a file and replacing the existing text with new text. I have implemented AJAX to accomplish this task, but I am encountering an issue where an error message is displayed before the expected output. The error message is part of the code I included to handle errors. Although I am getting the desired result, I am curious as to why the error message is appearing. Below is my code:

<!DOCTYPE html>
<html>   
<head>

    <script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.js"></script>
    <script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.min.js"></script>
    <script>
        function loadXML() {
            var xmlhttp;
            if (window.XMLHttpRequest) {
                xmlhttp = new XMLHttpRequest;
            }    
            else {
                xmlhttp = new ActiveXObject("MICROSOFT.XMLHTTP")
            }
            xmlhttp.onreadystatechange = function () {
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                    document.getElementById("p1").innerHTML = xmlhttp.responseText;
                }
                else {
                    alert("There is an error in your code");  
                }   
            }
            xmlhttp.open("GET","robots.txt", true);
            xmlhttp.send(null);
        }
    </script>
</head>    
<body>
    <p id="p1">This is Text</p>
    <button id="b1" onclick="loadXML()">Click me </button>
</body>
</html>

Answer №1

The issue lies within your if-block in the onreadystatechange function. As xmlhttp.readyState changes multiple times during the request and response, the onreadystatechange function gets called each time.

To address this problem, you can modify your code as follows:

xmlhttp.onreadystatechange = function () {
    if (xmlhttp.readyState == 4 ) {
         if( xmlhttp.status == 200 ) {
             document.getElementById("p1").innerHTML = xmlhttp.responseText;
         } else {
             alert("There is an error in your code");  
         }
    }   

An alternative approach would be to utilize other event-methods such as onload and onerror, which are explained here.

Answer №2

1- Make sure to include the jQuery file jquery-1.9.0.js. It is the same as jquery-1.9.0.min.js, but jquery-1.9.0.min.js is a minified file.

2- Can you provide the error message from the javaconsole log?

3- If you are already using jQuery, consider utilizing $.get instead of working with XMLHttpRequest. jQuery's $.get function handles HttpRequest effectively for all browsers.

You can update your JS code with the following:

<script type="text/javascript">
$( document ).ready(function() {
        $.get('robots.txt',function(data){ $('#p1').html(data) });

});
</script>

Answer №3

Have you set up a webserver? Ajax may not function properly when using a local file URL like 'file://...'

Answer №4

alert("Oops! There seems to be an issue with your code.");
In reality, there is no error in your code. The xmlhttp.onreadystatechange function is simply being called at different stages of the request. This is why you are checking for xmlhttp.readyState == 4. For more information on these stages, check out this link: http://www.w3schools.com/ajax/ajax_xmlhttprequest_onreadystatechange.asp Therefore, your code is actually running smoothly; you're just displaying an error message that isn't necessary.

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

Automatically populate input fields with text based on the option chosen from a dropdown menu

Having some issues here... I want to automatically populate the text input boxes in my form when a username is selected from the dropdown. The user data array is retrieved from a MySQL database. Not sure if my JavaScript code is correct. Here's my arr ...

Tips for iterating within a Vue.js template without disrupting the HTML structure

Currently, I am attempting to implement a loop within a table. However, I have encountered an issue with the following code: <tr v-for="( block , index ) in listRenderBlock" :key="index"> <div v-for="( section , i ) in ...

Change the content of an ion-card in Ionic2 dynamically

After fetching a list of books from the backend API provider, I am presented with sample data that looks like this: { "success":true, "books":[ { "id":1000, "book_code":"CC219102", "read_status":"completed", ...

Intricate form of a character's silhouette

Imagine I have a unique character that users can select, and when it's selected, I want to display an outline around it. The character is represented as an object3D with multiple meshes. I attempted cloning the character and applying a backside mater ...

Preventing an RxJS Observable interval: A step-by-step guide

I am facing a unique scenario where I am using an RxJS interval, but I might need to abruptly stop it at any point. I thought there would be a simple method like cancel() or stop() similar to clearTimeout for intervals. Is there a way to stop an interval o ...

What is the best way to extract the property name from the AJV output in order to effectively translate validation errors into user-friendly

I am currently utilizing the AJV library for input validation in my nodejs express api. I'm facing an issue with extracting the property name associated with each error object within the returned array. [{ instancePath: '', schemaPath: & ...

How can one determine if a new document was created by Mongoose's upsert feature?

My code in node.js/express.js looks like this: var User = mongoose.model('User'); var usersRouter = express.Router(); usersRouter.put('/:id', function(req, res) { req.body._id = req.params.id; var usr = new User(req.body); ...

Chrome is inaccurately reporting the outerHeight value, while IE and FireFox are displaying it correctly

The jquery.smartWizard plugin includes a function called fixHeight that adjusts the height of a wizard step. It is utilized when displaying a step for the first time or revealing hidden divs within the step. The function works correctly in IE and FireFox, ...

Conflict between jQuery and Primefaces

In my PrimeFaces based Webapp, I have multiple tabs, each containing a datatable. To add functionality to input fields with a specific class in the datatable component, I am using jQuery click handlers. Below is the jQuery code snippet: $(document).ready( ...

Exploring the fundamentals of JavaScript within the context of Express.JS

Can you please explain the distinction between these two blocks of code in JavaScript? app.get("/api/products/1", (req, res) => { const singleProduct = products.find((product) => { product.id === 1; }); res.json(singleProduct); }) ...

Store the link in a variable and retrieve its content into another variable

Is there a way to extract the content of a link stored in a variable and store it in another variable using jQuery or javascript while working on an XML page? I know this is possible with php, but since I am developing a Chrome extension, I am wondering ...

Issue with OnChange Not Triggering

Why isn't the onchange property firing when typing in my textbox? Check out the code below: VB.NET Dim textBoxUrlYoutube As New TextBox divUrlTextBoxContainer.Controls.Add(textBoxUrlYoutube) textBoxUrlYoutube.CssClass = "textboxyo ...

Use jquery ajax to upload an image with a reusable input field

UPDATE: Progress has been made in solving this issue. Please refer to Jquery form no submission to IE7 and IE8. The main task remaining is sorting out the compatibility with IE7 and IE8. I have been utilizing THIS plugin to upload files as email attachmen ...

Craft an engaging and dynamic Image map with SVG technology to elevate responsiveness and interactivity

I'm currently working on a website and I need to create two clickable sections on the home page. Each section will lead to a different specialization of the company. To achieve this, I decided to use a square image split into two right-angled triangle ...

Extracting the JQuery library from its source code

Is there a simple method for extracting only the necessary functions from the jQuery library? I have found that many of the functions within the library are not being utilized, so it would be beneficial to remove them. ...

Leveraging objects when making Ajax requests to PHP endpoints

After creating an instance of a class in my index.php file, I am facing an issue when trying to use jQuery Ajax to call some PHP files. The objects I created in the index.php file are not accessible from these PHP files. Is there a solution to make this s ...

Ways to verify the presence of a key within an array of objects

I'm on a mission to determine whether a specified key exists in an array of objects. If the key value is present, I need to return true; otherwise, false. I enter the key into a text box as input and then attempt to check if it exists in the array of ...

What is the process for accessing someone's birthday information using the Facebook API?

Working on integrating Facebook login and successfully retrieving user details such as first_name, email, etc. However, encountering an issue with fetching the birthday information. When attempting to call for birthday using the code snippet below, no data ...

"Despite receiving a response code of 200 in Rails using jQuery ajax, the data is still

I'm attempting to display a partial in a bootstrap modal. Although I am receiving a 200 response, the JavaScript code within show.haml is not functioning correctly. I have added an alert message for testing purposes, but it does not trigger. In the GE ...

PHP script encountering difficulty inserting data into database when AJAX is utilized; functions flawlessly without AJAX

In my "user registration" file, there is a form with the following structure: <form action="" method="POST"> <label for="user" class="control-label">User </label> <input type="text" name="user" class="form-control" id="user" ...