22๐
if you are planning to use an ajax submit with jquery you should not return html from your view.. I propose you to do this instead:
html:
<html>
<head>
</head>
<body>
<h1>Leave a Suggestion Here</h1>
<div class="message"></div>
<div>
<form action="" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit Feedback" />
</form>
</div>
</body>
</html>
the js
$('#form').submit(function(e){
$.post('/url/', $(this).serialize(), function(data){ ...
$('.message').html(data.message);
// of course you can do something more fancy with your respone
});
e.preventDefault();
});
the views.py
import json
from django.shortcuts import *
from django.template import RequestContext
from linki.forms import *
def advert(request):
if request.method == "POST":
form = AdvertForm(request.POST)
message = 'something wrong!'
if(form.is_valid()):
print(request.POST['title'])
message = request.POST['title']
return HttpResponse(json.dumps({'message': message}))
return render_to_response('contact/advert.html',
{'form':AdvertForm()}, RequestContext(request))
so that way you put the response in the message
div. instead of returning plain html you should return json.
7๐
<script type="text/javascript">
$(document).ready(function() {
$('#form_id').submit(function() { // On form submit event
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: $(this).attr('method'), // GET or POST
url: $(this).attr('action'), // the file to call
success: function(response) { // on success..
$('#success_div').html(response); // update the DIV
},
error: function(e, x, r) { // on error..
$('#error_div').html(e); // update the DIV
}
});
return false;
});
});
</script>
- [Django]-Is this the right way to do dependency injection in Django?
- [Django]-What does 'many = True' do in Django Rest FrameWork?
- [Django]-Django Rest JWT login using username or email?
2๐
$('#form-id').submit(function(e){
$.post('your/url', $(this).serialize(), function(e){ ... });
e.preventDefault();
});
- [Django]-How to customize activate_url on django-allauth?
- [Django]-What is the purpose of adding to INSTALLED_APPS in Django?
- [Django]-Do I need Nginx with Gunicorn if I am not serving any static content?
0๐
Here is a perfect tutorial for it. Iโll include the important parts:
first add this jQuery scripts to main.js
and link it to your page.
Add this codes to the main.js
(Iโll include my version for sending blog comment)
// Submit post on submit
$('#comment-form').on('submit', function(event){
event.preventDefault();
create_post();
});
// AJAX for posting
function create_post() {
$.ajax({
url : "/blogcomment/", // the endpoint
type : "POST", // http method
data : {
blog_id: blog_id,
c_name : $('#comment-name').val(),
c_email: $('#comment-email').val(),
c_text: $('#comment-text').val(),
}, // data sent with the post request
// handle a successful response
success : function(json) {
$('#comment-name').val(''); // remove the value from the input
$('#comment-email').val(''); // remove the value from the input
$('#comment-text').val(''); // remove the value from the input
$('#comment-form').prepend("<div class='alert alert-success'><button type='button' class='close' data-dismiss='alert'>×</button>" + json.result +"</div>");
},
// handle a non-successful response
error : function(xhr,errmsg,err) {
$('#comment-form').prepend("<div class='alert alert-danger'><button type='button' class='close' data-dismiss='alert'>×</button>Oop! Error happend!</div>"); // add the error to the dom
//console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
}
});
}
my views.py
for getting comment looks like this:
def get_blog_comment(request):
if request.method == 'POST':
blog_id = request.POST.get('blog_id')
user = request.POST.get('c_name')
email = request.POST.get('c_email')
comment = request.POST.get('c_text')
date = jdatetime.datetime.now().strftime("%Y-%m-%d");
response_data = {}
blogcomment = Comments(blog_id = blog_id, date = date, name = user, email = email, comment_text = comment)
blogcomment.save()
response_data['result'] = 'Success!!.'
return HttpResponse(
json.dumps(response_data),
content_type="application/json"
)
else:
return HttpResponse(
json.dumps({"nothing to see": "this isn't happening"}),
content_type="application/json"
)
And finally the url part for urls.py
which is not included in the original tutorial:
path('blogcomment/', views.get_blog_comment, name='get_blog_comment'),
- [Django]-How does django handle multiple memcached servers?
- [Django]-Django related_name for field clashes
- [Django]-Django annotation with nested filter
0๐
Donโt forget to add csrf_token
to the ajax
post request.
This way we can submit the form securely with out reloading.
In Script.js
jQuery.noConflict()
jQuery(document).ready(($) => {
$("#contactUsForm").on("submit", () => {
var el = document.getElementsByName("csrfmiddlewaretoken");
csrf_value = el[0].getAttribute("value");
$.ajax({
url: "/contactUs/",
type: "POST",
data: {
userName: $("#userName").val(),
companyName: $("#companyName").val(),
emailAddress: $("#emailAddress").val(),
message: $("#message").val(),
'csrfmiddlewaretoken': csrf_value
},
success: function (json) {
console.debug(json)
console.debug("Successfully send contact form")
},
error: function (json) {
console.error(json)
console.error("Error occured while sending contact form")
}
})
return false;
})
})
In Views.py
def contactUs(request: HttpRequest):
print("Contact Us")
if request.method == "POST":
username = request.POST.get("userName")
companyName = request.POST.get("companyName")
emailAddress = request.POST.get("emailAddress")
message = request.POST.get("message")
print(username)
print(companyName)
print(emailAddress)
print(message)
response_data = {}
response_data['result'] = 'Success!!.'
return HttpResponse(
json.dumps(response_data),
content_type="application/json"
)
pass
else:
logger.error(
f"Contact US request method {request.method} is not Valid expected POST")
return redirect("/")
- [Django]-How do you configure Django to send mail through Postfix?
- [Django]-Django migration fails with "__fake__.DoesNotExist: Permission matching query does not exist."
- [Django]-Django select_for_update cannot be used outside of a transaction