Checking form input using AJAX validation before submitting

I am attempting to create a data input form, but I have run into an issue. Even when the form is empty, it can still be saved when the save button is pressed. How can I prevent saving if the input fields are empty?

Here is the code for my form: https://jsfiddle.net/bubyj5xj/


$(".btn_save_news_item").button().click(function() {
    var form = $("#form_news_item");
    var json = ConvertFormToJSON(form);
    $.ajax({
        type: "POST",
        contentType: "application/json",
        url: BASE_URL + "setting/news",
        data: JSON.stringify(json),
        success: function(response) {
            console.log(response);
            resetForm();
            reloadGrid();
        }
    });
});

Answer №1

let formElement = $("#form_news_item");  
if(formElement == "")
{
    alert("Please make sure to fill in all fields");
}
else
{
   $.ajax({
   type: "POST",
   contentType: "application/json",
   url: BASE_URL + "setting/news",
   data: JSON.stringify(json),
   success: function(response) {
   console.log(response);
   resetForm();
   reloadGrid();
   }
}

Answer №2

var formData = {'data': jQuery("form[name='put_ad_form']").serializeArray()};


Next, it is important to validate each value:

var regex = new RegExp(/^[A-Za-z0-9+*-]{1,10}$/);
if(regex.test(data.val)){
    .......
}

Alternatively

if(data.val == ''){
  alert('Please enter some text');
}

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

Unable to locate the JSON file for loading in ThreeJS

I am currently attempting to load an external model from Blender onto an Angular app using Three.js. I have been following a tutorial for guidance, found here. However, I have encountered an issue when trying to load the external file: loader.load('. ...

A pair of demands within an express service

Currently, I'm facing an issue in a project where I am attempting to create a service using Express that makes two external API calls. However, I am encountering an error in Express that is difficult to comprehend. It seems like my approach might be i ...

Is Ajax.dll creating a nuisance?

I have implemented Ajax.dll in my project and registered the class using Ajax.Utility.RegisterTypeForAjax(typeof(Default)) during page load. In the server side, I have created a function to return "Name" as follows: [Ajax.AjaxMethod(HttpSessionStateRequ ...

Testing with fundamental authentication

I have been working on developing tests using supertest for my server, but I've encountered a problem. All routes on the server require basic authorization. When I use Postman, I am able to input the login and password into the authorization tab and s ...

Spin the div in the opposite direction after being clicked for the second time

After successfully using CSS and Javascript to rotate a div by 45 degrees upon clicking, I encountered an issue when trying to rotate it back to 0 degrees with a second click. Despite my searches for a solution, the div remains unresponsive. Any suggestion ...

Is JSDOM capable of configuring exuberant ctags for a project setup?

Anticipating great javascript ctags support got me considering the possibility of using a project like to configure ctags for optimum vim usage. ...

The Google Maps v3 API is frustratingly only loading properly after a refresh, and the authentication process is

Whenever I try to load the Google Maps v3 API on my page, I encounter an error message that says: "custom.js:46 Uncaught ReferenceError: google is not defined". The following APIs are enabled on my key: Google Maps Directions API Google Maps Distance M ...

Having difficulties with binding 'this' in Angular/Javascript?

Currently, I am attempting to integrate the pullToRefresh package into my Angular application. Here is the code snippet: const ptr = pullToRefresh.init({ mainElement: '.dashboard-container', onRefresh() { ...

"Implementation of clearInterval function may not always result in clearing the interval

The scrolling process within the div element flows smoothly in both directions, however, it seems to encounter an issue when executing the scrollBack() function. Despite including a clearInterval() statement at the intended point, the interval does not a ...

triggering audible alerts for PHP AJAX operations

I'm attempting to include a sound notification whenever new data is added to the database. However, when I add it to the script above, it plays the audio every second. var count_cases = -1; setInterval(function(){ $.ajax({ type : "POS ...

Storing information within a global variable array or exploring alternative methods

I am currently working on a project in electron / node.js and need assistance with the following tasks: Importing data from excel/csv files Visualizing the data using d3.js Cleaning the data by removing duplicates, etc. Using the data for calcu ...

Transmit information from React to Node.js

I'm currently facing an issue while trying to send data from React to Node.js using Ajax. Unfortunately, I am not receiving the data on the Node.js side. My React code snippet looks like this: let id = item.id $.ajax({ url: '/post ...

Discovering the version of the Javascript library utilized on a website - a step-by-step guide

My quest is to uncover the versions of JavaScript libraries being utilized by popular websites. By using phantomjs.exe, I successfully identified the version information for jquery. However, I am currently at a loss on how to expand this capability to inc ...

What is causing the React text component to fail to show changes made to my array state?

I am currently in the process of learning React Native. I have been working on an app and encountered an issue while attempting to update individual elements within an array. Here is an example of the code: function MyApp() { const [array, setArray] = ...

Maintain synchrony of the state with swiftly unfolding occurrences

I developed a custom hook to keep track of a state variable that increments based on the number of socket events received. However, when I tested by sending 10 simultaneous events, the total value of the state variable ended up being 6, 7, or 8 instead of ...

Transform the JSON response

Is there a way to transform the following data into A-Apple, B-Apple, A-Mango? { "Apple": [ "A", "B" ], "Mango": [ ...

Tips for preventing curved links in a radial tree diagram created with d3

I am currently utilizing this code to generate a radial tree diagram for my data. However, I am looking to make a modification to eliminate curved links. My preference is for linear connections instead of curved ones as the curved links can make the visual ...

Tips for preventing repetition in http subscribe blocks across various components

Imagine a scenario where there is a service used for making HTTP request calls. There are two different components (which could be more than two) that need to send the same request using the same observables via this service. After receiving the result, it ...

Audio issues plaguing audio playback on Discord

After spending two exhausting days, I am still trying to figure out what is going on. I am currently working on a Bot for my Discord Channel that should play an audio.mp3 file when a specific command, like !laugh, is entered. However, despite trying variou ...

@SpringBootApplication is unable to retrieve static files

Located within the directory path: src/main/resources/static/ js css img etc.. Despite numerous attempts to configure addResourceHandlers, the static files remain undetected. The issue persists no matter what I try. ...