Initiate an AJAX call

Hey there, I have a piece of code that I need some help with.

<button onclick="sbt()" name="step1[save]" type="submit" class="btn-type5 next-btn-form pie" value="Далее">Send</button>
function sbt(){
var phone = document.getElementById('fld1').value;
        var xmlhttp;
        if (window.XMLHttpRequest)
        {
                xmlhttp=new XMLHttpRequest();
        }
        else
        {
                xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }}
        xmlhttp.open("GET","host.com/send.php?phone="+phone+"&t="+Date.now(),true);
        xmlhttp.send();
}

I'm trying to send this request asynchronously, but when I use xmlhttp.open(...,...,true), the request doesn't even reach the server. I've been monitoring it in Google Chrome console. However, if I manually run the sbt() function from the console, the request goes through just fine. Additionally, if I change to xmlhttp.open(...,...,false), it works as expected. Can someone please assist me with this issue? Thank you.

Answer №1

When the submit button is clicked, the form will be submitted immediately, causing the browser to navigate away from the current page and exit the JavaScript execution environment that initiated the Ajax request.

To prevent the default submission behavior of the form and use JavaScript instead, you can include the following code:

onclick="submitForm(); return false;"

(Consider utilizing a more modern approach to event binding using EventTarget.addEventListener instead of inline onclick attributes).

Answer №2

Is this the full code for your page?

Have you verified the order in which JavaScript files are loaded?

Please check out this example---> here (it includes a 3-second response delay)

<h2>AJAX async demo</h2>

<button type="button" onclick="callAjax()">Request data</button>
<div id="testDiv"></div>

<script>
function callAjax() {

    var xmlhttp;
    if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    } else { // code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function () {

        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            document.getElementById("testDiv").innerHTML = xmlhttp.responseText;
        }
    };

    xmlhttp.open("POST", "/echo/html/", true);
    var params = "html=test&delay=3"
    xmlhttp.send(params);
}
</script>

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

Extract the body.req object within a loop in a Node.js application

I'm looking to efficiently parse and save the body of a POST request using Mongoose in Node.js. Is there a way to use a for loop to accomplish this task, rather than manually saving every property? My ideal solution would involve something like: for ...

Enhancing Tables with Angular for Dynamic Translation and Filtering

I'm facing a challenge with my search feature in a basic table - <table> <thead> <tr> <th> Name </th> <th> Lastname </th> <th> Job Title </th> </tr> </the ...

What is the best way to attach to the beforeSubmit event of a dynamically loaded AJAX form in Yii?

Recently, I encountered an issue with dynamically loading a form via AJAX and attempting to bind the beforeSubmit event. Strangely, the event didn't seem to work as expected, causing the form to submit and the browser to navigate to a new page. This b ...

Showcase a sizable picture broken down into smaller sections

I am interested in creating a mapping application similar to Google Maps that can asynchronously load images from the backend. I am seeking guidance on where to begin and how to proceed in this endeavor. The ultimate goal is to have the image displayed w ...

Troubleshooting an Error with Ajax and PHP JSON Response

Having trouble with my website registration form. Getting 'null' as a response from the server when using json for data exchange. Here is the code: JavaScript code: $("#customer-form").submit(function() { var form_data = { c ...

Is it possible for JavaScript to access and read a local file from a web page hosted locally

I am interested in using html, css, and javascript to develop a user interface for configuring a simulation. This interface will be used to generate a visualization of the simulation and an output parameters file based on multiple input files. It is impor ...

Unpredictable preset inline styles for HTML input elements

While developing a full-stack MERN application, I encountered an unusual issue when inspecting my React UI in Chrome DevTools. If any of these dependencies are playing a role, below are the ones installed that might be contributing to this problem: Tail ...

A guide to retrieving JSON data with Javascript

I'm in the process of building a small website for weather forecasting. However, I've encountered an issue when trying to retrieve JSON data from accuWeather - I'm not getting any response. I've double-checked my request and it seems to ...

Encountering an Issue: The program is throwing a TypeError because it is unable to access properties of null when trying to read '

My goal is to upload an excel file using ng-click and the fileUpload($event) function defined in the app controller scope. I am utilizing xlsx to read the file in JSON format, but I encounter an error when running the code: <div> <input id ...

Learn how to implement the JQuery ReplaceWith function with the resources provided by materials.io icon

I would like the favorite_border icon to switch to the favorite icon when clicked. As we are using material.io and both icons have the class material-icons, I am unsure about how to implement this using jQuery. What steps should I take to achieve this? (w ...

Literal Route Waypoints Guidance Service

I am currently working on an angularjs directive that utilizes the Google Maps Direction Service. In my controller, I have a getFunction that watches for changes in a scope variable. Once the scope variable changes, it triggers the calculateAndDisplayRoute ...

No data provided in request for jQuery JSON ajax call

Currently, my server setup involves Django 1.4 running on Heroku with all requests being sent over HTTPS. When making ajax calls, the structure typically follows this pattern: var data = { username: form.find('input[name="username"]').val(), ...

Show a collection of files in a table format

Here is the current code I have: index.html <!DOCTYPE html> <html> ... </form> </div> </body> </html> And here is my code.gs function doGet() { return HtmlService.createHtmlOutputFromFile('index'); } ...

How is it possible to access a variable in a function that hasn't been declared until later?

While working on a Dialog component, I had an unexpected realization. export const alert = (content: string) => { const buttons = [<button onClick={()=>closeModal()}>ok</button>] // seems alright // const buttons = [<button onCli ...

Trouble shooting: Angular 2 Http get request not firing

I'm facing an issue where nothing happens when I try to subscribe to my observable. There are no errors in the console or during the build process. Below is the code snippet that I am using: My service getBlueCollars(): Observable<BlueCollar[]& ...

Struggling to receive a successful reply from a web service

Currently in the process of developing a web frontend for a web service, I am utilizing jQuery 1.5.1 as my JS framework and Firebug for debugging purposes. To ensure functionality, I tested the web service using the Firefox Extension "REST Client", which ...

Update the directive automatically whenever a change occurs in the root scope property

I am facing an issue with a directive that generates a random number. My goal is to reload or refresh this directive when a checkbox is toggled. Below is the code I have been using, but unfortunately, it's not working as expected. var app = angular. ...

The controller in ng-controller returns an undefined error when loaded using RequireJs

I have encountered an issue while loading the Angular application using requirejs. The ng-controller written in main.html loads directly but ends up being undefined. app.js define(['sfongApp', 'ng-grid', 'angular-bootstrap'] ...

Utilize $validators during blur/focus interactions

In my validation directive, I currently manually set the validation state like this: $element.on('focus', function() { $scope.$apply(function() { ngModelCtrl.$setValidity('length', true); }); }); $element.on('blu ...

Only one bootstrap collapse is visible at a time

Currently, I am using Bootstrap's collapse feature that displays content when clicking on a specific button. However, the issue I am facing is that multiple collapses can be open at the same time. I want to ensure that only one collapse is visible whi ...