XMLHttpRequest request shows blank result

Issue:

After clicking the submit button on my HTML form, a JavaScript function is called with an Ajax request. The request returns successfully, but the result disappears quickly.

I'm curious if I may be overlooking something here (besides jQuery, which would make it easier, but xmlhttprequest is currently a requirement).

Below is my code - perhaps there's a small mistake I've missed (fingers crossed) as it has been some time since I worked with Ajax.

HTML Code:

<body>

   <form>
       <label>Name:</label>
       <input type="text" id="name" value="test1" placeholder="Your name" >

       <label>Email:</label>
       <input type="email" id="email" value="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="83f7e6f0f7b1c3e2e0eee6ade0ecee">[email protected]</a>" placeholder="Your email" >

       <label>Country:</label>
       <input type="text" id="country" value="test3" placeholder="Your country" >

       <input type="submit" value="Submit Form" onclick="postRequest()" >
   </form>
   <div id="repsonse"></div>
    <script src="scripts.js"></script>
</body>

JavaScript:

function postRequest()
{
   //data from the form
   var name = document.getElementById('name').value;
   var email = document.getElementById('email').value;
   var country = document.getElementById('country').value;
   var submitForm = "submitForm";

   //ajax objects
   var http = new XMLHttpRequest();
   var url = "functions_ajax.php";
   var params = JSON.stringify({ callFunction : submitForm, name : name, email : email, country : country });

   //alert(params);

   //Deal with ajax components
   http.open("POST", url, true);
   http.setRequestHeader("Content-type", "application/json; charset=utf-8");
   http.send(params);

   http.onreadystatechange = function() {

    //alert("Checking Status "+http.status+" "+http.readyState);

    if(http.readyState == 4 && http.status == 200) {
        //Return the data from the ajax request
        console.log(http.responseText);
        document.getElementById("repsonse").innerHTML = "<h1>Success!</h1>";
    }
    else
    {
       console.log(http.responseText);
       console.log(http.status);
       document.getElementById("repsonse").innerHTML = "<h1>No Cigar! HTTP Status == "+http.status+" </h1>";
    }
} 
}

Answer №1

By clicking the submit button, you trigger the form submission process which then causes the page to refresh.

To prevent this quick solution is to modify the input element like so:

<input type="button" ... />

This adjustment will halt the form submission from occurring.

Another approach is to access the event object within your handler function. You can achieve this by setting up the event handler using JavaScript. Assign an ID (e.g. "myButton") to your button and connect the handler as follows:

document.getElementById("myButton").onclick = function(e) {
    // ... body of your function here
    // or, call postRequest() here
    e.preventDefault();
}

In this case, remove the onclick attribute from the button since the function is bound to the click event via JavaScript.

This will successfully prevent the form submission.

Alternatively, attach an onsubmit handler to your form. Provide an id (such as "myForm") to your form and utilize:

document.getElementById("myForm").onsubmit = function(e) {
    e.preventDefault();
}

You may also invoke postRequest() from the form's onsubmit handler, but be sure to retain the submit button in its original state rather than changing it to a regular button.

Ensure that when establishing these event handlers, you place them within a script at the bottom of the page or in a function executed during or after the window's onload event.

Answer №2

Consider including the line e.preventDefault() at the beginning.

Note: Disapproving without providing feedback for a suggestion is disappointing.

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

Discover how to access the rotation of an object within ThreeJS based on

Currently in my code, I have implemented rotation restrictions around a specific axis using the following snippet: if (obj.rotation.x > -0.5) { // execute rotation } Initially, this setup worked perfectly. However, things took a turn when I introd ...

Locate a button element and dynamically assign an identifier using jQuery or JavaScript

I am currently working on a webpage that contains two forms, both enclosed within a <DL> element. <dl> <form action="" method="POST" style="display:inline-block;"> <dl><dt></dt><dd><input class="submit" typ ...

Testing a Vue component that includes a Vuetify data table with customized slots

I have been struggling to write a Jest test for a simple component that includes a nested v-data-table component. While the page renders correctly in the browser, my test keeps failing. The problem seems to lie with the template I am using for the slot - ...

What could be causing the dictionary error in my MVC Application when accessing the partial view?

In my MVC web app, I have an edit view that includes some partial views. These partial views are meant to allow users to add data to a dropdown list if it is missing. While the partial views work in the create view, they encounter an error when used in the ...

Update or Delete BreezeJS EntityManager After Losing Instance Reference

In the process of developing a CRM application with a single-page application structure, I am integrating BreezeJS and AngularJS. The implementation involves utilizing dynamically-generated tabs to display various modules. Each time a user clicks on a menu ...

What could be the reason for meteor not injecting the text from my template helpers?

My goal is to dynamically generate a table displaying two different sets of data. Despite having verified returns from my database, the rendered page does not show the corresponding HTML elements as expected. Here is the template and HTML code: <templ ...

The plugin 'vue' specified in the 'package.json' file could not be loaded successfully

There seems to be an issue with loading the 'vue' plugin declared in 'package.json': The package subpath './lib/rules/array-bracket-spacing' is not defined by the "exports" in C:\Users\<my_username>\Folder ...

Here's a method of sorting through an array of objects and displaying all objects that include a specific keyword in one of their values

I am currently working on a project involving an array of book objects. My task is to display a list of all books that have either "companies" or "people" in their title using console.log. const books = [{ title: 'How to win friends and influence ...

Utilizing JavaScript to Load an HTML File in a Django Web Development Project

Having a django template, I aim to load an html file into a div based on the value of a select box. The specific target div is shown below: <table id="template" class="table"> Where tables are loaded. </table> There ex ...

The data values are transformed following a JSON AJAX POST request with a percentage symbol

I'm facing an issue while developing a slide editor using AJAX. I have a PHP script with multiple functions that can be accessed via different GET parameters. Everything works smoothly until I try to save the slides, at which point the value of transf ...

What causes the oninput event to act differently in Angular as opposed to regular JavaScript?

As I delve into learning Angular with TypeScript, I've encountered some inconsistencies compared to JavaScript that are puzzling me. Take for example this function that works flawlessly with pure JavaScript, where it dynamically sets the min and max a ...

Obtaining JSON values by key name using JQuery

I am trying to extract JSON data using an HTML attribute How can I retrieve JSON values based on the translate attribute and "ed" key? JSON FILE { "open" : [ { "en": "Open", "ed": "Opened ...

Unraveling the mystery: How does JavaScript interpret the colon?

I have a quick question: When I type abc:xyz:123 in my GoogleChrome browser console, it evaluates to 123. How does JavaScript interpret the : symbol in this scenario? ...

Having trouble understanding why ng-resource refuses to return an array

I've recently encountered an issue while using AngularJS and NGResource. For some reason, every time I try to use the query function, I receive an empty array in return. Within my controller, the code looks like this: Task = $resource('/tasks&a ...

Modify the index in the creation of a json

I am trying to create a JSON object using the code below: var myJSONObject = []; var id = "1", value = "I'm a value !"; myJSONObject.push({id:value}); When I display this construction, it shows: [{"id":"I'm a value !"}] However, I want it to d ...

Function for Duplicating jQuery Events

I'm currently facing an issue where every time the browser is resized, a function is triggered. This function can turn a side panel into an accordion if the screen width meets certain criteria, or it can just display as an open side panel on larger sc ...

Combine two pieces of data from a JSON object using Angular's ng-repeat

Trying to organize data from a separate array into one section of a table. The first JSON named "names" : [ { "name": "AAAAAA", "down": "False" }, { "name": "BBBBBB", "down": "Tru ...

Searching for a client-side element within an update panel using code-behind: A step-by-step guide

While working on a user control in asp.net, I encountered a significant challenge in locating the client side HTML element positioned within an update panel. The .ascx file contains the following code snippet: <asp:UpdatePanel ID="UpdatePanel1" runat= ...

Using jQuery's AJAX method to retrieve data from C# on page load

Despite finding numerous posts on the subject, none of them have been helpful to me. I am currently sending data using jQuery AJAX to the same page and handling it in the page_load function. Is there a method to return data back to the calling AJAX reques ...

Attempting to retrieve the position of an image within an array upon clicking

function displayGalleryIndex(){ console.log($(this).index()); } $("body").on( "click", "#gallery img", displayGalleryIndex); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <section class="grid- ...