JavaScript and Ajax functions are only compatible with the use of the confirm() method

After some troubleshooting, I discovered that my JavaScript function only works when the final confirm() statement is included. Originally added for debugging purposes, removing it prevents delete_row.php from running. Additionally, when the confirm statement is present, the function works on all browsers except for Safari...

function deleterow(form) {

    if (!confirm("Are you sure you want to delete?")) return false;

    var queryString = "?ID=";

    for (var i = 0; i < document.myForm.rows.length; i++) {
        if (document.myForm.rows[i].checked) {
            ID = document.myForm.rows[i].value;
            ID = ID.slice(0, -1);
            queryString += ID;
            queryString += "-";
        }
    }
    queryString = queryString.slice(0, -1);

    try{
        // Opera 8.0+, Firefox, Safari
        ajaxRequest = new XMLHttpRequest();
    } catch (e){
        // Internet Explorer Browsers
        try{
            ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try{
                ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e){
                // Something went wrong
                alert("Your browser broke!");
                return false;
            }
        }
    }

    var ajaxRequest;  // The variable that makes Ajax possible!
    // Create a function that will receive data sent from the server
    ajaxRequest.onreadystatechange = function(){
        if(ajaxRequest.readyState == 4){
            var ajaxDisplay = document.getElementById('ajaxDiv');
            ajaxDisplay.innerHTML = ajaxRequest.responseText;
        }
    }

    ajaxRequest.open("GET", "delete_row.php" + queryString, true);
    ajaxRequest.send(null); 
    confirm('Delete successful!');
}

UPDATE SOLVED

I modified the following JavaScript script to check the status of the ajaxRequest:

ajaxRequest.onreadystatechange = function(){ // Create a function that will receive data sent from the server
    if(ajaxRequest.readyState == 4 && ajaxRequest.status == 200){
        var ajaxDisplay = document.getElementById('ajaxDiv');
        ajaxDisplay.innerHTML = ajaxRequest.responseText;
    }
    else{
        alert('An error has occurred making the request');
        return false;
    }
}

Upon realizing that I was receiving a status of 0 back from the server, some research led me to identify an issue in how I defined the buttons calling these functions.

The original code was:

<div style='float:left; margin-right:10px;'><input type="submit" onClick="deleterow(document.myForm)" VALUE="Delete ROWs"></div>

The fix is:

<div style='float:left; margin-right:10px;'><input type="button" onClick="deleterow(document.myForm)" VALUE="Delete ROWs"></div>

(The submit type needed to be changed to button type)

Answer №1

The delete_row.php file doesn't appear to be functioning correctly.
Have you confirmed this issue? Consider adding an alert to if(ajaxRequest.readyState == 4){. I tested your JavaScript code without the form elements and it worked smoothly. Check out my result on http://jsfiddle.net/6gjy6/. Have you checked for any JavaScript errors in Google Chrome's console? Also, have you tried performing a basic "GET" request in the browser using the correct URL like delete_row.php" + queryString,,to see how the server responds instead of using AJAX?

Give this a shot:

var queryString = "?ID=";

for (var i = 0; i < document.myForm.rows.length; i++) {
    if (document.myForm.rows[i].checked) {
        ID = document.myForm.rows[i].value;
        ID = ID.slice(0, -1);
        queryString += ID;
        queryString += "-";
    }
}
queryString = queryString.slice(0, -1);
var ajaxRequest; 

try{
    // For Opera 8.0+, Firefox, Safari
    ajaxRequest = new XMLHttpRequest();
} catch (e){
    // Handling Internet Explorer Browsers
    try{
        ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
        try{
            ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e){
            // An error occurred
            alert("Your browser is not supported!");
            return false;
        }
    }
}

// Define a function to handle data received from the server
ajaxRequest.onreadystatechange = function(){
    if(ajaxRequest.readyState == 4){
        alert("received: " + ajaxRequest.responseText);
        var ajaxDisplay = document.getElementById('ajaxDiv');
        ajaxDisplay.innerHTML = ajaxRequest.responseText;
    }
}

ajaxRequest.open("GET", "delete_row.php" + queryString, true);
ajaxRequest.send(null); 

Answer №2

From what I understand, the onreadystatechange event should be set after the open method is called to prevent the handler from being reset.

Answer №3

Make sure to keep your confirm() statement at the top of your JavaScript code, and right below it include:

window.alert = null ; 

Then give it a try and see if it works.

Okay, I'll give it a look and check for you.

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

Exploring the functionality of Grails: Leveraging jQuery and ajax for transferring data to a controller

I am currently working on implementing an AJAX review submission feature for an event to prevent page reload. Below is the form I have set up for submitting reviews. <g:form > <g:textArea class="form-control" id="review" name="comment" value="$ ...

Calculate the total number of pages within an epub document

As a beginner in the world of epub, I have acquired numerous files in different epub formats and now wish to make them easily readable online. I'm not quite sure what an epub file contains. Is there a method to determine the number of pages in my epub ...

Can you explain the functionality of this: http://welbog.homeip.net/ ?

Can you explain how this operates?: All you need to do is scroll down. The design is impressive, absolutely impressive, and it functions seamlessly without the use of javascript. How is that possible? ...

Is it possible to link a JavaScript object to a dropdown Select Option?

As I work on populating a select list with options using Javascript, I am looking for a way to attach a corresponding Javascript object to each option that can be easily accessed during the change event. While formulating this question, I began thinking a ...

Creating an outlined effect on a transparent image in a canvas: step-by-step guide

Currently, I am working on creating transparent images using canvas in HTML5 and I would like to incorporate borders into them. The issue I'm facing is that the "Stroke" property does not consider the transparency of the image and applies it as if it ...

Exploring the Modularity of Post Requests with Node.js, Express 4.0, and Mongoose

Currently, I am immersed in a project that involves utilizing the mean stack. As part of the setup process for the client-side, I am rigorously testing my routes using Postman. My objective is to execute a post request to retrieve a specific user and anot ...

Jest v29 Upgrade Issue: Test environment jest-environment-jsdom not found

Are there any success stories of upgrading to the newest version of Jest, specifically version 29? I keep encountering an error message: Error: Test environment jest-environment-jsdom cannot be found. Please ensure that the testEnvironment configuration ...

Accessing the statusText of a 403 response in Axios (React, Express, Node.js)

Within my component, there is a register function that makes an API call. The API checks if the email already exists and provides an appropriate status and statusText based on the result. Below is the API call handler in my Express app: router.post(' ...

Navigating through a JavaScript object array within another object

I am looking to iterate through a JavaScript object array Here is my object response: { "kind": "calendar#events", "etag": "\"p3288namrojte20g\"", "summary": "pedicura", "updated": "2019-05-01T14:25:51.642Z", "timeZone": "America/Argentina ...

Can we leverage protractor's by.cssContainingText for dynamic text conditions?

I am looking for a way to conditionally change text content in my web project, but I'm facing a challenge since the conventional methods seem limited. The cssContainingText function typically accepts string or regular expression values. Is there a wor ...

Is there a restriction in Firefox/ CORS that disallows the use of application/json contentType in POST requests

I was attempting to send a JSON via POST request using Ajax to my server, but every time I tried, it was blocked by CORS. Despite researching the reasons for this blockage, I couldn't find a solution. One commenter even suggested that POST requests wi ...

What is the protocol for managing this exception? (specifically when a throw occurs within a callback function nested inside

Exploring the intricacies of exception handling and promises in Node.js is the focus of this query. By dissecting a simplified snippet of code, I aim to discern the similarities and differences between how exceptions are managed and promise/async functions ...

Why won't my Chrome content script load even though I have the correct syntax and have tried troubleshooting?

I'm facing an issue with my extension where the file content.js is not being loaded on any webpage despite trying multiple troubleshooting steps. I've tried different permissions, changing site patterns, reinstalling, restarting Chrome, adjusting ...

Is it possible to utilize setTimeout to demonstrate the execution of a while loop visually?

I am working on a function that generates random numbers between 1 and 6 until it matches a target value of 3. I want to create a visual effect where each randomly generated number is displayed on the page, but I'm facing some challenges with delays. ...

Adding the Authorization header in an Ajax request within ExtJS can be easily done by including the

I've been struggling to upload a file using ExtJS and web API. The issue I'm facing is that when trying to send an authorization header to the server, it always returns as null. I even attempted to include the header in the XHR request within the ...

The HTML elements on the webpage are showing up incorrectly

When visiting thedaystaragency.com/home and scrolling down to our services section where the lightbulbs are located, it is apparent that they are misaligned and not functioning properly. I have provided the code that I am currently using, but I had to remo ...

Stop the time-dependent function from executing within a specific condition

Here is the code snippet I am currently working with: var w = $(window); var $navbar = $('.navbar'); var didScroll = false; w.on('scroll', function(){ didScroll = true; }); function AddScrollHeader(pxFromTop) { setInterval(fun ...

Calculating the average value of an attribute in an array using Mongodb (Mongoose)

Seeking assistance with a query to find sellers near users based on location input and sorting them by average rating. Is this achievable? Snippet of the model including an array of reviews: const sellerSchema = new mongoose.Schema({ _id: Mongo ...

Generate a refined selection of options for a secondary dropdown menu sourced from a database

There are two dropdown lists in my project. One is dynamically populated based on user selections, while the other is filled with data from a database. The second list should be filtered according to the choice made in the first dropdown. The values in th ...

Display personalized error messages using jQuery and PHP

I implemented an Ajax autocomplete feature on an input field within a form using jQuery. Here are the ajax settings I have set up: $.ajax({ type: "POST", url: myUrl, data: $("#id__form").serialize(), success: function(data){ ...