Complete the form by first implementing an AJAX control when submitting

I am currently working on a project that involves saving data from a form into a database. The aim is to verify if the data entered is correct (having a necessary key and at least one value), as well as checking if the key already exists in the database. While the initial part of validating parameters has been completed successfully, I am facing an issue with submitting the form. Below is the code snippet:

function insertControl() {

var insertError= $("#insertError");
var key = $.trim($("input[id='key']").val());
var value1 = $.trim($("textarea[id='valueITA']").val());
var value2 = $.trim($("textarea[id='valueGBR']").val());
var value3 = $.trim($("textarea[id='valueAUS']").val());
var value4 = $.trim($("textarea[id='valueUSA']").val());
var value5 = $.trim($("textarea[id='valueFRA']").val());
var id = $.trim($("input[id='control']").val()); 
var controlled= $.trim($("input[id='controlled']").val());
event.preventDefault();
if (key === "") {

    if (value1 === "" && value2 === "" && value3 === "" && value4 === ""
            && value5 === "") {
        insertError
                .html("KEY required<br>at least a value required");

    } else {
        insertError.html("KEY required");
    }
} else {
    insertError.html("");

    if (value1 === "" && value2 === "" && value3 === "" && value4 === ""
            && value5 === "") {
        insertError.html("at least a value required");

    } else {
        if (id == "") {
            if (controlled == "") {
                return control();
            } else if (controlled== 'ok') {
                if (!confirm('are you sure?'))
                    return e.preventDefault();
                document.getElementById('form').submit();
            }

        } else {
            if (id != "") {
                if (!confirm('are you sure??'))
                    return e.preventDefault();
                document.getElementById('form').submit();
            }

        }

    }
}

};

If the form is correctly filled out and there is no ID present (indicating the creation of a new record instead of editing), it triggers a function that initiates an AJAX call. This call checks the provided key against existing records in the database through a servlet and returns JSON data.

Below is the corresponding code for this functionality:

function control() {
$
        .ajax({
            url : 'edit',
            data : {
                key : $('#key').val()
            },
            success : function(data, status, xhr) {
                var insertError = $("#insertError ");
                var labels = data.length;
                if (labels == 0) {
                    $('#controlled').val('ok');
                    return insertControl();

                } else if (dati > 0) {
                    insertError
                            .html("this key is already used");
                    return event.preventDefault();
                }

            },
            error : function(req, status, err) {
                console.log('Something went wrong', status, err);
            }
        })

The verification process functions correctly but the submission fails when creating a new label. Editing, however, manages to submit without issues. I have integrated this function using the onsubmit attribute within the HTML file.

Answer №1

Solution provided

I attempted to insert it in the callback function (I extracted the entire control() and placed it where I was invoking it in the other function) but it did not produce the desired result. Perhaps I implemented it incorrectly?

A proper implementation would resemble:

if (id != "") {
  confirm('Are you sure?', document.getElementById('form').submit)
  return e.preventDefault();
}

function confirm(question, callback){
  /* Display modal */
  /* Take action on user confirmation */
  function userConfirm(){
    callback();
  }
}

Using jQuery, this can be achieved as follows:

if (id != "") {
  confirm('Are you sure?', $('#form').submit)
  return e.preventDefault();
}

function confirm(question, callback){
  /* Display modal */
  /* Take action on user confirmation */
  function userConfirm(){
    callback();
  }
}

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

Ajax - Every single request has been successfully fulfilled

I am struggling to determine when all my Ajax requests are finished in order to call another function. I have attempted to use various methods with native Ajax functions in Chrome, but none of them seem to be working for me. Can someone please help me? H ...

javascript execute a function when a click event occurs

I came across this code online that successfully creates a button document.write(nomedispositivo) var r=$('<input/>').attr({//beginning of button type: "button", id: "field" , value: "Turn On", However, when I add the line: on ...

Update the styling of a CSS div based on certain conditions

Is it possible to have a centered fullscreen main section at the very center of the webpage? <div id="main"></div> The main section will display a default web page: <script> $("#main").html('<object data="http://www.myweb.com"/ ...

Node.js functionality for exporting excel files along with database integration

I am currently exploring the world of node.js and its endless possibilities. In the early stages of planning an application project, I envision creating a system that tracks employee task statuses. The admin will have the ability to export Excel sheets co ...

The VueJs Method has the ability to directly alter a given response

Within my parent component, I am connecting to the backend using a query. Through interactions with the navbar and utilizing my activeView data in the parent component, I trigger the rendering of a new child page upon clicks and pass a prop from the respon ...

Deliver an index.html file upon server creation

My goal is to have the server load a file called index.html when it is created. Currently, when I run the server.js file using node, it responds with text using res.end("text"). However, I want the index.html file to be displayed instead. I attempted to a ...

Remove a field from a JSON array

Consider the following JSON array: var arr = [ {ID: "1", Title: "T1", Name: "N1"}, {ID: "2", Title: "T2", Name: "N2"}, {ID: "3", Title: "T3", Name: "N3"} ] Is there a way to remove the Title key from all rows simultaneously without using a loop? The r ...

Having trouble implementing Bootstrap Progress Bar with AJAX in webpy

I am currently working on a web application using webpy and dealing with a Bootstrap progress bar in the template HTML file. To update this progress bar dynamically, I aim to utilize jQuery AJAX calls to fetch data from the server. In order to achieve thi ...

Using React to trigger a child component's function upon clicking a tab

I need assistance with creating a React app that includes two tabs (Tab1, Tab2). When Tab2 is clicked, I want a message to appear in the console saying 'Function A is called'. Unfortunately, the code I have currently does not display the message ...

What could be causing my JavaScript/jQuery code to malfunction when dealing with checkboxes?

My code is supposed to select and disable checkboxes based on which radio button is clicked. For example, when Zero is selected, all checkboxes should be highlighted and disabled, except for the zeroth checkbox. However, this behavior does not consistent ...

Compose/erase content one character at a time

I am attempting to change text character by character, showing the text character by character, deleting the text character by character, and then displaying another one character by character. What I currently have? var i = 0; var terms = ['text & ...

Access numerous data points using ajax and php, sans the need for Jquery

Exploring website coding has been an amazing journey for me, and I've come to realize that JavaScript and Ajax play vital roles in creating a standout website. However, my internet research didn't yield very helpful results. Most of the code exam ...

The Yii yiiactiveform function remains undefined when clientValidation is disabled

I am currently using Yii 1.1.14 Instead of using Yii's ajax validation or client validation, I am using a form to capture an email. <?php $form = $this->beginWidget('CActiveForm', array( 'id' => 'form-newsletter ...

The 'import' statement is not functioning properly within a script in the rendered HTML

While working on an express application, I've encountered a recurring error that I can't seem to solve. The error message is: "GET http://localhost:3000/javascript/module2 net::ERR_ABORTED 404 (Not Found)" Could someone kindly assist me in ident ...

How do I convert the ImagePicker type to Base64 in Ionic Capacitor?

I am currently developing an app using Ionic (Angular-based) along with Capacitor Plugins, specifically the Camera Plugin. The main feature I am working on involves allowing users to choose up to 5 images from their gallery. To accomplish this, I have impl ...

I am looking to display data in Angular based on their corresponding ids

I am facing a scenario where I have two APIs with data containing similar ids but different values. The structure of the data is as follows: nights = { yearNo: 2014, monthNo: 7, countryId: 6162, countryNameGe: "რუსეთის ...

What is causing XMLHttpRequest to not accept my JSON data?

I've recently created a basic PHP program that retrieves data from a database, structures it into a PHP array, and then converts it into JSON format: $i = 0; while($row = mysqli_fetch_array($result)) { $output[$i] = array(); $output[$i]["tag"] = ...

The Mean Stack by Bitnami

After setting up the Mean Stack Manager, I encountered an issue. When running a command in the node terminal like console.log("Hello World"), it runs smoothly. However, if I place a Javascript sample file in any folder within the mean stack install directo ...

When using the HTML5 draw img feature, only the top 1/4 of the image will be

I am having trouble loading a full image into canvas. Currently, it only displays the top 1/4 of the image regardless of which one I use. Any help would be greatly appreciated. Here is the code snippet in question: var canvas = document.getElementById(&ap ...

Using Kinetic JS to overlay a PDF file with an additional layer

I am seeking to overlay a layer on top of a PDF file (using PDF JS) with the help of Kinetic JS. This layer will be utilized for adding annotation comments to the PDF file. However, my issue lies in the fact that each PDF document's canvas has differ ...