1

Hi I'm new in Ajax and django and I want to refresh my form. I try some code but it didn't work. I'm sure what I want to do is very basic.

Here my html:

    <div class="row" style="padding-top:20px;">
     <div class="col-md-12" id="testAjax">
      {% load crispy_forms_tags %}
      {% crispy form %}
    </div>
   </div>

I want to refresh my form in the div testAjax.

Here my view:

def createPin(request):
error = False   
if request.method == "POST":
    form = CreatePinForm(request.POST)
    if form.is_valid():
        pin = form.save(commit=False)
        pin.customer = request.user.customer
                    pin.save()
        msg = "pin saved"
        return redirect('/pin/CreatePin', {'form': form, 'msg': msg})
    else:
        error = True
else:
    form = CreatePinForm()
return render(request, 'createPin.html', {'form': form, 'error': error,})

My Ajax:

function refresh() 
{
 $form=$('#createPin');
 var datastring = $form.serialize();
    $.ajax({
        type: "POST",
        url: '/pin/CreatePin/',
        dataType: 'html',
        data: datastring,
        success: function(result)
        {
            /* The div contains now the updated form */
            $('#testAjax').html(result);
        }
    });

}

Thanks alot for your help.

5
  • Where does your code fails ? Wich is your error ? Commented May 31, 2014 at 8:45
  • Liarez, nothing happens Commented Jun 1, 2014 at 13:45
  • The view to render the template is not the same as the view of AJAX. Where is your AJAX view ? Where you say My Ajax that's not an AJAX function, that's a JQuery function that calls an AJAX function, and the url to the view in that function has to be the url of an AJAX view (in a file called ajax.py in same folder as view) Commented Jun 1, 2014 at 14:30
  • Check the function I call ajax_view that function has to be in the file ajax.py, and the best response is to create a list, assign the values you need in the template, and return that list converted to JSon as in the ajax_view : return HttpResponse(simplejson.dumps(response)) You will get this list in JQuery under success: and you have to parse the json doing ` result = JSON.parse(response);` in the JQuery function Commented Jun 1, 2014 at 14:32
  • What are you exactly trying to change without reloading the page? I mean, you're trying to update the form in wich way ? Fill the textbox with different information ? Update the actual information ? You can create a string in the AJAX function to be the full code you need to replace. Is this is what you're looking for I'll fullfill the AJAX function in my answer to help you Commented Jun 2, 2014 at 6:48

1 Answer 1

2

When I need to do some operations and I don't want to reload the page I use a JQuery call to Ajax, I make the pertinent operations in AJAX and then receive the AJAX response in the JQuery function without leaving or reloading the page. I'll make an easy example here for you to understand the basics of this:

JQuery function, placed in the template you need

function form_post(){       
    //You have to get in this code the values you need to work with, for example:
    var datastring = $form.serialize();

    $.ajax({  //Call ajax function sending the option loaded
      url: "/ajax_url/",  //This is the url of the ajax view where you make the search 
      type: 'POST',
      data: datastring,
        success: function(response) {
            result = JSON.parse(response);  // Get the results sended from ajax to here
            if (result.error) { // If the function fails
                // Error
                alert(result.error_text);
            } else {  // Success

                    //Here do whatever you need with the result;                                                  
                } 
            }
        }
    });              
    }

You have to realize that I cannot finish the code without knowing what kind of results you're getting or how do you want to display them, so you need to retouch this code on your needs.

AJAX function called by JQuery

Remember you need to add an url for this Ajax function in your urls.py something like:

url(r'^/ajax_url/?$', 'your_project.ajax.ajax_view', name='ajax_view'),

Then your AJAX function, it's like a normal Django View, but add this function into ajax.py from django.core.context_processors import csrf from django.views.decorators.csrf import csrf_exempt from django.utils import simplejson

@csrf_exempt
def ajax_view(request):    
    response = []
    #Here you have to enter code here 
    #to receive the data (datastring) you send here by POST       
    #Do the operations you need with the form information
    #Add the data you need to send back to a list/dictionary like response
    #And return it to the JQuery function `enter code here`(simplejson.dumps is to convert to JSON)
    return HttpResponse(simplejson.dumps(response))

So, without leaving the page you receive via javascript a list of items that you sended from ajax view.

So you can update the form, or any tag you need using JQuery

I know that this can be so confusing at the beginning but once you are used to AJAX this kind of operations without leaving or reloading the page are easy to do.

The basics for understanding is something like:

  1. JQuery function called on click or any event you need
  2. JQuery get some values on the template and send them to AJAX via POST
  3. Receive that information in AJAX via POST
  4. Do whatever you need in AJAX like a normal DJango view
  5. Convert your result to JSON and send back to the JQuery function
  6. JQuery function receive the results from AJAX and you can do whatever you need
Sign up to request clarification or add additional context in comments.

1 Comment

I recommend to not use @csrf_exempt (For obvious security reasons), and instead load CSRF in the Ajax request with something like this : data: { csrfmiddlewaretoken: '{{ csrf_token }}', my_awesome_input: 'example' }

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.