LearnHow to Create an AJAX Contact Form for a Website [Guide]
Conversions don’t always equate to purchases or transactions, they can also appear in the form of newsletter sign-ups and contact forms. Contact forms are one of the most common features on a website. Standard contact forms work just fine, but you can make them nicer by using AJAX to submit the form data in the background.
In this blog post, you’ll learn how to create a website contact form that submits the form data using AJAX. We’ll be using jQuery to help simplify the JavaScript code and a simple PHP mailer script to handle sending the form data via email.
Step 1: Building the HTML Form Using jQuery
We’ll start by setting up the HTML form that will collect data from the user. Give your element the ID ajax-contact , set the method attribute to post , and the action attribute to mailer.php .
Here you’ve set up a simple form that has fields to collect the user’s name, email address, and message. Notice that each of the form fields has a required attribute. In browsers that support HTML5 form validation, this will prevent the form from being submitted until all the fields have been completed.
Next you need to create a element that will be used to display success and error messages to the user. Create this element above the in your HTML markup and give it the ID form-messages .
Now you need to download the code resources and copy the style.css file into your project directory. You’ll also need to add a element that tells the browser to load the stylesheet.
Finally you need to create two elements that reference the jquery-2.1.0.min.js and app.js files. Add these just before the closing
tag.
It’s important that you load the jquery-2.1.0.min.js file first as the code within app.js requires jQuery.
That’s all the HTML you’re going to need in this post. Next up, let’s take a look at the JavaScript.
Step 2: Submitting the Form Using AJAX
Create a new file in your project directory called app.js . This is going to contain all of the code responsible for submitting the form data using AJAX.
Copy the following code into the app.js file.
Here you’ve created two new variables, form and formMessages , that reference the corresponding elements in your HTML markup.
Next you need to create an event listener that will intercept submit events on the form. You can do this using the jQuery submit method.
// Set up an event listener for the contact form. $(form).submit(function(event) < // Stop the browser from submitting the form. event.preventDefault(); // TODO >);
Here you’ve passed a function to the submit method that will be executed when the user submits the contact form. You’ve also told the browser not to submit the form as it would normally by calling the preventDefault method on the event.
Next you need to serialize the form data. This will convert the data the user has entered into the form into a key/value string that can be sent with the AJAX request. Use the jQuery serialize method to serialize the form data and then store the result in a variable called formData .
// Serialize the form data. var formData = $(form).serialize();
Now you’re ready to write the code that’s responsible for sending the form data to the server and processing the response. Copy the following code into your app.js file.
// Submit the form using AJAX. $.ajax(< type: 'POST', url: $(form).attr('action'), data: formData >)
Here you’re using jQuery’s ajax method to create a new AJAX request. You’ve passed an object to the ajax method that contains a number of properties used to configure the request. The type property specifies the HTTP method that will be used for the request, in our case POST . The url property is the location of the script that the form data will be sent to. You’ve populated this property by fetching the action attribute from the form. Finally, the data property has been populated using the formData variable that you created earlier.
Next you need to handle a successful response from the server. Copy the following code directly after the closing bracket of the ajax call. Note that I’ve deliberatly left out the semi-colon.
This done method will be called if the request completes successfully. Here you first make sure that the formMessages element has the success class and then set the text content of this element using the data returned by the mailer script. To finish, you clear out the values from each of the form fields.
The last bit of JavaScript you need to write handles what should happen if an error occurs. Copy the following into app.js .
This fail method is called if the mailer script returns an error. Here you first make sure that the formMessages element has the error class. You then check to see if the AJAX request returned any responseText . If it did, you use this text to set the content for the formMessages element; otherwise use a generic error message.
That completes the HTML and JavaScript code that’s needed to build an AJAX contact form. In the next section you’re going to learn about the mailer script that is responsible for processing the form data and sending out an email.
Step 3: Creating the PHP Mailer Script to Send Emails
Now it’s time to write the PHP mailer script that will process the form data. This simple script is responsible for checking that the form data is valid and then sending out the email. If an error occurs, the mailer script will respond with an appropriate status code so that the JavaScript within the fail callback you wrote earlier will be executed.
Create a new file called mailer.php and copy into it the following code.
// Set the recipient email address. // FIXME: Update this to your desired email address. $recipient = "hello@example.com"; // Set the email subject. $subject = "New contact from $name"; // Build the email content. $email_content = "Name: $name\n"; $email_content .= "Email: $email\n\n"; $email_content .= "Message:\n$message\n"; // Build the email headers. $email_headers = "From: $name "; // Send the email. if (mail($recipient, $subject, $email_content, $email_headers)) < // Set a 200 (okay) response code. http_response_code(200); echo "Thank You! Your message has been sent."; >else < // Set a 500 (internal server error) response code. http_response_code(500); echo "Oops! Something went wrong and we couldn't send your message."; >> else < // Not a POST request, set a 403 (forbidden) response code. http_response_code(403); echo "There was a problem with your submission, please try again."; >?>
Update: Thanks to Aaron Traas for his modifications that make this mailer script more secure.
This script starts by checking that the request was sent using the POST method. If it wasn’t, the script will return a 403 (forbidden) HTTP status code and an error message.
Once you’ve established that the correct HTTP method has been used you then extract the form data into three variables $name , $email , and $message . You also use the PHP trim method here to cut out any unwanted whitespace.
Next you will check to make sure that none of these variables is blank. If one or more is blank, set the response code to 400 (bad request) and return an error message to the browser.
Now that you’ve determined the data is clean, you prepare the email, first by creating a variable with the email recipient. You then create variables for the subject, email content, and finally the email headers.
Note: Setting the email headers is optional. Doing so will make the email appear as though it was sent by the person that filled out the form. However, it’s important to note that manipulating the headers like this can also cause the email to be marked as spam by some email clients.
Next you will attempt to send the email using the PHP mail function. If this is successful, you will return a success message. If it’s not, you need to set the response code to 500 (internal server error) and return an error message.
Note: The standard PHP mail function will do just fine for the purposes of this blog post, but there are more robust ways of sending email using PHP. If you’re interested in learning more, I recommend that you check out the Build a Simple PHP Application project on Treehouse.
Load up your HTML file in a web browser and try out the form. You’ll need to be using a web server with support for PHP and the mail function for everything to work correctly.
Final Thoughts
In this blog post, you’ve learned how to create a contact form that uses AJAX to communicate with a mailer script on the server. You’ve used jQuery to help simplify the JavaScript code, but you could have achieved the same result with standard JavaScript.
Using AJAX within your websites allows you to improve the user experience in a number of different areas, not just contact forms. Next time you’re building a website, ask yourself how AJAX could help to create a smoother experience for your users.
Useful Links
If you’re looking to take your JavaScript or HTML5/CSS programming skills to another level, check out our Techdegrees in Full Stack JavaScript and Front End Web Design. Our faculty of tech professionals guide learners like you from mastering the fundamentals of coding to polishing the skills of a job-ready software developer. Try one of them out with a free seven-day trial today.
Learning with Treehouse for only 30 minutes a day can teach you the skills needed to land the job that you’ve been dreaming about.
Как отправить HTML-форму без перезагрузки страницы
При разработке сайтов бывает, что у нас возникает необходимость отправить данные html-формы без перезагрузки страницы в фоновом режиме (с использованием AJAX). В данной статье мы рассмотрим этот вопрос и покажем на примере как реализовать нашу задачу с помощью языков jquery и php. Мы получим скрипт, при выполнении которого, сервер отправляет, а клиент получает данные в формате JSON.
Технология Ajax стала популярной и часто применяется при создании сайтов в WEB 2.0. Многие уже успешные или начинающие web-сайты стремятся создать удобство для своих пользователей, что немаловажно в условиях конкуренции и огромного количества интернет-ресурсов. Кроме того, Ajax-технология помогает увеличить быстродействие вашего сайта. Это происходит благодаря тому, что пользователь не перегружает страницу целиком, когда необходимо обновить только некоторые элементы/части вашего сайта.
Как выполнить отправку данных формы при помощи Ajax
Здесь мы создадим демо-проект, который будет включать в себя 3 файла:
index.php — это главная страница, на которой размещена сама форма
ajax.js — это файл javascript, в котором содержится алгоритм ajax для обработки формы
action_ajax_form.php — это серверная часть, которая отвечает за обработку полученных от формы данных и возвращает клиенту ответ в формате JSON
Создайте первый файл под названием index.php с таким содержимым:
Мы подключим библиотеку jQuery и создали базовую HTML-разметку, а также подключили файл ajax.js, далее нам нужно будет создать этот файл. Обратите внимание, что метод отправки формы у нас POST, задан и action=»». Также, после формы мы добавили div c Именно в этот div мы будем выводить результат обработки формы.
Теперь создадим второй файл — ajax.js
$( document ).ready(function() < $("#btn").click( function()< sendAjaxForm('result_form', 'ajax_form', 'action_ajax_form.php'); return false; >); >); function sendAjaxForm(result_form, ajax_form, url) < $.ajax(< url: url, //url страницы (action_ajax_form.php) type: "POST", //метод отправки dataType: "html", //формат данных data: $("#"+ajax_form).serialize(), // Сеарилизуем объект success: function(response) < //Данные отправлены успешно result = $.parseJSON(response); $('#result_form').html('Имя: '+result.name+' Телефон: '+result.phonenumber); >, error: function(response) < // Данные не отправлены $('#result_form').html('Ошибка. Данные не отправлены.'); >>); >
В файле ajax.js есть два метода: $(«#btn»).click и sendAjaxForm. Первый метод — это слушатель событий кнопки. То есть, когда мы нажимаем на кнопку «Отправить», слушатель срабатывает и вызывает метод sendAjaxForm.
В метод sendAjaxForm(result_form, ajax_form, url) передаются поля: result_form — это div в который будут рендерится данные, ajax_form — это id формы отправки сообщения и url — это местоположение файла action_ajax_form.php который отвечает за серверную часть (обработка формы).
action_ajax_form.php — это обработчик формы на стороне сервера. Этот файл отвечает за backend часть нашего мини-приложения. Для примера, мы делаем проверку: Если существуют переменные в POST запросе name и phonenumber, тогда мы формируем массив $result для JSON ответа от сервера. Затем, массив $result мы переводим в JSON объект, чтобы клиент ajax.js смог корректно получить данные в формате JSON.