[Answer]-Return in Http Response and Html page but its not showing on the browser in Django

1👍

It’s a client side thing, that means the desired behaviour needs to be implemented with javascript. Django is functioning normally here.

When you’re sending Requests via AJAX, that is a non blocking request with the XMLHttpRequestheader set, your browser won’t trigger the chain of events that occurs when a server side script evaluates your form and returns something, which may be data, or a redirect, depending on whether the form validated or not.
A typical AJAX call in jQuery looks like this:

$.ajax({
  type: "POST",
  url: url,
  data: data,
  success: success,
  dataType: dataType
});

If you would like to perform some actions when the request you sent by XMLHttpRequest returns, you could attach that to the appropriate success handler:

// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.post( "example.php", function() {
  alert( "success" );
})
  .done(function() {
    alert( "second success" );
  })
  .fail(function() {
    alert( "error" );
  })
  .always(function() {
    alert( "finished" );
});

// Perform other work here ...

// Set another completion function for the request above
jqxhr.always(function() {
  alert( "second finished" );
});

If you need to redirect to the URI that is returned as a redirect from your server you can get the redirect URI from the response in the success handler:

$.ajax({
    type: "POST",
    url: reqUrl,
    data: reqBody,
    dataType: "json",
    success: function(data, textStatus) {
        if (data.redirect) {
            // data.redirect contains the string URL to redirect to
            window.location.href = data.redirect;
        }
        else {
            // data.form contains the HTML for the replacement form
            $("#myform").replaceWith(data.form);
        }
    }
});

If you would like to modify the URL in the users bar without reloading the page you could have a look at this question.

Leave a comment