how to use ajax function to send form without page getting refreshed, what am I missing?Do I have to use rest-framework for this?

后端 未结 11 2153
花落未央
花落未央 2021-01-05 03:37

I\'m trying to send my comment form using ajax, right now when user inserts a comment then whole page gets refreshed. I want this to be inserted nicely without page getting

11条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-05 04:23

    The main thing you need to do for preventing page reloading on form submit is calling event.preventDefault() in your form submit event handler. @Vibhu provided a very good code example in the answer above. That's exactly what you need to do on client side. (I provide his code with a single difference, request is sent to 'comment/create-ajax', not to 'comment/create'

    $(document).ready(function() {
    $("#commentForAjax").submit(function( event ) {
        $.ajax({
            type:'POST',
            url:'comment/create-ajax',
            data:{
                post_id:$('#post_id').val(),
                origin_path:$('#origin_path').val(),
                parent_id:$('#parent_id').val(),
                csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
            },
            success: function(response){
    
            }
        });
        event.preventDefault()
    });
    

    });

    On server side, you may provide one more controller (view in Django terms) which handles POST /comments/create-ajax, it should look somehow like this:

    def handle_comment_creation_via_ajax(request):
        comment_dict = json.loads(request.body)
        # or json.loads(request.body.decode("utf-8")) if you use python 3
        comment = CommentModel(**comment_dict) # This will work if comment has no nested models, otherwise, implement static method in your model class which takes dict and returns model instance.
        try:
            comment.save()
        except Exception as e:
            return JsonResponse({'success':false, 'message': str(e)}, status_code=400)
        return JsonResponse(model_to_dict(instance, fields=[], exclude=[])
    

    JsonResponse and model_to_dict

    Good luck!

    P.S. Note that incoming model must be validated before save

提交回复
热议问题