ikucheriavenko
11/12/2017 - 10:41 AM

Simple AJAX js data sending; form-urlencoded format

https://knpuniversity.com/screencast/javascript/post-proper-api-endpoint

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) {
            e.preventDefault();
            var $form = $(e.currentTarget);
            var formData = {};
            $.each($form.serializeArray(), function(key, fieldData) {
                formData[fieldData.name] = fieldData.value
            });
            $.ajax({
                url: $form.data('url'),
                method: 'POST',
                data: JSON.stringify(formData),
                success: function(data) {
                    // todo
                    console.log('success!');
                },
                error: function(jqXHR) {
                    // todo
                    console.log('error :(');
                }
            });
        }