How can I create 3 conditions in an AJAX request to verify a user's ID?

I am trying to create 3 conditions in Ajax to check when creating a new user id. It works for 2 conditions (username can be used and username is already in use), but I encounter a problem when the user leaves the username field empty, and it still displays "username can be used". I attempted to use if(data == ""), but it did not work. Can anyone help me please? I apologize for being a beginner in JavaScript and still learning.

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="jquery-1.8.3.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    $('#username').change(function(e){
        $('#pesan').html("<img src='loading.gif' />checking...");
        var username = $('#username').val();
        $.ajax({
            type:"POST",
            url:"chk2.php",
            data:"username="+username,
            success: function(data){
                if(data == "")
                {
                    $('#pesan').html("<img src='failed.png' /><span style='color:green;margin-left:10px;'>Cannot Be Empty!!!</span>");
                }
                else
                {
                    if(data == 0){
                        $('#pesan').html("<img src='accept.png' /><span style='color:green;margin-left:10px;'>Username can be used</span>");
                    } else {
                        $('#pesan').html("<img src='failed.png' /><span style='color:red;margin-left:10px;'>Username is already in use</span>");
                    }
                }   
            }
        });
    });
});
</script>
</head>


<body>
<table>
    <form>
        <tr>
            <td><label for="username">Username</label></td>
            <td>:</td>
            <td><input type="text" size="20" name="username" id="username"/></td>
            <td><span id="pesan"></span></td>
        </tr>
        <tr>
            <td><label for="password">Password</label></td>
            <td>:</td>
            <td><input type="password" size="20" name="password" id="password"/></td>
        </tr>
        <td><input type="submit" value="submit" name="submit" /></td>
    </form>
</table>
</body>
</html>

for chk2.php

<?php
mysql_connect("localhost", "root", "");
mysql_select_db("ptmjp");

$username = $_POST['username'];

$sql = mysql_query("select code_item from stock where code_item='$username'");
$find = mysql_num_rows($sql);

echo $find;
?>

Answer №1

In my opinion, using data = '' and data = 0 yield the same result. 0 is often considered equivalent to null, so I suggest replacing 0 with something else.

Answer №2

I have the solution, apologies if it seems complicated. To simplify, just add a condition in chk2.php

if($username == "")
{
    $find = 2;
    echo $find;
}
else
{
    $sql = mysql_query("select code_item from stock where code_item='$username'");
    $find = mysql_num_rows($sql);
    echo $find;
}

So, change the JavaScript to check if 1 means already, 0 means yes, and 2 is empty. Thank you for your feedback.

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

Populate a database with information collected from a dynamic form submission

I recently created a dynamic form where users can add multiple fields as needed. However, I'm facing a challenge when it comes to saving this data into the database. You can view a similar code snippet for my form here. <form id="addFields" me ...

"Encountering an error retrieving weather forecast API in JavaScript - issue with

I've been attempting to fetch the weather forecast API JSON in a similar manner to how I accessed the current weather API, but unfortunately, it doesn't seem to be working no matter what approach I take. let inOneDay = { fetchWeather: functio ...

What is the best way to eliminate duplicate items in JavaScript?

Note: I am aware that we use Set to eliminate duplicates in an array. I have a date dropdown. When I select a date, it displays the date correctly in a list. However, the problem arises when I select an already chosen date, it still shows up in the list. ...

Creating dynamic Ionic slides by fetching data from a database

I am currently experimenting with Ionic. Web development is not my strong suit, so I may be a bit off the mark. However, I would like to retrieve data from an SQLite database and display it on an ion-slide-box. Here is what I have attempted: function sel ...

Problem with IE off-canvas scrolling

Currently, I am facing an issue with the scrolling functionality of an off-canvas sidebar on my Joomla 3 website. It seems to be working fine in Chrome and Firefox, but when it comes to Internet Explorer, the visible scroll bar refuses to move when attempt ...

Blunder! Error code EINVALIDTAGNAME encountered while trying to install a package

I'm encountering an issue while trying to add a new package to my React application. The error I'm receiving is: $ npm install xlsx npm ERR! code EINVALIDTAGNAME npm ERR! Invalid tag name "react-scripts start": Tags may not have any characters th ...

Unable to perform a fetch request in IE9 after the page has finished loading

I'm currently encountering an issue with my Node and Express server setup. I have a separate API on a different server that needs to be accessed, but everything works fine except in IE9. The problem arises when I try to make a call to the API after lo ...

Navigating with Buttons using React Router

Header: I need help figuring out how to properly redirect to a new page when clicking on a Material UI button using the onClick method. Specifically, I am unsure of what to include in my handleClickSignIn function. Here is a snippet of code from my Header ...

Create custom AngularJS directives for validation and store them in a variable

Through the use of AngularJS, I've developed a directive called "integer" that invalidates a form if anything other than integers are entered. Because I'm generating the page dynamically by fetching data from the database, it would be helpful to ...

Bundling sub-components using Rollup for NodeJS application packaging

My ES6 library consists of several sub-modules arranged like this: - package.json - lib - my_package - file1.js - file2.js - sub_module1 - file3.js - file4.js Currently, I import modules within my package using file resolution r ...

Ways to link a Javascript or Jquery function to an HTML form

I am looking to develop a form that can extract email addresses from input text. While I know there are many scripts available that can do this quite easily, my goal is to create one on my own. After reading, researching, and experimenting with differ ...

How can I resolve the "web page not found" error when using jQuery .replace()?

Working on HTML and javascript/jquery scripts, I have encountered a peculiar issue. My script utilizes a for-in loop to iterate through a JavaScript object, substituting specific patterns in HTML-formatted lines with data from the object using jQuery .appe ...

Removing div elements containing specific text using jQuery

Hello everyone, I am trying to remove all divs that contain a specific part of a string. Does anyone know how I can do this? This is what my original HTML looks like: <div class="article-options_4"></div> And this is the new HTML structure, ...

Implementing a Tri-state Checkbox in AngularJS

I've come across various discussions on implementing a 3-state checkbox with a directive or using CSS tricks (such as setting 'indeterminate=true' which doesn't seem to work). However, I'm curious if there's another method to ...

Transmitting intricate Javascript Array to ASP.NET Controller Function

I am facing an issue with sending a complex JavaScript array to my asp.net mvc6 controller method. I have tried two different methods to pass the data, but neither seem to be working for me. public IActionResult TakeComplexArray(IList<ComplexArrayInfo ...

Employing both Angular 1 and Angular 2 in conjunction

As a newcomer to angular, this is my first experience. My ultimate goal is to incorporate the following component into Angular 2: While I have some knowledge of JavaScript, I am attempting to integrate an Angular 1 library into an Angular 2 project. Aft ...

Attempting to showcase information in React

Having recently delved into React, I am attempting to display data (within a bootstrap modal) from MongoDB to React using an axios ajax request. Postman indicates everything is correct. However, React throws an error stating "TypeError: this.state.reviews. ...

Solving the puzzle of complex polymorphic object model deserialization in Java Jackson: Facing the JsonMappingException error – Unexpected token (START_OBJECT) instead

I am working with a hierarchy of objects described as follows: A B extends A C extends B D extends B E extends C F extends A and contains a reference to A The annotation for class A is defined as: @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS,include=Jso ...

What is the best way to iteratively fade in data from a MySQL database one by one?

How can I load data from a MySQL database and display it one by one with a fade-in effect? Let's say I have a total of 40 images stored in the database. First, I want to display each image like this: <li class="img" style=" list-style: none; flo ...

Just starting out with JavaScript - updating the appearance of an element

Based on the value of a boolean, I am looking to control the visibility of specific tabs in my sidebar when the page loads. var someVar = true; function show_ifTrue() { if (Boolean(someVar) == true) { document.getElementById('x'). ...