The typeof operator is not functioning as anticipated when used with an ajax response

Trying to implement form validation using AJAX and PHP, but encountering issues with the typeof operator.

The validation works smoothly except when receiving an empty response, indicating that all fields have passed. In this scenario, the last input retains error classes, and the Cart div fails to transition to the Success div as expected upon successful submission.

A typical JSON response would look like this:

{
     last_name: "The Last name is required", 
     email: "The Email is required", 
     city: "The City is required", 
     np_branch: "The Np branch is required"
   }
   

Notably, values that pass through PHP validation are not added to the array. Additionally, error messages can vary for each key, making it impractical to check for specific error messages.

Code snippet:

 // AJAX request
   $.ajax({
     type: "POST",
     dataType:"json",
     data: {
       last_name: l_name.val(),
       email: email.val(),
       city: city.val(),
       np_branch: np_branch.val()
     },
     success: function(data) {
       console.log(data);
       // If all fields pass validation, hide Cart div and display Success div
       if (typeof(data['last_name']) == "undefined" && typeof(data['email']) == "undefined" && typeof(data['city']) == "undefined" && typeof(data['np_branch']) == "undefined") {
         $('.cart').css({ "display":"none" });
         $('.success').css({ "display":"block" });
       }

       // Handle 'last_name' error
       if (typeof(data['last_name']) != "undefined" && data['last_name'] !== null) {
         l_name.addClass("error");
         $('#l_name-err').css({ "display":"block" });
       } else if (l_name.hasClass('error')) {
         l_name.removeClass("error");
         $('#l_name-err').css({ "display":"none" });
       }

       // Repeat similar error handling for 'email', 'city', and 'np_branch'

     }
   });
   

Is there a more efficient approach to achieve this form validation?

Answer №1

Perhaps you could verify by checking (unless there was a misunderstanding in the logic):

// Check if data.last_name is defined and has a value, display error message if true, else remove it
if(data['last_name']) {
 l_name.addClass("error");
 $('#l_name-err').show();
} else {
  l_name.removeClass("error");
  $('#l_name-err').hide();
}

Additionally, the typeof statement should be written without parentheses as follows:

typeof data['np_branch'] !== "undefined"
instead of
typeof(data['np_branch']) != "undefined"

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

Transform your HTML audio player into a Vue component

I am in the process of converting an HTML player into a Vue component. Half of the component has been successfully converted, but the time control slider is still missing. Below is the original HTML code for the player: // JavaScript code for the audi ...

Changing an array in JavaScript within a function

When working with arrays in JavaScript, how can I mutate the value of an array inside a function? I'm aware that certain array methods can achieve this, but regular assignment doesn't seem to work. var arr = [4]; function changeArray(arr) { ...

Can you modify the value of the link identified as "#showCities" based on the city that is clicked on?

There is a link called "All Country" that, when clicked, opens a modal displaying a list of cities: <a class="city" id="showCities" data-toggle="modal" data-target="#modal2" href="">All Country</a> The modal lists all the cities associated wi ...

Dynamically loading a JSON file in JavaScript

Can you please review this code snippet? var scripts = {}; require = function(src){ var id = Math.round(+new Date()/1000); $.ajax({ url: src + '.json', type: 'GET', dataType: "json", cache: ...

Chat application using Node.js without the need for Socket.IO

Recently delving into the world of Node.js, I stumbled upon the fs.watchFile() method. It got me thinking - could a chat website be effectively constructed using this method (along with fs.writeFile()) in comparison to Socket.IO? While Socket.IO is reliabl ...

The inner class tree property of ZK cannot be accessed

I am encountering a similar issue to the one discussed in this question: Property not readable on a inner class in a TreeModel However, the solution provided does not seem to work for my case. I have successfully implemented my Entity and TreeModel for a ...

JQuery-1.7.1 presenting issues with Ajax functionality

I've been struggling for the past couple of days with an issue where I want to call a method of CodeIgniter through AJAX, but the method is not getting called. Despite my efforts, I haven't been able to find a solution yet. Below is a snippet of ...

How can I dictate the placement of a nested Material UI select within a popper in the DOM?

Having trouble placing a select menu in a Popper. The issue is that the nested select menu wants to mount the popup as a sibling on the body rather than a child of the popper, causing the clickaway event to fire unexpectedly. Here's the code snippet f ...

What methods are available to gradually increase a counter until it reaches a specific number by a designated date?

I have a unique idea for my website - I want to create a special counter that gradually increases to a specific number, but does so over the course of an entire year. Imagine starting at 0 and aiming to reach 35340340 after exactly one year has passed. It ...

To activate a function, simply click anywhere on the body: instruction

One of my latest projects involved creating a directive that allows users to click on a word and edit it in a text box. Once edited, clicking anywhere on the body should return the word back to its updated form. html <div markdown>bineesh</div& ...

Trigger Ajax only when a new row is added by the user in the SQL database using PHP Codeigniter

Avoiding frequent AJAX calls is necessary to prevent slowing down the POS system. We now prefer to trigger AJAX only when a user enters data from the frontend site, such as adding items to the cart. This helps in keeping the POS processes running smoothly ...

The React DevTools display components with the message "Currently Loading."

I am currently facing an issue with debugging some props used in my React application. When I try to inspect certain components, they display as "Loading..." instead of showing the normal props list: https://i.sstatic.net/RtTJ9.png Despite this, I can con ...

Tips for handling value updates when a user clicks a checkbox using jQuery

Having trouble with updating values when a checkbox is clicked. When the checkbox is clicked once, the value is added correctly. However, if the user rapidly clicks on the same checkbox multiple times, the value is not added or subtracted properly and gets ...

Change the color of the background in the Material UI Snackbar

Whenever I try to change the background color of the Snackbar by setting a className, it doesn't get applied properly. Instead, for a brief moment when the page renders, the desired background color appears and then quickly gets replaced. I've g ...

When utilizing the .replaceWith() function in jQuery, the event bindings do not stay intact

Here is a brief example. Please note that the .chat-reply class has a click event handler attached to it. The HTML (Reply Button): <div class="container"> <a href="#" class="btn small chat-reply">Reply</a> </div> When anothe ...

How to target only the parent div that was clicked using jQuery, excluding any

I have attempted to solve this issue multiple times, trying everything I could find on Google and stack overflow without success. At times I am getting the span element and other times the div - what could be causing this inconsistency? $(".bind-key"). ...

Which file from Next.js should I statically serve using Node?

Whenever I work with React, my standard process includes running npm build, moving the content to a directory named public in Node, and then including the following code snippets: node/app.js app.use(express.static(path.join(__dirname, 'public') ...

Contrast between v-for arrangements

Would anyone be able to clarify the distinction between these two v-for structures? <li v-for="item in items" :key="item"> </li> and <li v-for="(item, i) in items" :key="i"> </li> ...

The dynamic JavaScript in Bootstrap 4 seems to be malfunctioning, despite working perfectly in Bootstrap 3

I am currently implementing a dynamic modal feature using the code snippet below: // Show Ajax modal with content $(document).on('click', '[data-modal]', function (event) { event.preventDefault(); $.get($(this).data('moda ...

Divide a JSON dataset into two distinct JSON files and incorporate them within the code

My JSON file structure is as follows: { "rID": "1", "rFI": "01", "rTN": "0011", "rAN": "11", "sID&quo ...