Ali B
Ali B

Reputation: 491

Returning ajax response from django

I have exhausted my brain trying to get something simple to work. I want to change the behavior of a form from post reload to ajax with django. I just can't get it to work.

The form is something like:

<form id="form1" action="/myurl/" method="post" onsubmit="doexchange">
<input id="input1" type="hidden" name="serializedData" value=""/>
<button id="button1" type="submit">render<button/>
</form>

Using jquery, I have something like:

function doexchange(){
var dataBuffer = new Object();
dataBuffer = myCollecter(dataBuffer);

$("#input1").attr("value", JSON.stringify(dataBuffer));

$.get($("#form1").attr("action"), 
      {serializedData: $("#input1").attr("value")}, 
      function(data){
        alert('yes' + data);
      });

return false;
}

Now the return false is to prevent the original form from doing a POST of its own.

On the server side, I have something really simple like:

def handler(request, data):
    return HttpResponse('{}', 'application/json')

The client successfully sends the data to the server through an ajax request. The server also returns the {} empty bracket to the client. But instead of the callback function getting called and seeing and alert, the whole page reloads and I see only {} on a new page.

As I said I have tried so many different things, but I think I am missing something elephant big... Any ideas? Oh, and I am using the latest Mozilla firefox, but I don't think this is a browser specific issue...

Upvotes: 0

Views: 217

Answers (2)

chhabrakadabra
chhabrakadabra

Reputation: 440

I don't think a solution needs to be very convoluted to achieve the outcome you're going for. Consider something on the lines of:

A page that looks like:

<a class="btn" onclick="doexchange">render</a>

An JavaScript that looks like the following:

function doexchange(){
    var dataBuffer = myCollecter(dataBuffer);

    $.get('/myurl/', {serializedData: JSON.stringify(dataBuffer)}, function(data) {
        alert('yes' + data);
    });
}

Upvotes: 1

czarchaic
czarchaic

Reputation: 6318

Try binding to the form submit in your javascript.

$('#form1').bind('submit', function( e ){
  e.preventDefault();
  var form=$(this),
    input=form.find('input[name="serializedData"]');
  $.ajax({
   //
  });

Upvotes: 0

Related Questions