Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to POST a django form with AJAX & jQuery

I've checked out tons of tutorials for django AJAX forms, but each one of them tells you one way of doing it, none of them is simple and I'm a bit confused since I've never worked with AJAX.

I have a model called "note", a modelform for it, and inside the template I need that everytime a note element sends the stop() signal (from jQuery Sortables) django updates the object.

My current code:

views.py

def save_note(request, space_name):      """     Saves the note content and position within the table.     """     place = get_object_or_404(Space, url=space_name)     note_form = NoteForm(request.POST or None)      if request.method == "POST" and request.is_ajax:         msg = "The operation has been received correctly."                   print request.POST      else:         msg = "GET petitions are not allowed for this view."      return HttpResponse(msg) 

JavaScript:

function saveNote(noteObj) {     /*         saveNote(noteObj) - Saves the notes making an AJAX call to django. This         function is meant to be used with a Sortable 'stop' event.         Arguments: noteObj, note object.     */     var noteID = noteObj.attr('id');      $.post("../save_note/", {         noteid: noteID,         phase: "Example phase",         parent: $('#' + noteID).parent('td').attr('id'),         title: $('#' + noteID + ' textarea').val(),         message: "Blablbla",     }); } 

The current code gets the data from the template and prints it in the terminal. I don't know how I can manipulate this data. I've seen some people manages the data through jqueryforms to send the data to django.

How can I access the data sent by AJAX and update the note object?

like image 509
CastleDweller Avatar asked Sep 07 '11 14:09

CastleDweller


People also ask

Can you use AJAX with django?

Using Ajax in Django can be done by directly using an Ajax library like JQuery or others. Let's say you want to use JQuery, then you need to download and serve the library on your server through Apache or others. Then use it in your template, just like you might do while developing any Ajax-based application.

How do I POST with jQuery AJAX in django?

submit(function (event) { $. ajax({ type: "POST", url: "/edit_favorites/", data: { 'video': $('#test'). val() // from form }, success: function () { $('#message'). html("<h2>Contact Form Submitted!

How send data from AJAX to django?

To send and receive data to and from a web server, AJAX uses the following steps: Create an XMLHttpRequest object. Use the XMLHttpRequest object to exchange data asynchronously between the client and the server. Use JavaScript and the DOM to process the data.


2 Answers

Since you are using jQuery why not use the following:

<script language="JavaScript">     $(document).ready(function() {         $('#YOUR_FORM').submit(function() { // catch the form's submit event             $.ajax({ // create an AJAX call...                 data: $(this).serialize(), // get the form data                 type: $(this).attr('method'), // GET or POST                 url: $(this).attr('action'), // the file to call                 success: function(response) { // on success..                     $('#DIV_CONTAINING_FORM').html(response); // update the DIV                  }             });             return false;         });     }); </script> 

EDIT

As pointed out in the comments sometimes the above won't work. So try the following:

<script type="text/javascript">     var frm = $('#FORM-ID');     frm.submit(function () {         $.ajax({             type: frm.attr('method'),             url: frm.attr('action'),             data: frm.serialize(),             success: function (data) {                 $("#SOME-DIV").html(data);             },             error: function(data) {                 $("#MESSAGE-DIV").html("Something went wrong!");             }         });         return false;     }); </script> 
like image 110
Robert Johnstone Avatar answered Oct 07 '22 09:10

Robert Johnstone


You can access the data on the POST request using the name of the variable, in your case:

request.POST["noteid"] request.POST["phase"] request.POST["parent"] ... etc 

The request.POST object is inmutable. You should assign the value to a variable, and then manipulate it.

I would advise you to use this JQuery plugin, so you can write normal HTML forms and then get them "upgraded" to AJAX. Having $.post everywhere in you code is kind of tedious.

Also, use the Network view on Firebug(for Firefox) or the Developer Tools for Google Chrome so you can view what's being sent by you AJAX calls.

like image 30
Gerardo Curiel Avatar answered Oct 07 '22 08:10

Gerardo Curiel