1

I've been learning Django + jQuery and so far have been able to AJAX-ify a New Post functionality. My question now is how do I display the new Post nicely and easily in the Post List AJAX-ly?

views.py:

def add_post(request):
error_msg = u"No POST data sent."
post = Post()
if request.method == "POST":
    #do stuff

return HttpResponse("success")

So far I am able to return "success" and save the new Post just fine.

jQuery:

       $("form#add_post").submit(function() {
       //do stuff
       var args = {type:"POST", url:"add_post/", data:data, complete:function(res, status) {
            if (status == "success") {
                alert("success");
            } else {

            }
        }};

       $.ajax(args);

       return false;

   })

Just alerting "success" here, and that works fine. I can see the new Post in the Post List if I refresh the page. Now how do I load the new Post AJAX-ly? Do I have to grab Post's attributes and prepend them to my DIV manually? Is there an easy way to just reload my Post List?

Thank you!

3 Answers 3

3

Why don't you just return the HTML for the post the in the success return, and use jQuery to append it to where it should go in your page. That's what I usually do in my code, it's quick and easy. For more complex solutions you'd want to return a list of JSON objects perhaps and use a javascript framework like backbone.js

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for your reply. That's actually what I wanted to avoid, building the HTML manually. Because I have a loop {% for object in object_list %} that displays all Posts when the page loads, I was hoping I could just re-run that somehow. I thought it would be more organic that way, rather than building an HTML manually and prepending it.
No, this doesn't mean you have to build it "manually". You can have a template that defines the HTML for 1 Post. And that can be included within {% for object in object_list %}. And then also in the ajax save view, after success render the template as a string for the newly created object and return the resulting HTML. response = {'success': 1, 'html': mark_safe(render_to_string('my_template', context, context_instance=RequestContext(request)))}
@rabbid: "re-running" it is also possible, if that Post list is loaded into the page through a separate AJAX request. Then you would only need to call the Post list AJAX in your save complete function if successful. But I think the method outlined by @Dominic is more efficient, as you don't need to make any additional requests.
Hmmm I think I understand what you mean, but I'll have to try it first. Thanks a lot!
1

Here's the dummy way;

views.py:

def add_post(request):
    error_msg = u"No POST data sent."
    post_instance = Post()
    if request.method == "POST":
        # I love Rock'nRoll
        return post_instance

 return HttpResponse(json.dumps({'status': 'success', 'object': post_instance}))

At template part use $.getJSON or $.ajax to catch json object from your views.py and if it is success, .append() the returned post_instance object to the list.

Comments

0

In your Django backend service, you need to give back some information related to the logic of your application. Mostly, people tend to use JSON for this.

def add_post(request):
   error_msg = u"No POST data sent."
   post = Post()
   if request.method == "POST":
      #do stuff
      response = HttpResponse(content_type = 'application/javascript')
      data = dict()
      #here it comes your logic
      #that fills 'data' with whichever 
      #information you need.
      data['message']='post added !!'
      response.write(json.dumps(data))
      return response
   else:
      return HttpResponse("NO POST REQUEST HANDLE")

Your client side next to handle that response accordingly to the data written in the HttpResponse object.

   complete: function(res, status) {
            //In here you can do whatever you want to modify your
            //HTML dynamically
            // the variable res contains the JSON object dumped in the
            // django HTTPResponse object.
            $("#message").text = res['message'];
    }

   error: function(res, status) {
            $("#message").text = "error handling ajax request";
    }

Make sure you handle both error and complete callbacks.

In the example I have given you'll need to have an HTML element with message as id, i.e:

<div id="message"></div>

1 Comment

For your add_post you should set the application/javascript mimetype of the response: return HttpResponse(json.dumps(data), mimetype='application/javascript')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.