Search code examples
ajaxdjangopython-3.xcorsdjango-cors-headers

Django POST using AJAX not working


I have a django backend where I have added corsheader and the middlewares.

I have an html page from which I am sending AJAX XMLHttpRequest POST to my localhost hosting django application but the post never goes through. It fires a GET transaction and the transaction never reaches the server.

The code for the front end HTML page is as below:-

<button type="submit" class="btn btn-success btn-lg" id="sub1" 
onClick=loadDoc() >Login </button>
<script>
                    function loadDoc() {
                        var xhttp = new XMLHttpRequest();
                        xhttp.onreadystatechange = function() {
                            if( this.readyState == 4 && this.status == 200 ) {
                                location.replace(Trial.html);
                            }
                        };
                        xhttp.open("POST", "http://localhost:XXXX/XXXX/XXXX/", true)
                        xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                        xhttp.send();
                    }
</script>

Can any one point out what is wrong? When I use form data the post works but it doesn't work when I use javascript.


Solution

  • The reason for that happening is CORS.

    Modern browsers don't support cross origin requests. So, I had to download and install Django CORS header module. Update the settings file appropriately to allow requests from other origin to come through.

    Also, the AJAX/jQuery post request was changed to:

     $( "#loginForm" ).submit(function( event ) {
         // Stop form from submitting normally
         event.preventDefault();
    
         var jqxhr = $.post( "http://XXXX.com/xxxx/xxxx/", $( "#loginForm" ).serialize(), function() {
                                alert( "success" );
                          })
                                .done(function( data ) {
                                    if( data == "SUCCESS") {
                                        location.replace("xxxx.html");
                                    }
                                    else {
                                        alert("WRONG CREDS");
                                    }
                            })
                                .fail(function() {
                                alert( "error" );
                            });
                        });