11/12/2017 - 10:41 AM

Simple AJAX js data sending; form-urlencoded format


This is the traditional form submit format for the web, a data format called application/x-www-form-urlencoded, if you want to get dorky about it. When you submit a normal HTML form, the data is sent like this. In PHP, that data is parsed into the familiar $_POST variable. We don't realize that it originally looked like this, because PHP gives us that nice associative array.

I wanted to show this because we are not going to send data in this format. Remember, our endpoint expects pure JSON. So, use Json.stringify()

        handleNewFormSubmit: function(e) {
            var $form = $(e.currentTarget);
            var formData = {};
            $.each($form.serializeArray(), function(key, fieldData) {
                formData[fieldData.name] = fieldData.value
                url: $form.data('url'),
                method: 'POST',
                data: JSON.stringify(formData),
                success: function(data) {
                    // todo
                error: function(jqXHR) {
                    // todo
                    console.log('error :(');