DEV Community

loading...
Cover image for How do I add an item to a database without reloading the page?

How do I add an item to a database without reloading the page?

leviathanprogramming profile image 𝐋𝐄𝑽𝐈𝑨𝐓𝐇𝐀𝐍 Programming ・1 min read

I'm working with Flask and I am making an entry to a hackathon (so hurry and help me if you can!).

Whenever I add an item to a database with SQLalchemy on form submission, the page reloads.

An example of what I want is when you click the Like button a post. Usually, when you click it, a Like is submitted and the page doesn't reload.

Can someone please help me with this?
Thank you for reading.
Happy Coding.

Discussion (8)

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
leviathanprogramming profile image
Collapse
eruizdechavez profile image
Erick Ruiz de Chavez

It is probably too late for this, but I'll share it anyway. You do not need jQuery to make an AJAX request, just use fetch which is supported already in all major browsers.

developer.mozilla.org/en-US/docs/W...

Thread Thread
leviathanprogramming profile image
𝐋𝐄𝑽𝐈𝑨𝐓𝐇𝐀𝐍 Programming Author

Yeah, I always try to use DOM. Thanks for sharing this. I almost don't use jquery at all anymore.

Collapse
jordanfinners profile image
Jordan Finneran

This is because when you submit a form, the default behaviour for a HTML form is to submit to a URL, which is the page refresh you are seeing. You can read about it more w3schools.com/html/html_forms_attr...

If you want to handle this yourself, you need to preventDefault on the submit event, which halts its default behaviour.
You can then use Javascript to get the form values and submit them via fetch, which means you also don't need any additional dependancies.
Heres my blog on how to get the values of the form dev.to/jordanfinners/how-to-easily...

And this blog will explain how to use fetch
freecodecamp.org/news/fetch-api-ch...

Collapse
hasnaindev profile image
Muhammad Hasnain

You can create an endpoint for it on your server and send an AJAX request from the front-end using JavaScript.

Collapse
leviathanprogramming profile image
𝐋𝐄𝑽𝐈𝑨𝐓𝐇𝐀𝐍 Programming Author

I don't know how to use AJAX just yet. Can you create or send me a link to a demo?

Collapse
hasnaindev profile image
Forem Open with the Forem app