44 |
45 |
46 |
--------------------------------------------------------------------------------
/magic.js:
--------------------------------------------------------------------------------
1 | // magic.js
2 | $(document).ready(function() {
3 |
4 | // process the form
5 | $('form').submit(function(event) {
6 |
7 | $('.form-group').removeClass('has-error'); // remove the error class
8 | $('.help-block').remove(); // remove the error text
9 |
10 | // get the form data
11 | // there are many ways to get this data using jQuery (you can use the class or id also)
12 | var formData = {
13 | 'name' : $('input[name=name]').val(),
14 | 'email' : $('input[name=email]').val(),
15 | 'superheroAlias' : $('input[name=superheroAlias]').val()
16 | };
17 |
18 | // process the form
19 | $.ajax({
20 | type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
21 | url : 'process.php', // the url where we want to POST
22 | data : formData, // our data object
23 | dataType : 'json', // what type of data do we expect back from the server
24 | encode : true
25 | })
26 | // using the done promise callback
27 | .done(function(data) {
28 |
29 | // log data to the console so we can see
30 | console.log(data);
31 |
32 | // here we will handle errors and validation messages
33 | if ( ! data.success) {
34 |
35 | // handle errors for name ---------------
36 | if (data.errors.name) {
37 | $('#name-group').addClass('has-error'); // add the error class to show red input
38 | $('#name-group').append('
' + data.errors.name + '
'); // add the actual error message under our input
39 | }
40 |
41 | // handle errors for email ---------------
42 | if (data.errors.email) {
43 | $('#email-group').addClass('has-error'); // add the error class to show red input
44 | $('#email-group').append('
' + data.errors.email + '
'); // add the actual error message under our input
45 | }
46 |
47 | // handle errors for superhero alias ---------------
48 | if (data.errors.superheroAlias) {
49 | $('#superhero-group').addClass('has-error'); // add the error class to show red input
50 | $('#superhero-group').append('
' + data.errors.superheroAlias + '
'); // add the actual error message under our input
51 | }
52 |
53 | } else {
54 |
55 | // ALL GOOD! just show the success message!
56 | $('form').append('
' + data.message + '
');
57 |
58 | // usually after form submission, you'll want to redirect
59 | // window.location = '/thank-you'; // redirect a user to another page
60 |
61 | }
62 | })
63 |
64 | // using the fail promise callback
65 | .fail(function(data) {
66 |
67 | // show any errors
68 | // best to remove for production
69 | console.log(data);
70 | });
71 |
72 | // stop the form from submitting the normal way and refreshing the page
73 | event.preventDefault();
74 | });
75 |
76 | });
77 |
--------------------------------------------------------------------------------
/process.php:
--------------------------------------------------------------------------------
1 |