Luke
Luke

Reputation: 623

Load Modal on form submission

I am trying to load a "thank you" modal when submitting my form.

I have 3 files, magic.js (which does the JQ magic), index.html and process.php.

Below is the code for each of the 3 files, and I can't for the life of me get it to work.

When the form is submitted it just loads the process.php page and displays success = true

if I remove the action="process.php" from the form tag I just get a Method Not Allowed error.

index.html:

<html>
<head>
    <title>Look I'm AJAXing!</title>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> <!-- load jquery via CDN -->
    <script src="magic.js"></script> <!-- load our javascript file -->
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css"> <!-- load bootstrap via CDN -->
</head>
<body>
<div class="col-sm-6 col-sm-offset-3">

    <h1>Processing an AJAX Form</h1>

    <!-- OUR FORM -->
    <form action="process.php" method="POST">

        <!-- NAME -->
        <div id="name-group" class="form-group">
            <label for="name">Name</label>
            <input type="text" class="form-control" name="name" placeholder="Henry Pym">
            <!-- errors will go here -->
        </div>

        <!-- EMAIL -->
        <div id="email-group" class="form-group">
            <label for="email">Email</label>
            <input type="text" class="form-control" name="email" placeholder="[email protected]">
            <!-- errors will go here -->
        </div>

        <!-- SUPERHERO ALIAS -->
        <div id="superhero-group" class="form-group">
            <label for="superheroAlias">Superhero Alias</label>
            <input type="text" class="form-control" name="superheroAlias" placeholder="Ant Man">
            <!-- errors will go here -->
        </div>

        <button type="submit" class="btn btn-success">Submit <span class="fa fa-arrow-right"></span></button>

    </form>

</div>
 <!-- Modal -->
  <div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog">

      <!-- Modal content-->
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h4 style="color:red;"><span class="glyphicon glyphicon-lock"></span> Login</h4>
        </div>
        <div class="modal-body tyModal">
          <p> Thank you for your submission!</p>
        </div>
        <div class="modal-footer">
          <button type="submit" class="btn btn-default btn-default pull-left" data-dismiss="modal"><span class="glyphicon glyphicon-remove"></span> Cancel</button>
          <p>Not a member? <a href="#">Sign Up</a></p>
          <p>Forgot <a href="#">Password?</a></p>
        </div>
      </div>
    </div>
  </div> 
</body>
</html>

magic.js:

$(document).ready(function() {

    // process the form
    $('form').submit(function(event) {

        $('.form-group').removeClass('has-error'); // remove the error class
        $('.help-block').remove(); // remove the error text

        // get the form data
        // there are many ways to get this data using jQuery (you can use the class or id also)
        var formData = {
            'name'              : $('input[name=name]').val(),
            'email'             : $('input[name=email]').val(),
            'superheroAlias'     : $('input[name=superheroAlias]').val()
        };

        // process the form
        $.ajax({
            type        : 'POST', // define the type of HTTP verb we want to use (POST for our form)
            url         : 'process.php', // the url where we want to POST
            data        : formData, // our data object
            dataType    : 'json', // what type of data do we expect back from the server
            encode      : true
            success: function (msg) {
                $("#thanks").html(msg)
                $("tyModal").modal('hide');
            },
            error: function () {
                alert("failure");
            }
        })
            // using the done promise callback
            .done(function(data) {

                // log data to the console so we can see
                console.log(data); 

                // here we will handle errors and validation messages
                if ( ! data.success) {

                    // handle errors for name ---------------
                    if (data.errors.name) {
                        $('#name-group').addClass('has-error'); // add the error class to show red input
                        $('#name-group').append('<div class="help-block">' + data.errors.name + '</div>'); // add the actual error message under our input
                    }

                    // handle errors for email ---------------
                    if (data.errors.email) {
                        $('#email-group').addClass('has-error'); // add the error class to show red input
                        $('#email-group').append('<div class="help-block">' + data.errors.email + '</div>'); // add the actual error message under our input
                    }

                    // handle errors for superhero alias ---------------
                    if (data.errors.superheroAlias) {
                        $('#superhero-group').addClass('has-error'); // add the error class to show red input
                        $('#superhero-group').append('<div class="help-block">' + data.errors.superheroAlias + '</div>'); // add the actual error message under our input
                    }

                } else {

                    // ALL GOOD! just show the success message!
                    $('form').append('<div class="alert alert-success">' + data.message + '</div>');

                    // usually after form submission, you'll want to redirect
                    // window.location = '/thank-you'; // redirect a user to another page

                }
            })

            // using the fail promise callback
            .fail(function(data) {

                // show any errors
                // best to remove for production
                console.log(data);
            });

        // stop the form from submitting the normal way and refreshing the page
        event.preventDefault();
    });

});

process.php:

<?php

$errors         = array();      // array to hold validation errors
$data           = array();      // array to pass back data

// validate the variables ======================================================
    // if any of these variables don't exist, add an error to our $errors array

    if (empty($_POST['name']))
        $errors['name'] = 'Name is required.';

    if (empty($_POST['email']))
        $errors['email'] = 'Email is required.';

    if (empty($_POST['superheroAlias']))
        $errors['superheroAlias'] = 'Superhero alias is required.';

// return a response ===========================================================

    // if there are any errors in our errors array, return a success boolean of false
    if ( ! empty($errors)) {

        // if there are items in our errors array, return those errors
        $data['success'] = false;
        $data['errors']  = $errors;
    } else {

        // if there are no errors process our form, then return a message

        // DO ALL YOUR FORM PROCESSING HERE
        // THIS CAN BE WHATEVER YOU WANT TO DO (LOGIN, SAVE, UPDATE, WHATEVER)

        // show a message of success and provide a true success variable
        $data['success'] = true;
        $data['message'] = 'Success!';
    }

    // return all our data to an AJAX call
    echo json_encode($data);

Upvotes: 1

Views: 2328

Answers (2)

ahervin
ahervin

Reputation: 461

Add the line

event.preventDefault();

Just after your submit event.

This should stop the usual form process of posting to that action and let the AJAX do it instead. See http://www.w3schools.com/jquery/event_preventdefault.asp

There's other aspects of your code that could be cleaned up tto be more flexible for added form fields in the future.

var formData = { 'name' : $('input[name=name]').val(), 'email' : $('input[name=email]').val(), 'superheroAlias' : $('input[name=superheroAlias]').val() };

You could do something like this

var formData = {};
$.each($('form').find('input'),function(i,v){
       formData[$(v).attr('name')] = $(v).val();
});

or look at .serialize(); - > https://api.jquery.com/serialize/

I'm also not sure whether your dialog will register even with my given code as the code within the success function doesn't match up with the HTML this issue has been identified by @Darren Willows

Upvotes: -1

Darren Willows
Darren Willows

Reputation: 2131

You never actually create the modal on forum submit.

You only hide on success.

$("tyModal").modal('hide');

You also have not created the modal on the page either, as myModal is the only one that exists. Not tyModal.

Another issue is that #thanks does not exists, so you are technically populating the data with nothing.

success: function(data) {
    $("#thanks").html(data);
    jQuery("#myModal").modal('show');
}

This is the code that I use.

HTML

<!-- data-backdrop="static" -->
<div class="modal fade" id="myAjaxModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-backdrop="static" data-keyboard="false">
    <div class="modal-dialog">
        <div class="modal-content" id="myAjaxModalContent">
        </div><!-- end modal-content -->
    </div>
    <!-- end modal-dialog -->
</div>
<!-- end modal -->

JS

function showModal() {
   $( "#myAjaxModal .modal-content" ).html('test');
    $('#myAjaxModal').modal('show');
}

Upvotes: 2

Related Questions