Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ajax request not working in django?

Here is my js that uses Jquery blockUI plug-in:

$(document).ajaxStop($.unblockUI);

 $('#submit-id-submit').click(function() {
  $.blockUI({message:'<h1><img src="{% static 'css/spinner.gif' %}" /> Just a moment ...</h1>'});
  $.ajax({
    url: "/search/test/",
    cache:'false',
    dataType: 'text',
    type:"GET",
    success: function(data){
      alert(data);
    },
    error: function(data){
      alert('error; '+ eval(error));
    }
  });
});

my view:

def test_ajax(request):
    time.sleep(20)
    print "in test_ajax"
    return HttpResponse("hell world")

url(r"search/test/$", test_ajax,name="dummy"),

First, I see the ajax call is returning error (because I get alert from error. but it does not show the error message)

Secondly, my view test_ajax is not called, because I would expect the print statement there to be executed, but it does not execute.

I cannot figure out what is going wrong here.

like image 205
eagertoLearn Avatar asked Sep 11 '25 10:09

eagertoLearn


1 Answers

I have had similar issues in the past. The reason is you are allowing the default form submission. Try this and see what you get;

$('#submit-id-submit').click(function(e) {
   e.preventDefault();
  $.blockUI({message:'<h1><img src="{% static 'css/spinner.gif' %}" /> Just a moment ...</h1>'});
  $.ajax({
    url: "/search/test/",
    cache:'false',
    dataType: 'text',
    type:"GET",
    success: function(data){
      alert(data);
    },
    error: function(data){
      alert('error; '+ eval(error));
    }
  });
});

or simply return false

$('#submit-id-submit').click(function() {

  $.blockUI({message:'<h1><img src="{% static 'css/spinner.gif' %}" /> Just a moment ...</h1>'});
  $.ajax({
    url: "/search/test/",
    cache:'false',
    dataType: 'text',
    type:"GET",
    success: function(data){
      alert(data);
    },
    error: function(data){
      alert('error; '+ eval(error));
    }
  });
   return false;
});

By doing either of this, you prevent default action (in your case form submission I guess) you can read more about this here;

like image 200
brain storm Avatar answered Sep 14 '25 10:09

brain storm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!