[Fixed]-Django + AJAX query model without refreshing the page

1đź‘Ť

âś…

Without JS (Need refresh)
You need to specify 2 attribute values

action : an url for where data should send and,

method : a method to send the data,

<form id="icao_search" action="/path/to/api" method="get">
 <input type="text" id="icao">
<input type="submit" value="SUBMIT">
</form>

With JS

action : an url for where data should send and,

method : a method to send the data,

id_to_display_result : a div id to inject fetched result html

document.onreadystatechange = function() {
    if (document.readyState === "complete") {
        document.querySelector("#icao_search input[type='submit']").onclick = function(e) {
            e.preventDefault();
            var xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {
                    document.getElementById("id_to_display_result").innerHTML =
                        this.responseText;
                }
            };
            xhr.open("GET", "/path/to/api", true);
            xhr.send();
        }
    }
}
👤Sajan

0đź‘Ť

If you don’t want the page to reload, you’ll need to use JavaScript to send an XMLHttpRequest. For details on that, see this answer: Send POST data using XMLHttpRequest

You’ll want to replace the “alert” in that example with something that updates the page with flight info from the response.

👤Malcolm White

Leave a comment