Tips for customizing bootstrap code for registration form to validate against duplicate emails?

The contact_me form utilizes default code to handle success or failure responses from the server. The code calls msend_form.php for communication with the database and always returns true. It allows checking for pre-existing email addresses in the database. The challenge is to pass this information to the ajax code so that it can display an error not only based on the server response but also for existing emails. Below is the snippet from msend_form.js:

    
    $.ajax({
        url: "././mail/msend_form.php",
        type: "POST",
        data: {
            fname: firstName,
            gender: gender,
            email: email
        },
        cache: false,
        success: function() {
            // Handle success message
            $('#success').html("<div class='alert alert-success'>");
            $('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;")
                .append("</button>");
            $('#success > .alert-success')
                .append("<strong>Thank you for registering! </strong>");
            $('#success > .alert-success')
                .append('</div>');

            // Clear all fields
            $('#contactForm').trigger("reset");
        },
        error: function() {
            // Handle failure message
            $('#success').html("<div class='alert alert-danger'>");
            $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;")
                .append("</button>");
            $('#success > .alert-danger').append("<strong>Sorry " + firstname + ", it seems that my mail server is not responding. Please try again later!");
            $('#success > .alert-danger').append('</div>');
            // Clear all fields
            $('#contactForm').trigger("reset");
        },
    })

The PHP code in msend_form.php:

<?php
// Insert into SQL database
include '../db_connect.php';

// Check if passed fields are empty
if(empty($_POST['fname']) || empty($_POST['email']) || !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL)) {
    echo "No arguments Provided!";
    return false;
}

$fname = mysql_real_escape_string($_POST['fname']);
$email_address = mysql_real_escape_string($_POST['email']);
$gender = mysql_real_escape_string($_POST['gender']);
$ip = 1;

$sqlemail=mysql_query('SELECT * FROM `sdusers` WHERE email="'.$email_address.'"');
$res2=mysql_num_rows($sqlemail);

if($res2>=1) {
    echo 'Email already in use';
} else {
    // Insert query here
    $sql='INSERT INTO `sdusers` (fname, gender, email, ip, time_registered) VALUES ("'.$fname.'","'.$gender.'","'.$email_address.'","'.$ip.'",CURRENT_TIMESTAMP)';
    $res3=mysql_query($sql);
}

mysql_close($link);

return true;            
?>

The HTML code in index.php:

        
<form name="sentMessage" id="contactForm" novalidate>
    <div class="row control-group">
        <div class="form-group col-xs-12 floating-label-form-group controls">
            <label>First Name</label>
            <input type="text" class="form-control" placeholder="First Name" id="fname" required data-validation-required-message="Please enter your first name.">
            <p class="help-block text-danger"></p>
        </div>
    </div>
    <div class="row control-group">
        <div class="form-group col-xs-12 floating-label-form-group controls">
            <label>Email Address</label>
            <input type="email" class="form-control" placeholder="Email Address" id="email" required data-validation-required-message="Please enter your email address.">
            <p class="help-block text-danger"></p>
        </div>
    </div>
    <div class="row control-group">
        <div class="form-group col-xs-12 floating-label-form-group controls">
            <label>Gender</label>
            <select id="gender" name="gender" class="form-control">
                <option value="female">Female</option>
                <option value="male">Male</option>
            </select>
        </div>
    </div>

    <br>
    <div id="success"></div>
    <div class="row">
        <div class="form-group col-xs-12">
            <button type="submit" class="btn btn-outline-dark">Submit</button>
        </div>
    </div>
</form>

Thank you!

UPDATE:


$.ajax({
    url: "././mail/msend_form.php",
    type: "POST",
    data: {
        fname: firstName,
        gender: gender,
        email: email
    },
    dataType: "json",
    cache: false,
    success: function(response) {
        if(response.status == 1){
            // Successful submission
            // Display success message
            $('#success').html("<div class='alert alert-success'>");
            $('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;")
                .append("</button>");
            $('#success > .alert-success')
                .append("<strong>Thank you for registering! We will contact you once this app is deployed soon. </strong>");
            $('#success > .alert-success')
                .append('</div>');
        } else {
            // Submission failed
            // Display error message
            $('#success').html("<div class='alert alert-danger'>");
            $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;")
                .append("</button>");
            $('#success > .alert-danger')
                .append("<strong>Email address already in use. </strong>");
            $('#success > .alert-danger')
                .append('</div>');
        }

        // Reset all form fields
        $('#contactForm').trigger("reset");
    },
    error: function() {
        // Display error message
        $('#success').html("<div class='alert alert-danger'>");
        $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;")
            .append("</button>");
        $('#success > .alert-danger').append("<strong>Sorry " + firstname + ", it seems that my mail server is not responding. Please try again later!");
        $('#success > .alert-danger').append('</div>');
        // Reset all form field values
        $('#contactForm').trigger("reset");
    },
})

Answer №1

When the server responds with a status of 200, the success callback is fired.

If you want to handle errors in the error function, you need to send a header of 500 (server error) from the backend.

You can also include a boolean flag in the success response:

{status: 1, message: "email does not exist"}

or

{status: 0, message: "email already taken"}

JavaScript:

$.ajax({
    url: "././mail/msend_form.php",
    type: "POST",
    data: {
        fname: firstName,
        gender: gender,
        email: email
    },
    dataType: "json",
    cache: false,
    success: function(response) {
        if(response.status == 1){
            // OK
        }else{
            // Fail
        }
    }
});

PHP

// Check for existing email

$email_exists = false; // or true

$json = ['status' => 0, 'message' => 'Email exists']; // Default

if(!$email_exists){
    $json['status'] = 1;
    $json['message'] = 'OK';
}

// Delete all outputs before the header (echo, print_r...)

header("Content-Type: application/json");
echo json_encode($json);
die;

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

A guide on efficiently storing and retrieving a webpage containing two angular2 components using local storage

I've been attempting to store and retrieve a page containing two angular2 components from local storage using the following code, but the component CSS is not being applied. Here is the code I'm using to save: localStorage.setItem('pageCon ...

What steps can I take to prevent my menu items from overlapping in the mobile navigation menu?

I am currently working on creating a mobile menu, but I'm facing an issue where the menu items overlap when hovered over. Instead, I want the menu items to move downwards when hovered upon to prevent the text from overlapping. Below is the HTML code ...

Can anyone recommend a high-quality jQuery lightbox replica?

Key Features Needed: Customizable with CSS Capable of handling forms, not just images Extensively documented Please provide any recommendations and suggestions for suitable options. Thank you in advance ...

Using a template in CodeIgniter allows for easy organization and

Currently, I am in the process of building a website by utilizing a templating method. I have created multiple files and now I am looking to run a query that would be accessible across all templates. Is this achievable? To provide you with some context, le ...

Set up local npm packages for easy access by different projects

Can someone explain to me how npm works compared to Maven (I have a background in Java) when it comes to package management? I've developed a generic component using Angular 4 that will be used across multiple projects. I've published it to our n ...

Automating testing with JavaScript and Selenium WebDriver

Can testing be automated using the combination of JavaScript and Selenium? I am not familiar with Java, Python, or C#, but I do have expertise in Front-End development. Has anyone attempted this before? Is it challenging to implement? Are there any recom ...

What is the process for refreshing HTML elements that have been generated using information from a CSV document?

My elements are dynamically generated from a live CSV file that updates every 1 minute. I'm aiming to manage these elements in the following way: Remove items no longer present in the CSV file Add new items that have appeared in the CSV file Maintai ...

A step-by-step guide on setting up a confirmation pop-up message using Gravity Forms

Has anyone attempted to implement a pop-up confirmation message in Gravity Forms? I am also looking to prevent the form from disappearing after submission. By the way, I have selected text as the confirmation type in my Gravity Form settings because I do ...

Iterating through a static array using a foreach loop

Is it possible to use a foreach loop to replace the locations in this array? I've tried putting the foreach inside the array, but it causes the code to break. I'm thinking that maybe I need to create a foreach variable and then use that for the l ...

Once more, objects cannot be used as a child element in React

I understand that there are similar questions about this topic, but I am struggling to approach it in a different way. I really need an array of objects to be inside a map. I have created an array to map it, but I need to find different information to disp ...

Problem concerning the window object in a React functional component

Hey there, I am currently facing a situation where I need to access the window object within my React component in order to retrieve some information from the query string. Here is an excerpt of what my component code looks like: export function MyCompone ...

Executing Phinx migrations in a SQLite in-memory database using PHPUnit

Having trouble with Phinx migrations not working on sqlite memory in version 0.9.2. My app has a simple table (product). However, after running the migration, the product table does not exist: use Symfony\Component\Yaml\Yaml; use Phinx&bsol ...

What is the difference in efficiency when accessing a Class property versus invoking a Class method in PHP?

Although it may not make a significant difference, I am curious to know if there is any overhead in calling class methods compared to calling class properties. Take a look at the example below involving $router->controller and $router->action. I'm not ...

I need to retrieve a specific image ID from a foreach loop in CodeIgniter using AJAX

I am looking to extract a specific image record from a foreach loop and then pass this value to another page. <?php foreach($portfolio_image as $image):?> <h3><?=$image->portfolio_image_title?></h3> <p><?=$ima ...

A single Modal, Ajax, and data that is continuously refreshed

I'm currently facing a challenge in my project as I try to implement Ajax functionality. Although I'm relatively new to using it, I believe I have a basic understanding of its workings. My website involves collecting form data, posting it to a d ...

Is it advisable to implement the modular pattern when creating a Node.js module?

These days, it's quite common to utilize the modular pattern when coding in JavaScript for web development. However, I've noticed that nodejs modules distributed on npm often do not follow this approach. Is there a specific reason why nodejs diff ...

"NaN is being caused by the presence of quotation marks within the split property

Apologies if this question has already been addressed, but I'm struggling to find the answer. I've recently delved into coding as a new hobby and found it quite enjoyable. After using a website that claimed I had learned all there is to know abou ...

Troubleshooting issue with file upload feature in Angular for Internet Explorer 9

I have implemented a file upload method using the following code: <input type="file" name="upload-file" ng-model= "excelFile" accept=".xlsx" onchange="angular.element(this).scope().fileChanged(this);" ...

Triggering an event in Angular 2 after ngFor loop completes

I am currently attempting to utilize a jQuery plugin that replaces the default scrollbar within dynamic elements in Angular 2. These elements are generated using an ngFor loop, making it impossible to directly attach jQuery events to them. At some point, ...

What is the importance of having Express in the frontend?

As someone who is relatively new to the world of JavaScript and web applications, I recently came across an Express web application project that contained a public directory, client directory, and server directory. This has raised some questions for me. I ...