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

Sharing context sub files in Next.js can be easily accomplished by following a few simple

These are the pages on my website: /pages /gift /[slug] index.tsx /personalize index.tsx In /gift/[slug]/index.tsx, I have a component called GiftProvider that looks like this: return ( <GiftProvider gift={gift}& ...

The hamburger menu unexpectedly appears outside the visible screen area and then reappears at random intervals

My website has a hamburger menu for mobile devices, but there's a problem. When the page loads on a small screen, the hamburger menu is off to the right, causing side scrolling issues and white space. I thought it might be a CSS problem, but after exp ...

Tips for preventing my component from being duplicated during the development process

I found a helpful guide on creating a JavaScript calendar in React that I am currently following. After implementing the code, I successfully have a functional calendar UI as shown below: // https://medium.com/@nitinpatel_20236/challenge-of-building-a-cal ...

Guide on sending a JavaScript variable to PHP using AJAX

I am currently utilizing the following JavaScript code to obtain data from a td element when a button is clicked within an onclick event. function rfk(element) { var element = element.parentElement.parentElement; var id = parseInt(element.childre ...

jQuery Autocomplete without dropdown menu suggestion available

I'm working on a form for my webpage and I want to enhance user experience by adding autocomplete functionality. The goal is to suggest existing names as users type in the 'name' input text box. Although I can see in my console that it&apos ...

ui-jq flot graph with lazy loading

I am working with this HTML code: <div id="test" ui-jq="plot" ui-options=" [ { data: {{line}}, points: { show: true, radius: 6}, splines: { show: true, tension: 0.45, lineWidth: 5, fill: 0 }, label: 'Akademi' }, ], { ...

Applying the jqtransform plugin to all forms except for one

We've implemented the jQuery jqtransform plugin to enhance the appearance of our website's forms. However, there is one particular form that we'd like to exclude from this transformation. I made adjustments to the script that applies jqtrans ...

Creating dynamic qtip2 tooltips is an effective way to enhance user interaction on

I am facing an issue where all tooltips work perfectly fine when the page loads, but stop working after data refreshes through ajax. How can I resolve this problem? $(document).ready(function() { // MAKE SURE YOUR SELECTOR MATCHES SOMETHING IN YOUR HT ...

What is the best way to incorporate a text box along with a submit button that triggers a callback to a javascript function when clicked, utilizing either plain javascript or jQuery?

As a beginner in the world of JavaScript, I'm struggling to find the solution to this problem. Any assistance would be greatly welcomed. ...

Creating a Sudoku game board using underscore templates

Currently, I am in the process of constructing a Sudoku board using underscores templating. However, I have hit a roadblock when it comes to tackling the mathematical aspects necessary for deriving the table structure. My approach involves utilizing a 1d ...

Explore one of the elements within a tuple

Can we simplify mapping a tuple element in TypeScript? I'm seeking an elegant way to abstract the following task const arr: [string, string][] = [['a', 'b'], ['c', 'd'], ['e', 'f']] const f ...

Managing state changes in React can be a complex task, but

As a newcomer to React, I am currently working on creating an icon menu. However, I am facing an issue with my handleChange function not functioning as expected. While the icon Menu and possibleValues menu are visible, I am unable to select any of the op ...

Tips on customizing the appearance of two Material-UI Sliders across separate components

Looking to customize two sliders, each within their own react component. Slider in the first component const customizedThemeSlider1 = createTheme({ overrides:{ MuiSlider: { thumb:{ color: "#4442a9", marg ...

When using React.js Material UI's CardActionArea with a flex display, the children elements may not automatically use the full width as expected

Getting straight to the point - I recently experimented with changing the display style property from block to flex, along with setting flexDirection: 'column' for the CardActionArea component. The main goal was to ensure that CardContent maintai ...

Creating a unique theme export from a custom UI library with Material-UI

Currently, I am in the process of developing a unique UI library at my workplace which utilizes Material-UI. This UI library features a custom theme where I have integrated custom company colors into the palette object. While these custom colors work perfe ...

Discovering how to navigate to a link within a web table using Cypress has been a challenge, as I keep receiving the error message stating that the element is not visible due to its CSS property being

Trying to click on the first enabled link in the 'Action' column of a web table has been proving difficult. In the example given, the first two rows do not have an enabled link, so the goal is to click on '8.5 AccountH' https://i.stack ...

Can JavaScript event listeners be compelled to trigger in a specific sequence?

Is there a way in JavaScript to receive notification or execute a callback function once an event has completed its propagation? Put differently, is it possible to 'prioritize' an event and ensure that it gets triggered after all other event lis ...

Experience the power of Vue Google Chart - Geochart where the chart refreshes seamlessly with data updates, although the legend seems to disappear

I have integrated vue google charts into my nuxt project. Whenever I select a different date, the data gets updated and the computed method in my geochart component correctly reads the new data. However, the legend or color bar at the bottom does not funct ...

Getting rid of the scrollbar in Internet Explorer

Instead of just removing the scrollbar, I want to ensure that scrolling capabilities remain intact. This is important because I want to create a 'slide show' effect on the website where users can click 'next' and scroll through content ...

Problems that seem to loop endlessly

I was working on some algorithm challenges from a coding platform, and I hit a roadblock with the "The Final Countdown" challenge. Here's what the challenge required: Provide 4 parameters (param1, param2, param3, param4), print the multiples of para ...