pythonjqueryajaxhttp-postget-request

What is the difference between manually extracting data and using a GET vs POST request with jquery AJAX?


I've developed a website using Python Flask, which includes a form with two dropdowns and a slider. I'm looking to retrieve the selected values from these form elements and send them to the python flask route by using jQuery AJAX. I am uncertain on whether I should use a GET or POST request or use Javascript to manually extract the data.

The code below shows how I am manually extracting data from the form. the console correctly logs the values whenever a change occurs, but I am unsure on if this is the correct method of obtaining the values as I have seen others use GET and POST requests to obtain form values.

$(document).ready(function() {
    $('form.ajax').on('submit', function(event) {
        event.preventDefault(); // Prevent the default form submission

        // Get the value of the slider
        var groupSize = $('#groupsize-input').val();

        // Get the value of the subjects dropdown
        var subject = $('select[name="subjects"]').val();

        // Get the value of the difficulty dropdown
        var difficulty = $('select[name="difficulty"]').val();

        
        // Log the values to the console for debugging
        console.log('Group Size:', groupSize);
        console.log('Subject:', subject);
        console.log('Difficulty:', difficulty);

        
    });

Solution

  • When user changes values in widgets (e.g dropdown, slider, input) then browser doesn't send it automatically to server but it waits until user presses button.

    So using GET/POST to get these values is totally useless. And it would need extra code on server to get values from browser and keep it (in memory, on disk, in database), and later it would need another code to get it (from memory, from disk, from database) and send it back to browser.

    GET/POST can be useful only if you have widget which content depends on value selected in other widget.

    For example you may have two dropdown. In first you select country and second dropdown should show only cities in this country - and then JavaScript could use GET/POST to send country to server and it should have function which sends back cities for this country.

    Other example: user write text in input and JavaScript send this to server and it sends back all results matching this word - and JavaScript display it as list, and user can select value from list. This is how can work autocomplementation (e.g. when you search something in Google)