DEV Community

[Comment from a deleted post]
Collapse
 
pazvanti profile image
pazvanti

First, you will need to create a new endpoint that can handle the request. It can receive a JSON string that it can parse to transform it into your internal representation. That internal representation you can save as you normally do. I am a Java dev, so using the JPA API it can be easily done.

Now, on the HTML page, you have to stop the form from being submitted. I know how to do this using jQuery.
Let's assume your form has the id "myAwesomeForm":

$("#myAwesomeForm").submit(function( event ) {
    submitForm($(this), function(data){ alert("Done");});
    event.preventDefault();
});
Enter fullscreen mode Exit fullscreen mode

The magic happens in the submitForm() method. After that we just prevent the actual form submission in the normal way.

Now, submitting the form data. How you transform it into JSON is up to you, but here are libraries out there that do this based on the input field names. I used such a library here.

function submitForm(form, onComplete) {
    var jsonData = JSON.stringify(form.serializeJSON());
    var action = form.attr("action");
    var method = form.attr("method");
    sendRequestWithData(action, jsonData, method, onComplete);
}

function sendRequestWithData(url, jsonData, method, onComplete) {
    $.ajax({
        url: url,
        dataType: 'json',
        type: method,
        contentType: 'application/json',
        data: jsonData,
        processData: false,
        success: function( data, textStatus, jQxhr ){
            if (data.redirect) {
                // data.redirect contains the string URL to redirect to
                window.location.href = data.redirect;
            }
            if (onComplete === undefined) {
                location.reload();
            } else {
                onComplete(jQxhr.responseText)
            }
        },
        error: function( jqXhr, textStatus, errorThrown ) {
            parseAndShowMessage(jqXhr.responseText);
        }
    });
}
Enter fullscreen mode Exit fullscreen mode

P.S. This is just a short example, and it may contain some errors, but you get the general idea.

Collapse
 
ironcladdev profile image
Conner Ow

Thank you, I'll try to use this.