[Answered ]-Load document returned by AJAX Call

1πŸ‘

βœ…

In the viewMethod, you can render page using POST data but not the whole page, that is ,the page you will respond just has the body tags not the head.

if success:
    return HttpResponse('<body><p>SUCCESS</p></body>')

and in front-end

$.post(url, data, function(data) {

      if(data=="ERROR") {

         alert("THERE WAS AN ERROR");

      } else {

         $('tip').append(data)
      }
});

if you still use the whole page, its formal like this: , you can use window.open or iframe tag to handle it.
But I advise just respond some snippets of html.

πŸ‘€Rex Huang

1πŸ‘

Unless there’s some peculiarity in Django, there should be nothing to prevent a POST request behaving differently from a GET request. Both should be capable of returning a URL string.

If you would prefer to receive a URL and replace the current document, then try the following :

function makeCall(url, data) {
    function newPageError(jqXHR, textStatus, errorThrown) {
        alert(textStatus + ' : ' + errorThrown);
    }
    $.post(url, data).success(function(data, textStatus, jqXHR) {
        if(!data.match(/^http/)) {
            newPageError(jqXHR, data, textStatus + ' - but error indicated');
        } else {
            location.href = data;
            //location.replace(data);//alternative; gives different Back button behaviour
        }
    }).fail(newPageError);
}

Alternatively, if you would prefer to receive an HTML snippet and work within the current document, then try the following :

function makeCall(url, data) {
    function newPageError(jqXHR, textStatus, errorThrown) {
        alert(textStatus + ' : ' + errorThrown);
    }
    $.post(url, data).success(function(data, textStatus, jqXHR) {
        if(data.toUpperCase() == 'ERROR') {
            newPageError(jqXHR, 'ERROR', textStatus + ' - but error indicated');
        } else {
            $("#myDiv").html(data); //change jQuery selector to suit
        }
    }).fail(newPageError);
}

Notes:

  • In both cases, two types of error are handled; an error indicated in a successful response, and a total HTTP error (eg internal server error).
  • In both cases, it is assumed the url, url, and query parameters, data, are passed to the function.
  • In the first case, the server-side script would need to be modified to return a URL.

Leave a comment