Django Form submit Through ajax call - javascript

I am pretty new to Ajax. i am trying to catch all the concepts.I am trying to submit a form through ajax. here's my code
views.py:
def ajax_test1(request):
if request.POST:
form = ModelForm(request.POST)
if form.is_valid():
form.save()
print request.POST.get('name')
x = request.POST.get('name')
if request.is_ajax():
response_dict = {}
response_dict.update({'server_response':x})
return HttpResponse(json.dumps(response_dict),content_type='application/json')
else:
return HttpResponse('not ok')
else:
form = ModelForm()
return render(request,'test1.html',{'form':form})
Jquery:
$(document).ready(function(){
$('#button').click(function{
var input_id = $('#id_name').val();
$.ajax({
type:'POST',
url:'/test1/',
datatype:'json',
data:{name:input_id},
success: function(json){
$('result').append(json.server_response);
},
headers:{'X-CSRFToken':csrf_token},
error: function(xhr,errmsg,err){
alert('Something worng');
}
});
});
});
Html:
<form action="" method="POST" accept-charset="utf-8">
{% csrf_token %}
{{ form }}
<p><input id="button" type="submit" value="Continue →"></p>
</form>
<div id="result">
</div>
<div id="result1">
</div>
The above code return 200 Response but data is not saving,and it return ServerResponse:Undefined

Related

Displaying comments using Ajax

i am working on a project using Django. There are lists of users posts in homepage and each post has a comment form. I was able to implement comment properly on views, but the issue now is when I submit a comment it display empty string instead of the comment, the comment display in chrome console. How do i display comment on each post by user when a form is submitted. I attached an image to my questioin to clarify my question.
home.html
<div id="newfeeds-form">
{% include 'ajax_newfeeds_comments.html' %}
</div>
ajax_newfeeds_comments.html
<!-- New Feeds comment Text -->
{% for post in all_images %}
<div class="container newfeeds-comment" id="display-comment">
{% for comment in post.comments_set %}
<div class="row">
<div class="col-1 col-md-1 col-lg-1">
{% if comment.user.profile.profile_pic %}
<img src="{{ comment.user.profile.profile_pic.url }}" class="d-flex rounded-circle" alt="image" height="28" width="28">
{% endif %}
</div>
<div class="col-10 col-md-10 col-lg-10 p-2 ml-1" id="user-commentpost">
<span class="comment-post truncate">
<span class="name text-lowercase">{{ comment.user }}</span>
{{ comment.comment_post }}</span>
</div>
</div>
{% endfor %}
</div>
{% endfor %}
<span class="md-form">
<form enctype="multipart/form-data" class="feeds-form form-inline md-form form-sm" method="POST" action="{% url 'site:home' %}" id="newfeeds-form{{ post.id }}">
{% csrf_token %}
<input type="hidden" value={{post.id}} name="post_comment">
<img src="{{ request.user.profile.profile_pic.url }}" class="rounded-circle avatar-img" height="28" width="28">
<textarea name="comment_post" class="textinput textInput animated fadeIn" placeholder="Add a comment..." required="" id="id_comment_post{{ post.id }}" onkeyup=""></textarea>
<button type="submit" class="submit" id="submit1-{{post.id}}"><i class="fas fa-paper-plane"></i></button>
</form
</span>
Views:
def home_view(request):
#All posts in new feed
all_images = Post.objects.filter(
Q(poster_profile=request.user, active=True)|
Q(poster_profile__from_user__to_user=request.user, active=True)|
Q(poster_profile__to_user__from_user=request.user, active=True)|
Q(poster_profile__profile__friends__user=request.user, active=True)).distinct().exclude(
Q(hide_post=request.user, active=True)|
Q(poster_profile__profile__blocked_users__user=request.user, active=True))
#Comment form homepage
if request.method == 'POST':
post_id = request.POST.get("post_comment")
post_obj = Post.objects.get(pk=post_id)
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.user = request.user
comment.commented_image = post_obj
comment.save()
# messages.info(request,'You submitted a comment')
#return redirect('/')
else:
form = CommentForm()
context = {
'form': form,
'all_images': all_images,
}
if request.is_ajax():
html = render_to_string('ajax_newfeeds_comments.html', context, request=request)
return JsonResponse({'form': html})
return render(request,'home.html', context)
Ajax:
<script type="text/javascript">
//HomeFeeds Comment
$(document).ready(function() {
$('.feeds-form').on('submit', onSubmitFeedsForm);
$('.feeds-form .textinput').on({
'keyup': onKeyUpTextInput,
'change': onKeyUpTextInput
});
function onKeyUpTextInput(event) {
var textInput = $(event.target);
textInput.parent().find('.submit').attr('disabled', textInput.val() == '');
}
function onSubmitFeedsForm(event) {
event.preventDefault();
console.log($(this).serialize());
var form = $(event.target);
var textInput = form.find('.textinput');
var hiddenField = form.find('input[name="post_comment"]');
$.ajax({
type: 'POST',
url: "{% url 'site:home' %}",
data: form.serialize(),
dataType: 'json',
beforeSend: function() {
form.find('.submit').attr('disabled', true);
},
success: function(response) {
$('#newfeeds-form' + hiddenField.val()).html(response.form);
textInput.val('');
var numberOfCommentsElement = $('#number-of-comments');
numberOfCommentsElement.text(parseInt(numberOfCommentsElement.text()) + 1);
},
error: function(rs, e) {
console.log(rs.resopnseText);
},
complete: function() {
textInput.trigger('change');
}
});
}
});
</script>
You don't need ajax actually, you can simply:
let value = $('myInput').val();
$('myCommentContainer').prepend(`
Format the comment as you want ${value}
`)
$('myInput').val('') // To empty the value
now call the ajax normally:
$({
type: 'POST',
url: "{% url 'site:home' %}",
data: form.serialize(),
dataType: 'json',
beforeSend: function() {
form.find('.submit').attr('disabled', true);
},
success: function(response) {}
})
Done, leave the success empty
appending it within the ajax success will make it slower anyway!

i try ajax partial refresh html,but it does't work

I'm trying to load the page locally with Ajax, but the following code doesn't work.
My idea is to pass the 'MSG' information of 'views' to Ajax and refresh the page locally without loading the entire page. If the input does not meet the requirements, the front end rejects the submission and gives a prompt message.
views.py
def login(request):
hashkey = CaptchaStore.generate_key()
image_url = captcha_image_url(hashkey)
captcha = {'image_url': image_url, 'hashkey':hashkey}
if request.POST:
username = request.POST['username']
password = request.POST['password']
key = request.POST['hashkey']
capt = request.POST['captcha']
if username and password:
if captchautil.is_valid(capt, key):
user = auth.authenticate(username=username, password=password)
human = True
if user:
auth.login(request, user)
return redirect('/')
else:
msg = '用户名密码错误'
else:
msg = '请输入正确的验证码'
else:
msg = '请输入用户名与密码'
return render(request, 'login.html', locals())
return render(request, 'login.html', locals())
login.html
{% block content %}
<div id="login" class="login">
<form action="/login/" method="post" class="navbar-form">
{% csrf_token %}
<div id="input" class="form-group">
<input type="username" name="username" class="form-control" placeholder="请输入手机号或邮箱" id='user' title="请输入手机号或邮箱"><br><br>
<input type="password" name="password" class="form-control" placeholder="密码" id='pwd' title="请输入密码"><br><br>
<img src="{{image_url}}" alt='验证码' id='id_captcha'>
<span>看不清验证码?刷新</span>
<br>
<input id='captcha' placeholder="请输入验证码" name="captcha" class="form-control" type="text" data-toggle="tooltip" data-placement="bottom" title="请输入验证码">
<input value="{{hashkey}}" type="hidden" name="hashkey" id='hashkey'>
<br>
<button type="submit" class="btn btn-primary form-control" name="click" id='click'>登录</button>
</div>
<p style="margin-left: auto;" id="msg">{{ msg }}</p></div>
</form>
<div style="margin-left: 3%">
<span>
忘记密码了?
</span>
<span style="margin-left: 3%">免费注册</span>
</div>
</div>
{% endblock %}
{% block lastscript %}
<script type="text/javascript">
$(document).ready(function(){
//刷新验证码
$('#refresh_captcha').click(function(){
$.getJSON("/refresh_captcha/", function(result){
$('#id_captcha').attr('src', result['image_url']);
$('#hashkey').val(result['hashkey'])
});
});
});
$(function(){
$("#click").submit(function(){
var username = $("#user").val();
var password = $("#pwd").val();
var captcha = $("#captcha").val();
var key = $("#hashkey").val();
$(this).ajaxSubmit({
type:'post',
url: '/login/',
dataType: 'text',
data:{'username':username, "password":password, "capt":captcha, "key":key},
success:function(msg){
$("#msg").html(msg);
}
});
return false;
})
})
</script>
{% endblock %}
I didn't find out where the problem was. Please help me if you know
If you are fetching form dynamically and if you are trying to say like your javascript click functions are not working then you should try below.
$(document).on("click","#test-element",function() {
});
instead of normal click or submit an event
$("#click").submit(function(){ }); .
As per my knowledge if you are creating dynamic elements then the normal click event of jquery will not work. you need to write click event what added above.

Using Ajax to post a form, no response

Django version 1.11.1
I have a form on my template, wanna use ajax to post it which can only change the form, my form code like:
<form action="" class="poster" id="posterForm">
{% csrf_token %}
<input type="file" accept="image/png,image/gif,image/jpeg" id="img_input" class="file_btn">
<input type="button" class="file_front_btn" value="选择图片" name="image">
<input type="text" name="title" id="title" class="title_area" placeholder="标题(不超过20字):">
<span class="img_root">已选图片:<span id="img_root" class="hidden">无</span></span>
<textarea name="content" id="content" name="content" class="content_area" placeholder="输入内容(不超过2000字):"></textarea>
<div id="title_error"></div>
<div id="content_error"></div>
<input type="button" class="submit" id="submitBtn" value="发布">
<div id="img_error"></div>
</form>
And my jQuery:
$(function(){
$('#submitBtn').on('click', function(){
$.ajax({
cache: false,
type: "POST",
url:"{% url 'community:poster' %}",
data:$('#posterForm').serialize(),
async: true,
success: function(data) {
if(data.status == 'success'){
$('#posterForm')[0].reset();
alert("发布成功")
}else if(data.status == 'fail'){
$('#img_error').html(data.msg)
}
},
});
});
})
And my views is:
class PosterView(View):
def post(self, request):
poster_form = PostForm(request.POST)
if poster_form.is_valid():
poster = poster_form.save(commit=True)
return HttpResponse("{'status':'success'}", content_type='application/json')
else:
return HttpResponse("{'status':'fail', 'msg':{0}}".format(poster_form.errors), content_type='application/json')
I use a ModelForm to commit the form, the forms is:
class PostForm(forms.ModelForm):
class Meta:
model = Posts
fields = ['image', 'title', 'content']
urls:
urlpatterns =[
url(r'^allpost/$', AllPosts.as_view(), name='allpost'),
url(r'^poster/$', PosterView.as_view(), name='poster'),
]
I can't see where the problem is, but when I click the submit button, nothing happened, no fail status.

AJAX update list of object

Can someone help me and say whats wrong I did?
In my django project I have product_detail page which has comment part. I am tring to update comments list after successfully adding new comment with AJAX. Unfortunatly it updates all page. I am little bit comfused and need advice. I need to update only list of comments not all page.
product_detail.html:
<div class="card">
<div class="card-block">
<table id="comment-table">
<thead>
<tr>
<th>Author</th>
<th>Date</th>
<th>Comment Text</th>
</tr>
</thead>
<tbody>
{% include 'project/comment_list.html' %}
</tbody>
</table>
</div>
<div class="card-footer">
<form method="post" class="comment-form" id="comment-form" action="{% url 'project:comment_add' project_code=project.code product_code=product.code %}">
{% csrf_token %}
{% for field in form %}
<div class="form-group{% if field.errors %} has-error{% endif %}">
{% render_field field class="form-control" %}
{% for error in field.errors %}
<p class="help-block">{{ error }}</p>
{% endfor %}
</div>
{% endfor %}
<button type="submit" class="btn btn-primary">Send</button>
</form>
</div>
</div>
views.py:
def comment_add(request, project_code, product_code):
data = dict()
project = get_object_or_404(Project, pk=project_code, status='open')
product = get_object_or_404(Product, pk=product_code)
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.author = request.user
comment.save()
product.comments.add(comment)
data['form_is_valid'] = True
data['html_comment'] = render_to_string('project/comment_list.html', {'product': product})
form = CommentForm()
else:
data['form_is_valid'] = False
else:
form = CommentForm()
context = {'project': project, 'product': product, 'form': form}
return render(request, 'project/product_detail.html', context)
js:
$(function () {
var saveForm = function () {
var form = $(this);
$.ajax({
url: form.attr("action"),
data: form.serialize(),
type: form.attr("method"),
dataType: 'json',
success: function (data) {
if (data.form_is_valid) {
$("#comment-table tbody").html(data.html_comment);
}
else {
$("#comment-form").html(data.html_comment_form);
}
}
});
return false;
};
$("#comment-form").on("submit", ".comment-form", saveForm);
});
The problem is type="submit" native refresh new page. You have to stop form submitting. Try something like this:
$("#comment-form").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
// here your ajax code
});

Jquery form Ajax Submit

I want to submit a form using ajax in the background. I tried:
<div class="form-horizontal" id="form">
<label for="name" class="control-label">Username</label>
<div class="controls">
<span id="name_input"><input type="text" name="name" id="medium" class='input-medium input-square'></span>
<span class="help-inline" id = "ajax_load"></span>
</div>
<div class="form-actions">
<button class="btn btn-red5" onclick="resolve()">Login</button>
<input type="reset" class='btn btn-danger' value="Reset">
</div>
</div>
And the Javascript:
<script type="text/javascript">
var resolve = function () {
jAlert('test', 'test');
$('#ajax_load').html('<img src="templates/img/ajax-loader.gif" alt="">');
$.ajax( {
url : 'plugin.php?plugin=test',
type : 'post',
data: $("#form").serialize(),
success : function( resp ) {
if(resp.ajax_success == false) {
} else {
jAlert('test', 'test');
}
}
});
};
</script>
I get an alert, but there is no form submit. I checked that with Live http headers.
Why does it not submit the form?
If it doesn't submit the form, because, the #form is not a form.
Change:
<div class="form-horizontal" id="form">
To:
<form class="form-horizontal" id="form">
You need to replace the resp.ajax_success with resp. Let us also know the response of the plugin.php?plugin=test URL.
If you don't want the <form> to get submitted on clicking on the Submit button, add a return false; at the end of the resolve function this way:
var resolve = function () {
jAlert('test', 'test');
$('#ajax_load').html('<img src="templates/img/ajax-loader.gif" alt="">');
$.ajax( {
url: 'plugin.php?plugin=test',
type: 'post',
data: $("#form").serialize(),
success: function( resp ) {
if(resp.ajax_success == false) {
} else {
jAlert('test', 'test');
}
}
});
return false;
};
its because you haven't used the form you are serializing the data from div
<div class="form-horizontal" id="form">
not form the form
should be
<form class="form-horizontal" id="form">

Categories