Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Submit a form without refreshing/redirecting of the current page (Python (Django) + jQuery + Ajax)

Any way to submit a form without refreshing the current page at all using Python with jQuery Ajax? I want the end results similar to how Facebook comment works.

I'm currently using jQuery Form to do the Ajax. However, it doesn't give me the user experience that I want because:

  1. After submitting using jQuery Form, the URL on address bar refreshed to the form I submitted.

  2. It did refresh the page. I don't like it especially, let's say I was at the bottom of the page scrolled down to the maximum. After submitting the form, it refreshed the page, and the focus was redirected to the top of the page.

I hope I've made my point clear of what I want. I need something like Facebook comment system works. Someone commented, and then the comment was submitted without any refresh of the page at all.

EDIT

jQuery Code:

$('#review_submit').submit(function() { 
        var options = {};           
        $(this).ajaxSubmit(options);
        return false; 
});



    $('[name=submit_review_btn]').click(function(){                      
        $('#review_submit').submit();
    });

So, the python code to handle the submit will need to redirect a page from its server side code, so redirect the page to this URL, 'main_URL.com'

With the jQuery codes shown, results are:

  1. The URL appeared on address bar: main_URL.com/ form_action_url <--- This is the form action that I've set to submit the form.

  2. Page redirected to the page that I set in server side.

I'm confused with this Ajax experience.

like image 488
MrCooL Avatar asked Oct 30 '11 15:10

MrCooL


People also ask

How can we submit a form without refreshing page using jQuery?

Create an HTML file & add the jquery library CDN above the javascript code. Create 2 input fields, a submit button, and a span to display the result. Add an onsubmit listener to the form and take a callback with one single parameter.

How can I submit a form without refreshing the page?

Use jQuery's submit event to handle the form submit, add return false; at the end of the submit handle function to prevent the page to reload.


1 Answers

You could handle this by instead of using jquery's form, use jquery's ajaxPost. This will allow you to .serialize() the form (to get the parameters) and be able to return to a JS function to do what you want after the 'form is submitted'. Check out jQuery.post()

jsFiddle

This will not refresh the page as the post happens through an AJAX call. It allows you to run a function after the post goes through and do w/e you want (if the post returns data, it will be available here... if you want to do another GET or POST after this one was a success, it can be done here... so on and so forth)

like image 69
g19fanatic Avatar answered Oct 18 '22 02:10

g19fanatic