Vuejs - Posting Data Posted on November 21, 2015

Vue Resouce

Once again we will be using Vue-Resource to handle our ajax requests. Installation is super easy, lets get started by including it into our script.

<script src="//cdnjs.cloudflare.com/ajax/libs/vue/1.0.4/vue.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/vue-resource/0.1.16/vue-resource.min.js"></script>

Now that we have everything lets take a look at the POST command with Vue-JS.

this.$http.post('url', [data], function(data, status, request){});

this syntax is exactly the same as the GET command, which is awesome :) When we use Vue-Resource to post data to our server it will send as application/json by default. What does this mean? Well for us in PHP the data will get stored in the GLOBALS variable under HTTP_RAW_POST_DATA. Not good right?

We can change the way that Vue-Resource sends our data. We will change the options to ask it to send as FORM-DATA. This means that it will send as a POST method for us. This is a one line change, lets take a look at that line.

Vue.http.options.emulateJSON = true;

That's it... yes it is that simple :) Now let's take a look at it in action. For my demo I am using a service called Mockable.io but you can test this on your own server, or even in Laravel really easily. I am going to skip how I set up my mockable post, and instead go straight to how you can test it on your server. First let's look at some good old straight php. As you may (or may not) know you have access to a special variable called $_POST. All we need to do is do a quick dump of that variable and we will see the data come back properly.

print_r($_POST);

Now this is great and all, but Vue is meant for nicer things so how can we use this data in Laravel? All we need to do is take control of the Request variable. Let's create a quick method.

    public function testMethod(Request $request)
    {
        // will output all our request and die
        dd($request->all());

        // we also have access to everything we would normally have
        if($request->has('something'))
        {
            // do something
        }
    }

Now you have all the access to the features of the request, so you can check if a variable exists in the post, do validation, etc. Amazing and simple, I think so.

If you are looking for some sample code, I have added a Pen which you can view at http://codepen.io/tutelagesystems/pen/pjBbxQ however, the test server you will need to do yourself, or use Mockable.io to put in some test post and get methods.

Share this post