This is How to Make Your WordPress Form with File Upload Submit with Ajax
As a software developer, it's important to provide a seamless user experience for your website visitors. One common task is creating a form with file upload functionality that submits via Ajax, without requiring a full page refresh. This not only improves the user experience but also reduces server load and improves overall website performance.
In this blog post, we'll walk through the step-by-step process of creating a WordPress form with file upload that submits using Ajax. We'll cover the client-side JavaScript code, the server-side PHP code, and how to handle any errors that may occur.
The HTML Form Structure
Let's start with the HTML form structure. Here's an example of a WordPress form with a text input, a file upload input, and a submit button:
<div class="ajax-error" style="color: red;"></div>
<form class="form-assignment" name="form_assignment" id="form-assignment" method="post" enctype="multipart/form-data"
data-url="<?php echo esc_url(admin_url('admin-ajax.php')) ?>" data-action="form_submit1">
<label for="customer-field-text">Name:</label>
<input type="text" name="customer-field-text" id="customer-field-text" pattern="[a-zA-Z0-9 ]+" size="40"/>
<label>File Upload</label>
<input type="file" name="customer-field-upload" id="customer-field-upload" multiple="false"/>
<label for="select">Select:</label>
<select name="carlist" id="select">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<label for="email">Email:</label>
<input type="text" name="email" id="email">
<input type="submit" value="Submit" name="submit">
</form>
The key points to note are:
- The form has the
enctype="multipart/form-data"
attribute, which is required for file uploads.
- The form has
data-url
and data-action
attributes, which will be used by the JavaScript code to submit the form via Ajax.
- The form includes a text input, a file upload input, a select dropdown, and an email input field.
The JavaScript (jQuery) Code
Now, let's look at the JavaScript (jQuery) code that handles the form submission via Ajax:
jQuery(document).ready(function ($) {
// when user submits the form
jQuery(document).on('submit', '.form-assignment', function (event) {
var error_elm = jQuery('.ajax-error');
var response_elm = jQuery('.ajax-response');
error_elm.html('');
response_elm.html('');
event.preventDefault();
var form_elm = jQuery(this);
var url = form_elm.data('url');
var action = form_elm.data('action');
var file_input_name = jQuery('#form-assignment').find('input[type=file]').attr('id');
var form_data = new FormData();
form_data.append('action', action);
jQuery.each(jQuery(':input:not([type=submit]):not([type=file])', '#form-assignment' ), function(i, fileds){
form_data.append(jQuery(fileds).attr('name'), jQuery(fileds).val());
});
jQuery.each(jQuery(':input:not([type=submit]):not([type=text]):not([type=select])', '#form-assignment' )[0].files, function(i, file){
form_data.append(file_input_name, file);
});
response_elm.html('Loading...');
jQuery.ajax({
type: 'POST',
url: url,
data: form_data,
processData: false,
contentType: false,
cache: false
}).success(function (response) {
error_elm.html('');
response_elm.html('');
if (response.status !== 'success') {
// something went wrong
if (response.message) {
error_elm.html(response.message);
return;
}
// don't know ?
}
response_elm.html(response.message);
$("#form-assignment").trigger("reset");
}).error(function (response) {
error_elm.html('');
response_elm.html('');
error_elm.html(response.statusText);
});
});
});
Here's a breakdown of what the JavaScript code is doing:
- The code listens for the
submit
event on the form with the class form-assignment
.
- When the form is submitted, it prevents the default form submission behavior and instead handles the submission via Ajax.
- It creates a
FormData
object and appends the form field values to it, including the file upload.
- It then sends the
FormData
object to the server using the jQuery.ajax()
function.
- If the server responds with a successful status, it displays the response message. If there's an error, it displays the error message.
- Finally, it resets the form after a successful submission.
The Server-side (PHP) Code
On the server-side, we need to handle the form submission and file upload. Here's an example PHP code that you can use:
// Handle the form submission
add_action('wp_ajax_form_submit1', 'handle_form_submission');
function handle_form_submission() {
$response = array('status' => 'success', 'message' => 'Form submitted successfully!');
// Validate the form data
if (empty($_POST['customer-field-text'])) {
$response['status'] = 'error';
$response['message'] = 'Name field is required.';
wp_send_json($response);
wp_die();
}
// Handle the file upload
if (isset($_FILES['customer-field-upload']) && $_FILES['customer-field-upload']['error'] == UPLOAD_ERR_OK) {
$upload_dir = wp_upload_dir();
$file_name = sanitize_file_name($_FILES['customer-field-upload']['name']);
$file_path = $upload_dir['path'] . '/' . $file_name;
if (move_uploaded_file($_FILES['customer-field-upload']['tmp_name'], $file_path)) {
// File upload successful
} else {
$response['status'] = 'error';
$response['message'] = 'Error uploading the file.';
wp_send_json($response);
wp_die();
}
}
// Process other form data (e.g., save to the database)
$name = sanitize_text_field($_POST['customer-field-text']);
$select_value = sanitize_text_field($_POST['carlist']);
$email = sanitize_email($_POST['email']);
// Save the form data to the database or perform other actions
// ...
wp_send_json($response);
wp_die();
}
This PHP code does the following:
- It hooks into the
wp_ajax_form_submit1
action, which is the same action we specified in the JavaScript code.
- It first validates the form data, ensuring that the required fields are filled out.
- It then handles the file upload, moving the uploaded file to the WordPress uploads directory.
- It processes the other form data, such as the name, select value, and email.
- Finally, it sends the response back to the JavaScript code using the
wp_send_json()
function.
By combining the client-side JavaScript code and the server-side PHP code, you can create a WordPress form with file upload functionality that submits via Ajax, providing a smooth and seamless user experience.
Flowpoint.ai can help you identify all the technical errors that are impacting conversion rates on your website and directly generate recommendations to fix them, including issues with your form submissions.
Get a Free AI Website Audit
Automatically identify UX and content issues affecting your conversion rates with Flowpoint's comprehensive AI-driven website audit.