The Simplest Way to Use Ajax

if you have never used ajax before or if you simply hate it because of the added complexity cuz you want to show some fancy notification to the user instead of the page refresh,

Then Today Is Your Lucky Day 😉💪

Am going to show you the most simplest/easiest way to use ajax and even if you want to change to the basic form submission, you still can do by just removing a couple of wrapper elements.

1- lets build a very basic form

<form action="url" method="POST">
    <!-- Name-->
    <label for="name">Name</label>
    <input name="name" type="text">

    <!-- Email -->
    <label for="email">E-Mail Address</label>
    <input name="email" type="email">

    <!-- other form inputs -->
    // ...

    <!-- submit -->
    <button type="submit">Submit</button>
</form>

2- for this demo we are going to use Vuejs & Axios, ofcourse you are free to use anything else ex.jQuery but i prefer Vue for simplicity.

  • create component file Form.vue
  • register it Vue.component(“MyForm”, require(“./Form.vue”))
  • add the logic to the component
<template></template>

<script>
  export default {
    data() {
        return {}
    },
    methods: {
      FormSubmit(event) {
        axios({
          method: event.target.method,
          url: event.target.action,
          data: new FormData(event.target) // the secret is right here "new FormData()"

        }).then(function (response) {
          console.log(response);
        })
        .catch(function (error) {
          console.log(error);
        });
      }
    }
  }
</script>

3- we are almost done but for Vue to start handling the form, we need to add a couple of extra markups to our form, check the highlighted lines below

<my-form inline-template>
  <form action="url" method="POST" @submit="FormSubmit($event)">
      <!-- Email -->
      <label for="email" class="label">E-Mail Address</label>
      <input name="email" type="email">

      <!-- other form inputs -->
      // ...

      <!-- submit -->
      <button type="submit">Submit</button>
  </form>
</my-form>

DONE 🎉, How easy was that ?!!.

  • if you liked the idea, i’ve made a repo for exactly that + away to handle the backend “Laravel” validation errors aswell
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s