[Fixed]-Form submission with ajax

1👍

Using $.ajax with POST does not post a form, but posts the data you send in that method. You need to choose which method to use, not both as you have done. Your code taps into the form’s submit, prevents it, then uses XmlHttpRequest to post the data instead. Why not remove your forms and just use your $.ajax implementation when the user clicks a button?

You are also not required to use the success() callback.

Edit

If you use forms, then you need some way to submit the form. Usually a ‘submit’ type input. This will do a post to the form’s target url.

If you use ajax, you don’t need forms (or any element’s name attribute), but you do need some kind of action/event that will trigger the use of that ajax POST. This is also usually a click of a button, or a select onchange. So instead of

$(document).on('submit','.commentForAjax' ... etc

which handles the submit event of the form, you can use a similar handler for a button’s click.

$("#buttonId").on("click", function() {
    //Call $.ajax POST here
});
👤DvS

0👍

There’s a django+jquery chat system tutorial on YouTube. This uses AJAX to send the messages. You can get an idea from this tutorial and optimize your code based on that. https://www.youtube.com/watch?v=Z8Gjm858CWg

The tutorial could be a bit confusing but you will find the GitHub repository link on the video description. Download the code and work from there.

Leave a comment