employing an ajax function for sending user information upon clicking

I am struggling to comprehend this issue with using the addUser function to input user data only if the email goes through validation. All of this is initiated by clicking a button.

Below is the addUser function:

function addUser(username, email, callback) {
    var xhr = new XMLHttpRequest();
    var response;
    var success = (!!Math.round(Math.random()));
    
    if (!success){
        response = JSON.stringify({
            success: success,
            error: "Oops, something went wrong!"
        });
    } else {
        response = JSON.stringify({
            success: success,
            user: {
                username: username,
                email: email
            }
        });   
    }
    
    xhr.open("POST", "/echo/json/");
    xhr.onload = function () {
            if (xhr.status === 200) {
                callback(JSON.parse(xhr.responseText));
        }
    }
    xhr.send("json=" + response);
};

Here's my progress so far. I have attempted to invoke addUser, establish a success handler for the ajax response, enter in the email and username values. But none of it seems to be working.

function validation() {
    var emailRegex = /^\w+[\w-+\.]*\@\w+([-\.]\w+)*\.[a-zA-Z]{2,}$/;
  var usernameInput = document.getElementById("userName").value;
  var emailInput = document.getElementById("userEmail").value;
  var emailError = document.getElementById('emailErr').textContent = "please enter a valid email address";
  if(!emailRegex.test(emailInput)) {
        emailError
  }
}
function addUserClient() {
    validation();
}

document.getElementById('addUserButton').addEventListener('click', addUserClient);

Answer №1

If you're looking for a reliable tool to handle promises and requests seamlessly, I suggest checking out axios. It's easily accessible through a CDN as well. Personally, I find the bare bones implementation of Ajax too cumbersome and error-prone. Feel free to reach out if you'd like a vanilla JS solution.

function addUser(username, email, callback) {
    // Utilizing axios for an ajax post request
    axios.post("/echo/json", {
            // Insert your form fields here
            username,
            email
        })
        .then(res => {
            // Response from server can be accessed in res
        })
        .catch(err => {
            // Error handling goes here
        );
}

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

Tips for breaking down a collection of objects and nested arrays into distinct arrays containing individual pieces of data

I have a list of objects structured like this: [ { alert_count: 3, alert_level: {value: 0, label: "ignore"}, count_dates: (3) ["2021-04-21T14:36:02.446Z", "2021-04-21T14:36:12.039Z", "2021-04-21T14:37:04.495Z"], sound_type: {_id: "606331d ...

Combining the elements within an array of integers

Can anyone provide insight on how to sum the contents of an integer array using a for loop? I seem to be stuck with my current logic. Below is the code I've been working on: <p id='para'></p> var someArray = [1,2,3,4,5]; funct ...

How can you modify the data within a Vue.js model using the model's method?

Trying to update the model with a simple action. After clicking the button, the data field "message" is changed to display "Good Bye!". However, it quickly reverts back to displaying "Hello Vue.Js!" immediately. How can you modify the value of the model ...

How can we prevent users from changing URLs or accessing pages directly in Angular 7 without using authguard?

Hey there! I am trying to find a way to prevent users from accessing different pages by changing the URL, like in this https://i.sstatic.net/E2e3S.png scenario. Is there a method that can redirect the user back to the same page without using Authguard or a ...

Invoke JavaScript function upon page load

There is a link on my page that, when clicked, opens a login popup. However, I am struggling to make it work on page load. I have spent a lot of time trying to figure this out, but nothing seems to be working. <a id="onestepcheckout-login-link" href=" ...

Unraveling a JSON array in PHP

Having trouble decoding a JSON object in PHP that is received from a JavaScript page? Here's how you can decode the JSON and store it in PHP such that $arr[0]=[1,2,34,5,2]; $arr[1]=[2,1,34,5,2]; $arr[2]=[8,1,34,5,2]; in PHP. after removing "myString ...

Difficulties encountered when attempting to perform a POST request to a Web API using JQuery

I am encountering an issue with my web API's POST method. When using HttpClient in a console app, everything works fine. However, when attempting to make a call using jQuery, the package variable returns null. Below is the current code snippet: $.aj ...

Using PHP and AJAX for deletion will only work on the initial row

I created a basic PHP blog platform. On the Add Post page, users can input a title and body text for their posts. These posts are displayed on the Posts page, where users also have the option to delete them. However, I encountered an issue where only the ...

Differences between Ajax and GET requests in jQuery

Similar Question: jQuery ajax() vs get()/post() Can someone help me understand the variances between jQuery ajax() and jQuery get()? Furthermore, which method would be more appropriate for loading data from a URL into a div after a user clicks on a l ...

Issue encountered while trying to create a JSON string using the jsoncpp library and the / operator

Having an issue with the JSONcpp library when trying to create a JSON object that includes the / operator (such as date: 02/12/2015). Below is the code snippet: JSONNODE *n = json_new(JSON_NODE); json_push_back(n, json_new_a("String Node", "02/05/2015")); ...

Unreliable Response from JEditable

I have encountered an unusual behavior while using the JEditable jQuery plugin to update data on my webpage. One specific field is not updating as expected, instead displaying the following message: EM29UPDATE NetLog SET grid = 'EM29&apo ...

"Keeping your HTML content up-to-date with AngularJS dynamic updates

I've noticed that when I upload changes to my AngularJS HTML partial files, there is a caching issue where the old data is displayed. It takes a few refresh actions before the changes become visible. Is there a way to make these changes appear immedi ...

How come I am not receiving any replies when using cUrl along with a class?

When I write my code without a class, it works perfectly and returns a "SUCCESS" response. However, when I encapsulate it within a class, it doesn't seem to work. Here is the full code: class THBS_API { private const call_url = "https://xxxxxxx ...

Enhancing JSON array in JMeter with the power of Groovy

In need of extracting a Non-Zero Account Number from the Accounts array provided in the JSON below. The Accounts have been successfully fetched and stored in a variable. { "glossary": { "title": "example glossary", ...

Enhancing image clips using jQuery techniques

Could someone help me figure out why the image clip value isn't changing when I move the range slider in the code below? $('#myRange').on('input', function() { var nn = $(this).val(); $("img").css({ 'clip': ...

Implementing access restrictions for modules in NodeJS

In Node, is it possible to limit access or permit access only to specific modules from a particular module? Should I consider replacing the require function and object in the global scope for this purpose? I have concerns about the security of a certain mo ...

Functionalities for retrieving nested JSON data structures

Currently, I am seeking a solution to implement a sequence where a .getJSON call triggers another function which then initiates another .getJSON call. I am repeatedly invoking a JSON method on my Controller and aiming to terminate this repetitive process ...

Is there a limit to the number of arguments the Python Selenium driver can handle

I've encountered an issue while attempting to retrieve JSON data in driver.get using Selenium. The error message indicates that I cannot use more than 2 arguments with this particular method. for d in data["screen"]: display = Display(visible=1, ...

Directing users to a specific section on another webpage can be accomplished using HTML, JavaScript, or

<nav> <div class='container-fluid'> <h1 class='logo'>Logo</h1> <ul class='list-unstyled naving'> <li><a href='index.html'>Home</a></li> ...

Immediately Invoked Function Expression in Javascript

const user = { name: "John", age: 30, lastName: "Smith" } (({name, lastName}) => { console.log(name); console.log(lastName); })(user); An error occurred: {(intermediate value)(intermediate value)(intermediate value)} is not function ...