Title: jQuery form submit event is not caught
Tags: javascript;php;jquery;mysql;ajax
Question: Note: I have already posted this at the WordPress Stack Exchange but received no help, so I am posting here in hopes of getting an answer.
I'm building a little form to let users update their contact information outside of the vanilla WordPress user management systems. I plan to use a simple CRUD setup and throw in some sanitation. I've got the initial insert/create function built using the $wpdb functions and the form does write to the database correctly. However, my JavaScript isn't getting called when I submit my form. The JavaScript file doesn't capture the submit event and the form just POSTs the data straight to the PHP processor file. I'm scratching my head here.
Run down of the issue, play-by-play:
Form submits, but user is redirected to a page with the JSON encoded data in an array.
The JavaScript file that contains my error processing and Ajax calls is never touched.
The JavaScript file does not capture the submit event.
The form is still written to the DB, I assume because the POST method is being called on the PHP file in the form action.
NOTE: I am including the .js file using wp_enqueue_script in my functions file, but will most likely change this to be included only when the page with this form is loaded, to cut down on load times. I don't think loading the JavaScript file this way should change anything.
PHP Processing:
<?php
# DB CRUD commands for updating the table for alumni contact info
/* wordpress db globals, require wp-load to bring in useful functions */
$parse_uri = explode( 'wp-content', $_SERVER['SCRIPT_FILENAME'] );
require_once( $parse_uri[0] . 'wp-load.php' );
global $wpdb;
$errors         = array();      // array to hold validation errors
$data           = array();      // array to pass back data
/*Ensure no fields are empty, and if they are, return $errors array encoded in JSON */
if (empty($_POST['first_name']))
$errors['first_name'] = 'First name is required.';
if (empty($_POST['last_name']))
$errors['last_name'] = 'Last name is required.';
if (empty($_POST['email']))
$errors['email'] = 'Email is required.';
if (empty($_POST['phone']))
$errors['phone'] = 'A phone number is required.';
if (empty($_POST['address']))
$errors['address'] = 'A mailing address is required.';
if (empty($_POST['city']))
$errors['city'] = 'Please enter the city for your mailing address.';
if (empty($_POST['zip']))
$errors['zip'] = 'Your zip code is required.';
if (empty($_POST['state']))
$errors['state'] = 'Please select your state.';
// 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
/* Set the proper table name to a variable */
$table_name = "wp_alumni";
/* Use insert function to write the data to the table
* Called on form submit when the user adds their contact info
* to the Alumni database using the on-page form.
* button name = submit is used to check 'if isset'
* and then perform the update function
*/
if (isset($_POST['create'])) {
$wpdb-&gt;insert(
$table_name, array(
'first_name'    =&gt; $_POST['first_name'],
'last_name' =&gt; $_POST['last_name'],
'address'   =&gt; $_POST['address'],
'address2' =&gt; $_POST['address2'],
'city'  =&gt; $_POST['city'],
'state' =&gt; $_POST['state'],
'zip'   =&gt; $_POST['zip'],
'phone' =&gt; $_POST['phone'],
'email' =&gt; $_POST['email'],
'time' =&gt; current_time('mysql', 1)
)
);
}
// 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);
The Form/HTML:
<form method="POST" action="<?php echo plugins_url( 'alumni/alumni_update.php' ); ?&gt;" name="alumni-update" id="alumni-update"&gt;
<div id="alumni-form-column"&gt;
<li&gt;
<span class="alumni-span"&gt;First Name</span&gt;<br /&gt;
<input id="first_name" type="text" name="first_name" class="alumni-input" /&gt;
</li&gt;
<li&gt;
<span class="alumni-span"&gt; Last Name</span&gt;<br /&gt;
<input id="last_name" type="text" name="last_name" class="alumni-input" /&gt;
</li&gt;
<li&gt;
<span class="alumni-span"&gt;Street Address</span&gt;<br /&gt;
<input id="address" type="text" name="address" class="alumni-input" /&gt;
</li&gt;
<li&gt;
<span class="alumni-span"&gt;Apt, Unit, Ste #, etc</span&gt;<br /&gt;
<input id="address2" type="text" name="address2" class="alumni-address-2" cols="1" /&gt;
</li&gt;
</div&gt;
<div id="alumni-form-column"&gt;
<li&gt;
<span class="alumni-span"&gt;City</span&gt;<br /&gt;
<input id="city" type="text" name="city" class="alumni-input" /&gt;
</li&gt;
<li&gt;
<span class="alumni-span"&gt;State</span&gt;<br /&gt;
<select id="state" type="text" name="state" class="alumni-input"&gt;
<option value="AL"&gt;Alabama</option&gt;
<option value="AK"&gt;Alaska</option&gt;
<option value="AZ"&gt;Arizona</option&gt;
<option value="AR"&gt;Arkansas</option&gt;
<option value="CA"&gt;California</option&gt;
<option value="CO"&gt;Colorado</option&gt;
<option value="CT"&gt;Connecticut</option&gt;
<option value="DE"&gt;Delaware</option&gt;
<option value="DC"&gt;District Of Columbia</option&gt;
<option value="FL"&gt;Florida</option&gt;
<option value="GA"&gt;Georgia</option&gt;
<option value="HI"&gt;Hawaii</option&gt;
<option value="ID"&gt;Idaho</option&gt;
<option value="IL"&gt;Illinois</option&gt;
<option value="IN"&gt;Indiana</option&gt;
<option value="IA"&gt;Iowa</option&gt;
<option value="KS"&gt;Kansas</option&gt;
<option value="KY"&gt;Kentucky</option&gt;
<option value="LA"&gt;Louisiana</option&gt;
<option value="ME"&gt;Maine</option&gt;
<option value="MD"&gt;Maryland</option&gt;
<option value="MA"&gt;Massachusetts</option&gt;
<option value="MI"&gt;Michigan</option&gt;
<option value="MN"&gt;Minnesota</option&gt;
<option value="MS"&gt;Mississippi</option&gt;
<option value="MO"&gt;Missouri</option&gt;
<option value="MT"&gt;Montana</option&gt;
<option value="NE"&gt;Nebraska</option&gt;
<option value="NV"&gt;Nevada</option&gt;
<option value="NH"&gt;New Hampshire</option&gt;
<option value="NJ"&gt;New Jersey</option&gt;
<option value="NM"&gt;New Mexico</option&gt;
<option value="NY"&gt;New York</option&gt;
<option value="NC"&gt;North Carolina</option&gt;
<option value="ND"&gt;North Dakota</option&gt;
<option value="OH"&gt;Ohio</option&gt;
<option value="OK"&gt;Oklahoma</option&gt;
<option value="OR"&gt;Oregon</option&gt;
<option value="PA"&gt;Pennsylvania</option&gt;
<option value="RI"&gt;Rhode Island</option&gt;
<option value="SC"&gt;South Carolina</option&gt;
<option value="SD"&gt;South Dakota</option&gt;
<option value="TN"&gt;Tennessee</option&gt;
<option value="TX"&gt;Texas</option&gt;
<option value="UT"&gt;Utah</option&gt;
<option value="VT"&gt;Vermont</option&gt;
<option value="VA"&gt;Virginia</option&gt;
<option value="WA"&gt;Washington</option&gt;
<option value="WV"&gt;West Virginia</option&gt;
<option value="WI"&gt;Wisconsin</option&gt;
<option value="WY"&gt;Wyoming</option&gt;
</select&gt;
</li&gt;
<li&gt;
<span class="alumni-span"&gt;Zip</span&gt;<br /&gt;
<input id="zip" type="text" name="zip" class="alumni-input" maxlength="5" /&gt;
</li&gt;
<li&gt;
<span class="alumni-span"&gt;Phone</span&gt;<br /&gt;
<input id="phone" type="text" name="phone" class="alumni-input" maxlength="10" onfocus="if (this.value == 'Hint text..') this.value=''" value="Hint text.." onblur="if (this.value == '') this.value='Digits only: 5458881234'"/&gt;
</li&gt;
<li&gt;
<span class="alumni-span"&gt;Email</span&gt;<br /&gt;
<input id="email" type="text" name="email" class="alumni-input" /&gt;
</li&gt;
<li&gt;
<button class="alumni-button" type="submit" name="create"&gt;Submit</button&gt;
</li&gt;
</div&gt;
</form&gt;
JavaScript
// .js document to capture the Submit event from the form and send back errors asychronously
$(document).ready(function() {
// process the form
$('form').submit(function(event) {
event.preventDefault();
$('.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 = {
'email'             : $('input[name=email]').val(),
'address'              : $('input[name=address]').val(),
'phone'             : $('input[name=phone]').val(),
'city'              : $('input[name=city]').val(),
'state'             : $('input[name=state]').val(),
'first_name'              : $('input[name=first_name]').val(),
'last_name'             : $('input[name=last_name').val(),
'zip'              : $('input[name=zip]').val()
};
// process the form
$.ajax({
type        : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url         : 'http://localhost/wordpress/wp-content/plugins/alumni/alumni_update.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
})
// 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 fist name ---------------
if (data.errors.first_name) {
$('#first_name').addClass('has-error'); // add the error class to show red input
$('#first_name').append('<div class="help-block"&gt;' + data.errors.first_name + '</div&gt;'); // add the actual error message under our input
}
// handle errors for last name ---------------
if (data.errors.last_name) {
$('#last_name').addClass('has-error'); // add the error class to show red input
$('#last_name').append('<div class="help-block"&gt;' + data.errors.last_name + '</div&gt;'); // add the actual error message under our input
}
// handle errors for city---------------
if (data.errors.city) {
$('#city').addClass('has-error'); // add the error class to show red input
$('#city').append('<div class="help-block"&gt;' + data.errors.city + '</div&gt;'); // add the actual error message under our input
}
// handle errors for last name ---------------
if (data.errors.state) {
$('#state').addClass('has-error'); // add the error class to show red input
$('#state').append('<div class="help-block"&gt;' + data.errors.state + '</div&gt;'); // add the actual error message under our input
}
// handle errors for phone ---------------
if (data.errors.phone) {
$('#phone').addClass('has-error'); // add the error class to show red input
$('#phone').append('<div class="help-block"&gt;' + data.errors.phone + '</div&gt;'); // add the actual error message under our input
}
// handle errors for address ---------------
if (data.errors.address) {
$('#address').addClass('has-error'); // add the error class to show red input
$('#address').append('<div class="help-block"&gt;' + data.errors.address + '</div&gt;'); // add the actual error message under our input
}
// handle errors for zip ---------------
if (data.errors.zip) {
$('#zip').addClass('has-error'); // add the error class to show red input
$('#zip').append('<div class="help-block"&gt;' + data.errors.zip + '</div&gt;'); // add the actual error message under our input
}
// handle errors for email ---------------
if (data.errors.email) {
$('#email').addClass('has-error'); // add the error class to show red input
$('#email').append('<div class="help-block"&gt;' + data.errors.email + '</div&gt;'); // add the actual error message under our input
}
} else {
// ALL GOOD! just show the success message!
$('form').append('<div class="alert alert-success"&gt;' + data.message + '</div&gt;');
// usually after form submission, you'll want to redirect
// window.location = '/thank-you'; // redirect a user to another page
alert('success'); // for now we'll just alert the user
}
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
Comment: think you haven't set your state correctly: `$('input[name=state]').val()` - it's a `select` not an `input`, also you're not sending your address 2 field

Comment: It's OK to cross-post if you have not received an answer in a couple of days, but please edit your duplicate to link here, so that someone does not waste their time answering at the WP site once this has attracted an answer. It's worth editing into this question a link to your other one, for the same reason.

Comment: Steve - the wp_enqueue_script function will load the .JS file in the header of the page.
Let me look at the console real fast and see if it throws any exceptions. Thanks for chiming in.

Comment: @Pete got it on the head. I followed Steve 's advice and found errors using the console. I also had to remove the **if(isset('create'))** statement from the PHP processor.
Now, I need to figure out how to do all of this by using the wp_ajax class. I'm writing this as a plugin so I cannot depend on using functions.php or other core theme files. I would need to find a way to package this using wp_nonce with wp_ajax using only what I have here.

Comment: Is js file actually being included in the html? If yes check js console for errors, perhaps its a conflict with jquery dollar sign, try: `jQuery(document).ready(function($) {`


Here is another answer: You can use alternate method to fulfill your requirement of ajax call by changing for submit button to anchor or simple button
<button class="alumni-button" type="button" name="create"&gt;Submit</button&gt;
Now check for onClick event in your javascript file
$('.alumni-button').onClick(function(){
// your javascript code
// ajax call

Here is another answer: @TheDeadMedic figured out this whole ordeal over on the Wordpress exchange:
https://wordpress.stackexchange.com/a/187995/72933
Thanks for all the help.

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 2, 'CommentCount': 5, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2015:00:05/11/15', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<javascript><php><jquery><mysql><ajax>', 'Title': 'jQuery form submit event is not caught', 'ViewCount': 283, 'id': 30168898, 'user_AboutMe': None, 'user_AccountId': 4360208.0, 'user_DisplayName': 'Jordan W.', 'user_Reputation': 1.0, 'user_Views': 2.0, 'user_id': 4887281.0}}