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

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.

Related

JavaScript is not executed in tracking form

I'm doing an e-commerce website for school and got the task to implement an order tracking system to display the status history of the order. I used a template for this, and half of the code is working. In the views.py file I fetch the information form the database and put it in json format.
However in my html file there is a js script that is supposed to display the iformation from the database and that is not working.
I unfortunately do not have any previous experience with web development, so I'm lost as to why it doesn't work because in the video that used the template it worked.
If someone could help me that would be fantastic as we have to hand the project in in two days.
PS.:
When I put in the ref code and email, it just gives back the HttpResponse with the json. I'm not sure what to do with the HttpResponse though. How does it interact with the script in the html file?
I put
jQuery.noConflict();
at the start of the script as I thought maybe the bootstrap js was overshadowing my script. It didn't do anything though.
Here is my views.py function:
def tracking(request):
if request.method == "POST":
ref_code = request.POST.get('ref_code', '')
email = request.POST.get('email', '')
try:
order = Order.objects.filter(ref_code=ref_code, email=email)
if len(order) > 0:
update = OrderUpdate.objects.filter(ref_code=ref_code)
updates = []
for item in update:
updates.append(
{'text': item.update_desc, 'time': item.timestamp})
response = json.dumps(updates, default=str)
return HttpResponse(response)
else:
return HttpResponse('Please enter a valid ref code and email address.')
finally:
print()
return render(request, 'order_tracking.html')
Here is the script from the order_tracking html file:
<script>
jQuery.noConflict();
$('#trackingForm').submit(function(event) {
$('#items').empty();
var formData = {
'ref_code': $('input[name=ref_code]').val(),
'email': $('input[name=email]').val(),
'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val()
};
print(ref_code)
$.ajax({
type: 'POST',
url: '/order-tracking/',
data: formData,
encode: true
})
.done(function(data) {
console.log(data)
updates = JSON.parse(data);
if (updates.length > 0 & updates != {}) {
for (i = 0; i < updates.length; i++) {
let text = updates[i]['text'];
let time = updates[i]['time'];
mystr = `
<li class="list-group-item d-flex justify-content-between align-items-center">
${text}
<span class="badge badge-primary badge-pill">${time}</span>
</li>`
$('#items').append(mystr);
}
} else {
mystr = `<li class="list-group-item d-flex justify-content-between align-items-center">
Sorry, We are not able to fetch this ref code and email. Make sure to type correct ref code and email</li>`
$('#items').append(mystr);
}
});
event.preventDefault();
});
</script>
And this is the rest of the html file, I'm not sure if it's relevant:
{% block content %}
<div class="container tracking">
<div class="col my-4">
<h2> Enter Your Order ID and Email address to track your order </h2>
<form method="post" action="#" id="trackingForm">{% csrf_token %}
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputname">Ref Code</label>
<input type="text" class="form-control" id="ref_code" name="ref_code" placeholder="Ref Code">
</div>
<div class="form-group col-md-6">
<label for="inputEmail">Email</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Email">
</div>
<button type="submit" class="btn btn-primary">Track Order</button>
</div>
</div>
<div class="col my-4">
<h2>Your Order Status:</h2>
<div class="my-4">
<ul class="list-group" id="items">
</ul>
</div>
</div>
</div>
{% endblock content %}

how can i resolve the issue in displaying the ajax search results in django?

Problem
The results are being retrieved by the ajax search function but when I display the data retrieved in the selector using $(selector).htm(data) it loads whole the page with a page with correct search results.
The code is attached below with the screenshot of what I'm getting from this code for a better understanding.
JS
$('#searchsubmit').on('click', function(e){
e.preventDefault();
q = $('#search').val();
console.log(q);
updateContentBySearch(q);
});
function updateContentBySearch(q) {
var data = {};
data['search_by'] = q
// data["csrfmiddlewaretoken"] = $('#searchform [name="csrfmiddlewaretoken"]').val();
$.ajax({
method: 'POST',
url: "{% url 'main:Search' %}",
data: {
'search_by': q,
'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val()
},
success: function (data) {
searchSuccess(data)
}
});
}
function searchSuccess(data, textStatus,jqXHR)
{
$('#search-results').html(data);
}
HTML
<div class="row">
<div class="row justify-content-center" style="text-align:center">
<form class="d-flex col-md-6" id="searchform" method="POST">
{% csrf_token %}
<div class="input-group mb-3" style="text-align:center">
<input name="q" type="text" class="form-control" placeholder="Search" id="search">
<button class="btn btn-primary shadow px-5 py-2" type="submit" id="searchsubmit">Search</button>
</div>
</form>
</div>
<hr style="border-top: 1px solid #ccc; background: transparent;">
<div class="row" id="search-results">
{% regroup transaction by productID as ProductList %}
{% for productID in ProductList %}
///some code
</div>
{% endfor %}
</div>
VIEWS
#csrf_exempt
def search(request):
q = request.POST.get('search_by')
print(q)
product = Products.objects.all()
cart_product_form = CartAddProductForm()
transaction = transactions.objects.filter(productID__name__icontains=q,status='Enable').order_by('productID')
print(transaction)
context={
'products':product,
'transaction': transaction,
'cart_product_form':cart_product_form
}
html = render_to_string('main/home.html',context)
return JsonResponse(html,safe=False , content_type="application/json")
SCREENSHOT
Now in this screenshot u can see it showing me two banners and search bars and after the second the products from the search results are displayed. It's like it loads the whole page again within the page from the selector i have passed data too.
DOES ANYONE KNOWS HOW TO RESOLE THIS ISSUE OR WHERE I HAVE DONE WRONG.
because you render 'main/home.html' agin ! you just need send a json response with your context data and add it to web page with JS or create a new html template and render that with your context data and send that as response!

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!

How to get data from AJAX request with Symfony 4?

I'm trying to get data from an AJAX request with Symfony 4 and what I get is not that I'm expecting.
Here is my routes.yaml
(...)
ajax_test:
path: /ajax/test
defaults: { _controller: 'App\Controller\AjaxTestController::test' }
requirements:
_method: POST
My controller :
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class AjaxTestController extends AbstractController
{
public function test(Request $request) {
if ($request->isXmlHttpRequest()) {
$serializer = $this->get('serializer');
$response = $serializer->serialize('test ok', 'json');
return new JsonResponse(['data' => $response]);
}
return new Response("test ko", 400);
}
}
Here is the template where I make the AJAX request :
{% extends "layout.html.twig" %}
{% set active = 'connexion' %}
{% block page_title 'Login' %}
{% block final_javascripts %}
{{ encore_entry_script_tags('sendCredentials') }}
{% endblock %}
{% block content %}
(...)
<div class="row mt-4">
<div class="col-md-6">
<form id="connexion-form" action="{{ path('security_connexion') }}" method="post">
<div class="form-group">
<label for="email">Email</label>
<input type="text" id="email" name="_email" class="form-control">
</div>
<div class="form-group">
<label for="password">Mot de passe</label>
<input type="password" id="password" name="_password" class="form-control">
</div>
<button type="submit" class="btn btn-primary button">Se connecter</button>
</form>
</div>
</div>
</div>
</div></div>
{% endblock %}
And finally the JavaScript file (sendCredentials.js) where I make AJAX request :
$(document).ready(function() {
$('#connexion-form').submit(function(event) {
sendCredentials($('#email').val(), $('#password').val());
});
});
function sendCredentials(username, password) {
$.ajax({
method: "POST",
url: "/ajax/test",
data: {username: username, password: password},
async: false
}).done(function(msg) {
console.log(msg['data']);
console.log(msg);
});
}
The first log console.log(msg['data']); displays undefined. The second log console.log(msg); displays me the html code of the template itself, that is to say the code of the template generated by twig. I don't understand why. How to get the data wanted : 'test ok' ?
P.S. : I don't use credentials yet (username and password), I'm just making tests, I want first the AJAX request to work.

AJAX I must double click to submit second textarea! (Laravel)

$(document).ready(function (){
$('#myForm').submit(function (e) {
e.preventDefault(); //Do not submit the form
var dataflow=$(this).serialize(); //Get the inputs value
$.post('{{route('homepage.update')}}', dataflow, function (data){ //post.create is the route name
//The request is done, do something with the server response
});
});
});
I use this to save form without refresh
Here is my route
Route::post('/homepage/update', 'AdminController#Update')->name('homepage.update');
And my html
{{ csrf_field() }}
<div class="form-group">
<label for="title"><b class="fa fa-pencil"></b> Title</label>
<input id="title" class="form-control" value="{{ $article->title }}" name="title">
<br />
<label for="content"><b class="fa fa-home"></b> Desc</label>
<div class="box-body pad">
<textarea id="content" name="content" rows="10" cols="80">
{{ $article->content }}
</textarea>
</div>
</div>
<center>
<div class="form-group">
<button type="submit" class="btn btn-success btn-sm"><b class="fa fa-save"></b> Submit</button>
</form>
My function who update ajax data
public function HomePage(Request $r) {
$article = Article::find(1);
$article->title = $r->input('title');
$article->content = $r->input('content');
$article->homepage = 1;
$article->save();
}
The problem is i must click twice button to save two forms when i click one it submit only title! Please help how to fix that

Categories