One place for hosting & domains

      How To Build Forms in React


      The author selected Creative Commons to receive a donation as part of the Write for DOnations program.

      Introduction

      Forms are a crucial component of React web applications. They allow users to directly input and submit data in components ranging from a login screen to a checkout page. Since most React applications are single page applications (SPAs), or web applications that load a single page through which new data is displayed dynamically, you won’t submit the information directly from the form to a server. Instead, you’ll capture the form information on the client-side and send or display it using additional JavaScript code.

      React forms present a unique challenge because you can either allow the browser to handle most of the form elements and collect data through React change events, or you can use React to fully control the element by setting and updating the input value directly. The first approach is called an uncontrolled component because React is not setting the value. The second approach is called a controlled component because React is actively updating the input.

      In this tutorial, you’ll build forms using React and handle form submissions with an example app that submits requests to buy apples. You’ll also learn the advantages and disadvantages of controlled and uncontrolled components. Finally, you’ll dynamically set form properties to enable and disable fields depending on the form state. By the end of this tutorial, you’ll be able to make a variety of forms using text inputs, checkboxes, select lists, and more.

      Prerequisites

      Step 1 — Creating a Basic Form with JSX

      In this step, you’ll create an empty form with a single element and a submit button using JSX. You’ll handle the form submit event and pass the data to another service. By the end of this step, you’ll have a basic form that will submit data to an asynchronous function.

      To begin, open App.js:

      • nano src/components/App/App.js

      You are going to build a form for purchasing apples. Create a <div> with a className of <wrapper>. Then add an <h1> tag with the text “How About Them Apples” and an empty form element by adding the following highlighted code:

      form-tutorial/src/components/App/App.js

      
      import React from 'react';
      import './App.css';
      
      function App() {
        return (
          <div className="wrapper">
            <h1>How About Them Apples</h1>
            <form>
            </form>
          </div>
        )
      }
      
      export default App;
      

      Next, inside the <form> tag, add a <fieldset> element with an <input> element surrounded by a <label> tag. By wrapping the <input> element with a <label> tag, you are aiding screen readers by associating the label with the input. This will increase the accessibility of your application.

      Finally, add a submit <button> at the bottom of the form:

      form-tutorial/src/components/App/App.js

      
      import React from 'react';
      import './App.css';
      
      function App() {
        return(
          <div className="wrapper">
            <h1>How About Them Apples</h1>
            <form>
            <fieldset>
               <label>
                 <p>Name</p>
                 <input name="name" />
               </label>
             </fieldset>
             <button type="submit">Submit</button>
            </form>
          </div>
        )
      }
      
      export default App;
      

      Save and close the file. Then open App.css to set the styling:

      • nano src/components/App/App.css

      Add padding to the .wrapper and margin to the fieldset to give some space between elements:

      form-tutorial/src/components/App/App.css

      .wrapper {
          padding: 5px 20px;
      }
      
      .wrapper fieldset {
          margin: 20px 0;
      }
      

      Save and close the file. When you do, the browser will reload and you’ll see a basic form.

      Basic form with a field for

      If you click on the Submit button, the page will reload. Since you are building a single page application, you will prevent this standard behavior for a button with a type="submit". Instead, you’ll handle the submit event inside the component.

      Open App.js:

      • nano src/components/App/App.js

      To handle the event, you’ll add an event handler to the <form> element, not the <button>. Create a function called handleSubmit that will take the SyntheticEvent as an argument. TheSyntheticEvent is a wrapper around the standard Event object and contains the same interface. Call .preventDefault to stop the page from submitting the form then trigger an alert to show that the form was submitted:

      form-tutorial/src/components/App/App.js

      
      import React from 'react';
      import './App.css';
      
      function App() {
        const handleSubmit = event => {
         event.preventDefault();
         alert('You have submitted the form.')
       }
      
        return(
          <div className="wrapper">
            <h1>How About Them Apples</h1>
            <form onSubmit={handleSubmit}>
              <fieldset>
                <label>
                  <p>Name</p>
                  <input name="name" />
                </label>
              </fieldset>
              <button type="submit">Submit</button>
            </form>
          </div>
        )
      }
      
      export default App;
      

      Save the file. When you do the browser will reload. If you click the submit button, the alert will pop up, but the window will not reload.

      Form submit alert

      In many React applications, you’ll send the data to an external service, like a Web API. When the service resolves, you’ll often show a success message, redirect the user, or do both.

      To simulate an API, add a setTimeout function in the handleSubmit function. This will create an asynchronous operation that waits a certain amount of time before completing, which behaves similarly to a request for external data. Then use the useState Hook to create a submitting variable and a setSubmitting function. Call setSubmitting(true) when the data is submitted and call setSubmitting(false) when the timeout is resolved:

      form-tutorial/src/components/App/App.js

      
      import React, { useState } from 'react';
      import './App.css';
      
      function App() {
        const [submitting, setSubmitting] = useState(false);
        const handleSubmit = event => {
          event.preventDefault();
         setSubmitting(true);
      
         setTimeout(() => {
           setSubmitting(false);
         }, 3000)
       }
      
        return(
          <div className="wrapper">
            <h1>How About Them Apples</h1>
            {submitting &&
             <div>Submtting Form...</div>
           }
            <form onSubmit={handleSubmit}>
              <fieldset>
                <label>
                  <p>Name</p>
                  <input name="name" />
                </label>
              </fieldset>
              <button type="submit">Submit</button>
            </form>
          </div>
        )
      }
      
      export default App;
      

      In addition, you will alert the user that their form is submitting by displaying a short message in the HTML that will display when submitting is true.

      Save the file. When you do, the browser will reload and you’ll receive the message on submit:

      Form submitting shows message for 3 seconds

      Now you have a basic form that handles the submit event inside the React component. You’ve connected it to your JSX using the onSubmit event handler and you are using Hooks to conditionally display an alert while the handleSubmit event is running.

      In the next step, you’ll add more user inputs and save the data to state as the user fills out the form.

      Step 2 — Collecting Form Data Using Uncontrolled Components

      In this step, you’ll collect form data using uncontrolled components. An uncontrolled component is a component that does not have a value set by React. Instead of setting the data on the component, you’ll connect to the onChange event to collect the user input. As you build the components, you’ll learn how React handles different input types and how to create a reusable function to collect form data into a single object.

      By the end of this step, you’ll be able to build a form using different form elements, including dropdowns and checkboxes. You’ll also be able to collect, submit, and display form data.

      Note: In most cases, you’ll use controlled components for your React application. But it’s a good idea to start with uncontrolled components so that you can avoid subtle bugs or accidental loops that you might introduce when incorrectly setting a value.

      Currently, you have a form that can submit information, but there is nothing to submit. The form has a single <input> element, but you are not collecting or storing the data anywhere in the component. In order to be able to store and process the data when the user submits a form, you’ll need to create a way to manage state. You’ll then need to connect to each input using an event handler.

      Inside App.js, use the useReducer Hook to create a formData object and a setFormData function. For the reducer function, pull the name and value from the event.target object and update the state by spreading the current state while adding the name and value at the end. This will create a state object that preserves the current state while overwriting specific values as they change:

      form-tutorial/src/components/App/App.js

      import React, { useReducer, useState } from 'react';
      import './App.css';
      
      const formReducer = (state, event) => {
       return {
         ...state,
         [event.target.name]: event.target.value
       }
      }
      
      function App() {
        const [formData, setFormData] = useReducer(formReducer, {});
        const [submitting, setSubmitting] = useState(false);
      
        const handleSubmit = event => {
          event.preventDefault();
          setSubmitting(true);
      
          setTimeout(() => {
            setSubmitting(false);
          }, 3000)
        }
      
        return(
          <div className="wrapper">
            <h1>How About Them Apples</h1>
            {submitting &&
              <div>Submtting Form...</div>
            }
            <form onSubmit={handleSubmit}>
              <fieldset>
                <label>
                  <p>Name</p>
                  <input name="name" onChange={setFormData}/>
                </label>
              </fieldset>
              <button type="submit">Submit</button>
            </form>
          </div>
        )
      }
      
      export default App;
      

      After making the reducer, add setFormData to the onChange event handler on the input. Save the file. When you do, the browser will reload. However, if you try and type in the input, you’ll get an error:

      Error with SyntheticEvent

      The problem is that the SyntheticEvent is reused and cannot be passed to an asynchronous function. In other words, you can’t pass the event directly. To fix this, you’ll need to pull out the data you need before calling the reducer function.

      Update the reducer function to take an object with a property of name and value. Then create a function called handleChange that pulls the data from the event.target and passes the object to setFormData. Finally, update the onChange event handler to use the new function:

      form-tutorial/src/components/App/App.js

      import React, { useReducer, useState } from 'react';
      import './App.css';
      
      const formReducer = (state, event) => {<^>
       return {
         ...state,
         [event.name]: event.value
       }
      }
      
      function App() {
        const [formData, setFormData] = useReducer(formReducer, {});
        const [submitting, setSubmitting] = useState(false);
      
        const handleSubmit = event => {
          event.preventDefault();
          setSubmitting(true);
      
          setTimeout(() => {
            setSubmitting(false);
          }, 3000);
        }
      
        const handleChange = event => {
          setFormData({
            name: event.target.name,
            value: event.target.value,
          });
        }
      
        return(
          <div className="wrapper">
            <h1>How About Them Apples</h1>
            {submitting &&
              <div>Submtting Form...</div>
            }
            <form onSubmit={handleSubmit}>
              <fieldset>
                <label>
                  <p>Name</p>
                  <input name="name" onChange={handleChange}/>
                </label>
              </fieldset>
              <button type="submit">Submit</button>
            </form>
          </div>
        )
      }
      
      export default App;
      

      Save the file. When you do the page will refresh and you’ll be able to enter data.

      Now that you are collecting the form state, update the user display message to show the data in an unordered list (<ul>) element.

      Convert the data to an array using Object.entries, then map over the data converting each member of the array to an <li> element with the name and the value. Be sure to use the name as the key prop for the element:

      form-tutorial/src/components/App/App.js

      ...
        return(
          <div className="wrapper">
            <h1>How About Them Apples</h1>
            {submitting &&
             <div>
               You are submitting the following:
               <ul>
                 {Object.entries(formData).map(([name, value]) => (
                   <li key={name}><strong>{name}</strong>:{value.toString()}</li>
                 ))}
               </ul>
             </div>
            }
            <form onSubmit={handleSubmit}>
              <fieldset>
                <label>
                  <p>Name</p>
                  <input name="name" onChange={handleChange}/>
                </label>
              </fieldset>
              <button type="submit">Submit</button>
            </form>
          </div>
        )
      }
      
      export default App;
      

      Save the file. When you do the page will reload and you’ll be able to enter and submit data:

      Fill out the form and submit

      Now that you have a basic form, you can add more elements. Create another <fieldset> element and add in a <select> element with different apple varieties for each <option>, an <input> with a type="number" and a step="1" to get a count that increments by 1, and an <input> with a type="checkbox" for a gift wrapping option.

      For each element, add the handleChange function to the onChange event handler:

      form-tutorial/src/components/App/App.js

      ...
        return(
          <div className="wrapper">
            <h1>How About Them Apples</h1>
            {submitting &&
              <div>
                You are submitting the following:
                <ul>
                  {Object.entries(formData).map(([name, value]) => (
                    <li key={name}><strong>{name}</strong>: {value.toString()}</li>
                  ))}
                </ul>
              </div>
            }
            <form onSubmit={handleSubmit}>
              <fieldset>
                <label>
                  <p>Name</p>
                  <input name="name" onChange={handleChange}/>
                </label>
              </fieldset>
              <fieldset>
               <label>
                 <p>Apples</p>
                 <select name="apple" onChange={handleChange}>
                     <option value="">--Please choose an option--</option>
                     <option value="fuji">Fuji</option>
                     <option value="jonathan">Jonathan</option>
                     <option value="honey-crisp">Honey Crisp</option>
                 </select>
               </label>
               <label>
                 <p>Count</p>
                 <input type="number" name="count" onChange={handleChange} step="1"/>
               </label>
               <label>
                 <p>Gift Wrap</p>
                 <input type="checkbox" name="gift-wrap" onChange={handleChange} />
               </label>
             </fieldset>
              <button type="submit">Submit</button>
            </form>
          </div>
        )
      }
      
      export default App;
      

      Save the file. When you do, the page will reload and you’ll have a variety of input types for your form:

      Form with all input types

      There is one special case here to take into consideration. The value for the gift wrapping checkbox will always be "on", regardless of whether the item is checked or not. Instead of using the event’s value, you’ll need to use the checked property.

      Update the handleChange function to see if the event.target.type is checkbox. If it is, pass the event.target.checked property as the value instead of event.target.value:

      form-tutorial/src/components/App/App.js

      import React, { useReducer, useState } from 'react';
      import './App.css';
      
      ...
      
      function App() {
        const [formData, setFormData] = useReducer(formReducer, {});
        const [submitting, setSubmitting] = useState(false);
      
        const handleSubmit = event => {
          event.preventDefault();
          setSubmitting(true);
      
          setTimeout(() => {
            setSubmitting(false);
          }, 3000);
        }
      
        const handleChange = event => {
         const isCheckbox = event.target.type === 'checkbox';
         setFormData({
           name: event.target.name,
           value: isCheckbox ? event.target.checked : event.target.value,
         })
       }
      ...
      

      In this code, you use the ? ternary operator to make the conditional statement.

      Save the file. After the browser refreshes, fill out the form and click submit. You’ll find that the alert matches the data in the form:

      Form elements submitting correct data

      In this step, you learned how to create uncontrolled form components. You saved the form data to a state using the useReducer Hook and reused that data in different components. You also added different types of form components and adjusted your function to save the correct data depending on the element type.

      In the next step, you’ll convert the components to controlled components by dynamically setting the component value.

      Step 3 — Updating Form Data Using Controlled Components

      In this step, you’ll dynamically set and update data using controlled components. You’ll add a value prop to each component to set or update the form data. You’ll also reset the form data on submit.

      By the end of this step, you’ll be able to dynamically control form data using React state and props.

      With uncontrolled components, you don’t have to worry about synchronizing data. Your application will always hold on to the most recent changes. But there are many situations where you’ll need to both read from and write to an input component. To do this, you’ll need the component’s value to be dynamic.

      In the previous step, you submitted a form. But after the form submission was successful, the form still contained the old stale data. To erase the data from each input, you’ll need to change the components from uncontrolled components to controlled components.

      A controlled component is similar to an uncontrolled component, but React updates the value prop. The downside is that if you are not careful and do not properly update the value prop the component will appear broken and won’t seem to update.

      In this form, you are already storing the data, so to convert the components, you’ll update the value prop with data from the formData state:

      form-tutorial/src/components/App/App.js

      ...
        return(
          <div className="wrapper">
            <h1>How About Them Apples</h1>
            {submitting &&
              <div>
                You are submitting the following:
                <ul>
                  {Object.entries(formData).map(([name, value]) => (
                    <li key={name}><strong>{name}</strong>: {value.toString()}</li>
                  ))}
                </ul>
              </div>
            }
            <form onSubmit={handleSubmit}>
              <fieldset>
                <label>
                  <p>Name</p>
                  <input name="name" onChange={handleChange} value={formData.name}/>
                </label>
              </fieldset>
              <fieldset>
                <label>
                  <p>Apples</p>
                  <select name="apple" onChange={handleChange} value={formData.apple}>
                      <option value="">--Please choose an option--</option>
                      <option value="fuji">Fuji</option>
                      <option value="jonathan">Jonathan</option>
                      <option value="honey-crisp">Honey Crisp</option>
                  </select>
                </label>
                <label>
                  <p>Count</p>
                  <input type="number" name="count" onChange={handleChange} step="1" value={formData.count}/>
                </label>
                <label>
                  <p>Gift Wrap</p>
                  <input type="checkbox" name="gift-wrap" onChange={handleChange} checked={formData['gift-wrap']}/>
                </label>
              </fieldset>
              <button type="submit">Submit</button>
            </form>
          </div>
        )
      }
      
      export default App;
      

      As before, the checkbox is a little different. Instead of setting a value, you’ll need to set the checked attribute. If the attribute is truthy, the browser will show the box as checked.

      If you want to pre-fill the form, add some default data to the formData state. Set a default value for the count by giving formState a default value of { count: 100 }:

      form-tutorial/src/components/App/App.js

      ...
      
      function App() {
        const [formData, setFormData] = useReducer(formReducer, {
         count: 100,
       });
        const [submitting, setSubmitting] = useState(false);
      ...
      

      Save the file. When you do, the browser will reload and you’ll see the input with the default data:

      Form with default count

      Note: The value attribute is different from the placeholder attribute, which is native on browsers. The placeholder attribute shows information but will disappear as soon as the user makes a change; it is not stored on the component. You can actively edit the value, but a placeholder is just a guide for users.

      Now that you have active components, you can clear the data on submit. To do so, add a new condition in your formReducer. If event.reset is truthy, return an object with empty values for each form element. Be sure to add a value for each input. If you return an empty object or an incomplete object, the components will not update since the value is undefined.

      After you add the new event condition in the formReducer, update your submit function to reset the state when the function resolves:

      form-tutorial/src/components/App/App.js

      import React, { useReducer, useState } from 'react';
      import './App.css';
      
      const formReducer = (state, event) => {
        if(event.reset) {
         return {
           apple: '',
           count: 0,
           name: '',
           'gift-wrap': false,
         }
       }
        return {
          ...state,
          [event.name]: event.value
        }
      }
      
      function App() {
        const [formData, setFormData] = useReducer(formReducer, {
          count: 100
        });
        const [submitting, setSubmitting] = useState(false);
      
        const handleSubmit = event => {
          event.preventDefault();
          setSubmitting(true);
      
          setTimeout(() => {
            setSubmitting(false);
            setFormData({
             reset: true
           })
          }, 3000);
        }
      
      ...
      

      Save the file. When you do, the browser will reload and the form will clear on submit.

      Save the form and then clear the data

      In this step, you converted your uncontrolled components to controlled components by setting the value or the checked attributes dynamically. You also learned how to refill data by setting a default state and how to clear the data by updating the form reducer to return default values.

      In this next step, you’ll set form component properties dynamically and disable a form while it is submitting.

      Step 4 — Dynamically Updating Form Properties

      In this step, you’ll dynamically update form element properties. You’ll set properties based on previous choices and disable your form during submit to prevent accidental multiple submissions.

      Currently, each component is static. They do not change as the form changes. In most applications, forms are dynamic. Fields will change based on the previous data. They’ll validate and show errors. They may disappear or expand as you fill in other components.

      Like most React components, you can dynamically set properties and attributes on components and they will re-render as the data changes.

      Try setting an input to be disabled until a condition is met by another input. Update the gift wrapping checkbox to be disabled unless the user selects the fuji option.

      Inside App.js, add the disabled attribute to the checkbox. Make the property truthy if the formData.apple is fuji:

      form-tutorial/src/components/App/App.js

      ...
              <fieldset>
                <label>
                  <p>Apples</p>
                  <select name="apple" onChange={handleChange} value={formData.apple}>
                      <option value="">--Please choose an option--</option>
                      <option value="fuji">Fuji</option>
                      <option value="jonathan">Jonathan</option>
                      <option value="honey-crisp">Honey Crisp</option>
                  </select>
                </label>
                <label>
                  <p>Count</p>
                  <input type="number" name="count" onChange={handleChange} step="1" value={formData.count}/>
                </label>
                <label>
                  <p>Gift Wrap</p>
                  <input
                   checked={formData['gift-wrap']}
                   disabled={formData.apple !== 'fuji'}
                   name="gift-wrap"
                   onChange={handleChange}
                   type="checkbox"
                  />
                </label>
              </fieldset>
              <button type="submit">Submit</button>
            </form>
          </div>
        )
      }
      
      export default App;
      

      Save the file. When you do, the browser will reload and the checkbox will be disabled by default:

      Gift wrap is disabled

      If you select the apple type of Fuji, the element will be enabled:

      Gift wrap is enabled

      In addition to changing properties on individual components, you can modify entire groups of components by updating the fieldset component.

      As an example, you can disable the form while the form is actively submitting. This will prevent double submissions and prevent the user from changing fields before the handleSubmit function fully resolves.

      Add disabled={submitting} to each <fieldset> element and the <button> element:

      form-tutorial/src/components/App/App.js

      ...
            <form onSubmit={handleSubmit}>
              <fieldset disabled={submitting}>
                <label>
                  <p>Name</p>
                  <input name="name" onChange={handleChange} value={formData.name}/>
                </label>
              </fieldset>
              <fieldset disabled={submitting}>
                <label>
                  <p>Apples</p>
                  <select name="apple" onChange={handleChange} value={formData.apple}>
                      <option value="">--Please choose an option--</option>
                      <option value="fuji">Fuji</option>
                      <option value="jonathan">Jonathan</option>
                      <option value="honey-crisp">Honey Crisp</option>
                  </select>
                </label>
                <label>
                  <p>Count</p>
                  <input type="number" name="count" onChange={handleChange} step="1" value={formData.count}/>
                </label>
                <label>
                  <p>Gift Wrap</p>
                  <input
                    checked={formData['gift-wrap']}
                    disabled={formData.apple !== 'fuji'}
                    name="gift-wrap"
                    onChange={handleChange}
                    type="checkbox"
                  />
                </label>
              </fieldset>
              <button type="submit" disabled={submitting}>Submit</button>
            </form>
          </div>
        )
      }
      
      export default App;
      

      Save the file, and the browser will refresh. When you submit the form, the fields will be disabled until the submitting function resolves:

      Disable form elements when submitting

      You can update any attribute on an input component. This is helpful if you need to change the maxvalue for a number input or if you need to add a dynamic pattern attribute for validation.

      In this step, you dynamically set attributes on form components. You added a property to dynamically enable or disable a component based on the input from another component and you disabled entire sections using the <fieldset> component.

      Conclusion

      Forms are key to rich web applications. In React, you have different options for connecting and controlling forms and elements. Like other components, you can dynamically update properties including the value input elements. Uncontrolled components are best for simplicity, but might not fit situations when a component needs to be cleared or pre-populated with data. Controlled components give you more opportunities to update the data, but can add another level of abstraction that may cause unintentional bugs or re-renders.

      Regardless of your approach, React gives you the ability to dynamically update and adapt your forms to the needs of your application and your users.

      If you would like to read more React tutorials, check out our React Topic page, or return to the How To Code in React.js series page.



      Source link

      Submitting AJAX Forms with JQuery


      Introduction

      While vanilla JavaScript continues to catch up to JQuery in terms of capability and cross-browser consistency, handling form submissions in JavaScript can still be a minefield of gotchas and inconsistency.

      What we’ll build: There are a few basic requirements usually asked from forms. We want:

      • Process a form without a page refresh using AJAX
      • Client side validation
      • Server side validation (validation from the PHP side)
      • Showing a processing icon while our form is… processing
      • Showing errors if there are any
      • Showing success if the form is submitted correctly

      processing ajax forms with jquery demo

      Getting Started

      Let’s get started processing our form. We will need three different things for this:

      • A way to process the form (we’ll be using PHP, but you can use anything you want)
      • A view to show the form
      • The JavaScript and AJAX (jQuery flavored) to make it all work

      Processing the Form with PHP

      This will be the easiest part. Since we’re using PHP, we can just create a simple script to process our form. Let’s call it process.php (clever I know), and make the code for that.

      We will provide support to send back JSON data (which is what our JavaScript code will be processing after our PHP or any server side code sends back information). We will also send back errors and error messages in the data that we send back.

      We will just check to see if a variable exists or not. There are many more validations that you can do like checking to see if there is a valid email, but we’ll just focus on the required status.

      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);
      

      Notice in PHP, to pass data back to our JavaScript call, you want to echo json_encode(). Using a return like you normally would in a function wouldn’t provide JSON data back.

      Now that we have the form processing worked out, we’ll create our form.

      Rendering the form in HTML

      We will be using Bootstrap to build out our views. It’s just easier since all their classes are already pre-built and we can create our view quickly.

      We will place all of the code we need for our view and inject errors into the view later.

      index.html

      <!doctype html>
      <html>
      <head>
          <title>Look I'm AJAXing!</title>
          <link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css"> <!-- load bootstrap via CDN -->
          <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> <!-- load jquery via CDN -->
          <script src="form.js"></script> <!-- load our javascript file -->
      </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="rudd@avengers.com">
                  <!-- 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>
      </body>
      </html>
      

      Here’s what it looks like:
      processing-ajax-forms-with-jquery

      Handling Form Submit Logic in JavaScript

      To submit a form via AJAX, we will need to do certain things in our JavaScript file.

      • Capture the form submit button so that the default action doesn’t take place
      • Get all of the data from our form using jQuery
      • Submit using AJAX (we’ll go through a few ways)
      • Show errors if there are any

      We’ll start our JavaScript file by getting data from our form and sending a POST request to our already create PHP script (process.php).

      form.js

      $(document).ready(function() {
      
          // process the form
          $('form').submit(function(event) {
      
              // 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
              })
                  // 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
                  });
      
              // stop the form from submitting the normal way and refreshing the page
              event.preventDefault();
          });
      
      });
      

      Now when we press submit on our form, our JavaScript code will get all the input values that we need and send a POST request to process.php.

      Promise Callbacks: We will be using the .done callback to handle a successful AJAX request. This used to be called .success but that has since been deprecated in jQuery 1.8+.

      Another Way to Get Form Data serialize

      You could also use serialize instead of pulling the form information individually.

      Seeing JSON Data Come Back

      Our PHP script will process the inputs that our AJAX call sent and spit back the $data[] array that we created. You can see this in your browser’s console after you submit your form.

      console showing data returned from php

      You can access any of these attributes as part of your data object. Just use the . to get to a specific item.

      Handling Errors

      In our PHP script, we are only checking to make sure that all the fields are required. If a field is not present, we send an error back. We’ll want to inform our user of this error.

      We’re going to add errors under each of the inputs. The Bootstrap classes help us do this so let’s go ahead and handle those errors and inject them into our page if they happen.

      form.js

      ...
      // 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
      })
          // 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').html('<div class="alert alert-success">' + data.message + '</div>');
              }
      
          });
      ...
      

      Now if there are any errors that come back from our server, we can show them like so:

      form showing validation errors

      And if our AJAX form was successful:

      form showing success messsage

      Clearing Errors

      Every time we submit the form, our errors from our previous submission are still there. We just need to clear them by removing them as soon as the form is submitted again.

      form.js

      ...
      // process the form
      $('form').submit(function(event) {
      
          $('.form-group').removeClass('has-error'); // remove the error class
          $('.help-block').remove(); // remove the error text
      ...
      

      Showing Server Errors

      If there is an error in our server-side code, we won’t get any feedback from our AJAX call. We’ll just be left there scratching our heads. There’s a simple solution to that: we’ll add an errorattribute to our AJAX call.

      form.js

      ...
      
      // 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
      })
          // using the done promise callback
          .done(function(data) {
              ...
          })
      
          // using the fail promise callback
          .fail(function(data) {
            //Server failed to respond - Show an error message
            $('form').html('<div class="alert alert-danger">Could not reach server, please try again later.</div>');
          });
      ...
      

      Now if the server is broken or down for any reason, a user who attempts to submit a form will get:

      form showing server fail messsage

      Cleaner JS with $.post Method

      If you don’t want to write all that AJAX code out every time, there’s an easier way! You can use the jQuery POST Shorthand method. This let’s you simplify your code and still get the same results.

      The above code would be the equivalent of:

      $.post('process.php', function(formData) {
      
          // place success code here
      
      })
          .fail(function(data) {
              // place error code here
          });
      

      Much cleaner!

      Conclusion

      Submitting forms using JQuery and AJAX is a fairly easy process and hopefully this helped you on your journey in creating forms and processing them without a page refresh.

      This article only covers the server-side validation part of forms. You’ll want to look at doing client-side validation as well and doing more than just required validation. There are plenty of resources out there to push forward and as always, ask questions in the comments if you need any help!



      Source link

      How to Get Visitors to Fill Out Lead Forms on Your Website


      Running a business means you’re probably always on the lookout for new customers. This can be tough online, where there’s so much content vying for your audience’s attention. Even if you’ve built a beautiful website, it can be difficult to get visitors to stick around and interact with it.

      That’s where a lead capture form comes in!

      These marketing gems can be used in many ways throughout your website. In particular, they’re especially useful for gathering valuable data about your leads and increasing conversion rates.

      In this article, we’ll look deeper into what lead generation forms are. We’ll also discuss why you should include them on your site, and how to get site visitors to click on their Submit buttons. Let’s get started!

      An Introduction to Lead Generation Forms and Why They’re Beneficial

      Whether you know it or not, you’ve probably filled out dozens of lead generation forms. Some common examples include user registrations, contact forms, opt-in forms, and email subscription sign-ups. They’re the entry points to your site’s “lead capture funnel,” which means they gather the information you need to convert visitors into customers.

      According to Kissmetrics, 96% of people who go to a website don’t go with the intention to buy something right away. Building high-quality lead generation forms that follow best practices can do a lot to help boost your conversion rate and turn your visitors (think of them as “qualified leads”) into customers.

      Although they may seem like small details, lead generation forms are key to any site’s success. For example, getting visitors to register on your website can make them feel as though they’re part of an online community. This helps build brand loyalty that may steer them towards your site when they’re ready to purchase a product or service you offer.

      Similarly, contact forms that enable users to make inquiries about offers can streamline the conversion process. By putting you directly in touch with leads, these forms allow you to easily respond and seal the deal.

      Finally, email marketing is still a highly effective strategy. Building your email list and collecting information to craft targeted content is a vital part of a successful marketing plan. High-quality lead generation forms can help with that.

      How to Get Visitors to Fill Out Lead Forms on Your Website (5 Tips)

      Designing a great sign-up form is only half the battle. Getting people to actually fill them out without abandoning them can be a bigger challenge! Let’s take a look at five tips for getting site visitors to follow through.

      1. Offer Incentives to Attract Visitors to Your Forms

      Most people enjoy receiving discounts or free products. Many are willing to “pay” for them by giving you their email addresses or signing up for an account. This makes coupons and other special offers smart ways to incentivize your lead generation forms.

      Take ThredUp, for example. This online thrift store offers a pop-up for a 50% off coupon in exchange for your email address.

      ThredUp’s home page featuring a pop-up.

      Some other potential incentives include free trials, e-books, online courses, or sample products. At CrazyEgg, users receive a free heatmap for submitting their website address. All are workable options as incentives you can offer site visitors in return for filling out your capture form.

      2. Review the Length of Your Forms to Prevent Abandonment

      Generally speaking, website users like to complete tasks quickly. Keeping your forms short and simple will likely yield the highest conversion rates. That said, you also want to gather as much information as possible about your potential customers.

      Elements such as progress bars can help extend users’ patience when it comes to filling out multi-step forms. Breaking up questions into sections and tabs is also a way to make forms feel shorter.

      BrokerNotes’ interactive question with options.

      For instance, BrokerNotes has a 46% conversion rate through their “un-form,” which provides an interactive experience for users guided by helpful breadcrumbs. It gathers a lot of information, while also providing users with incentives along the way.

      3. Leverage Social Media to Promote Lead Generation

      Incorporating social media might seem like a no-brainer when it comes to marketing. However, it can also boost access to your lead generation forms via tools such as Facebook Lead Ads.

      An example of Facebook’s Lead Ads product.

      Additionally, enabling users to create accounts using their favorite social platforms can increase your registration count. In fact, 77% of users think social login is a great idea and wish all sites offered it.

      By shortening the registration and sign-in processes, social logins can help combat “account fatigue” and increase the likelihood of visitors becoming members. Additionally, this strategy makes it easier for you to gather information on your users, which you can then use to improve your marketing strategy.

      4. Test Your Forms to Find and Fix Errors

      Once you dive in and design a lead capture form that suits your goals and branding needs, you’ll want to make sure it actually works. Regularly testing your forms can help avoid a high bounce rate, incorrect information, and user frustration.

      A contact form with an error message.

      High-quality forms often follow basic web design best practices, but there are a few exceptions and considerations. You’ll want to review your content and structures for elements such as title consistency, error message language, button content, and more.

      You might also consider instituting A/B testing. This process involves creating two versions of a form and trying them out to see which one works better. Just remember to be careful when setting this system up for your forms, as there are some technical aspects to consider that could cause the test to fail.

      5. Eliminate Distractions and Friction to Decrease User Frustration

      When users try to fill out your lead capture form, they shouldn’t feel like they’re working. The best way to avoid this is to reduce “friction” such as error messages, data that fails to load or send, and unclear instructions.

      To do that, keep vital elements such as form field labels, layout, placement on the page, and even Call to Action (CTA) color choice in mind. Doing this will help point users in the right direction to complete your form.

      A form field asking for your website URL.

      Similarly, distractions can also cause a dip in your conversion rate. Distractions include anything that prevents your visitors from engaging in the action you most want them to take. The closer a user gets to completing the desired action, the fewer elements you should have on the page to draw their attention away from the ultimate goal.

      Tools for Adding Lead Generation Forms to Your Website

      If you’re using WordPress, you’re one step closer to taking advantage of lead generation forms. There are several plugins available to help you incorporate them into your site; one of the most popular is OptinMonster.

      The OptinMonster lead generation plugin.

      OptinMonster enables you to create popups to re-engage visitors who are leaving your site and encourage them to fill out your lead generation form. The tool also makes creating different form layouts easy. Pairing this and other tools with a fast, reliable WordPress host can improve your site’s user experience and increase your chance of capturing leads.

      Do More with DreamPress

      Our automatic updates and strong security defenses take server management off your hands so you can focus on conversion rate optimization.

      Lead Nurturing to Increase Conversions

      Building a client base can be challenging. However, knowing that your lead generation forms are consistently converting at a high rate can provide you with some comfort as you grow your business.

      Are you ready to add lead generation forms to your landing pages? Combining these key takeaways with lead capture plugins and our fully-managed WordPress hosting plans can help you start working towards a higher conversion rate!



      Source link