Ajax function inside JavaScript is not getting called - javascript

I am trying to render the template called reset_password_page.html using AJAX. I intend to send some data to this template. The problem is that page is not getting loaded. It gets loaded when I use location.href, but this cannot be used as I won't be able to send any data to the template.
function trial() {
if ("{{ verified }}" == "yes") {
document.getElementById('lbl_verify').style.display = "block";
document.getElementById('lbl_verify2').style.display = "none";
window.setTimeout(function() {
$(document).ready(function() {
$.ajax({
url: "{% url 'reset_password_page' %}",
type: "POST",
data: {
csrfmiddlewaretoken: '{{ csrf_token }}'
},
async: false,
});
});
}, 1000);
} else {
}
}
views.py
def reset_password_page(request):
return render(request,"reset_password_page.html")

Its due to the if condition used.You are comparing
if ("{{ verified }}" == "yes")
which is false.
try if ({{ verified }} == "yes") which will fetch verified value.

Related

Return a view from an ajax call

I have 0 experience in Ajax, and now I'm trying to get an html table to return on an ajax call.
As a result, I get the error
jquery-3.6.0.min.js:2 POST http://test.loc/%7B%7B%20url('blog/articles')%20%7D%7D 404 (Not Found)
I understand that there are still a lot of mistakes, so don't judge too much, and help in any way you can :)
Route:
Route::post('blog/articles', 'App\Http\Controllers\BlogController#articles');
Ajax on calling page:
function getBlogLists(category_id) {
var category_id = category_id;
$.ajax({
url: "{{ url('blog/articles') }}",
type: 'POST',
data: { 'category_id': category_id },
datatype: 'html',
success: function(data) {
console.log('success');
console.log(data);
document.querySelectorAll('.blog-filter__item').forEach(el => {
el.addEventListener('click', () => {
document
.querySelector('.blog-filter__item.active')
.classList.remove('active');
el.classList.add('active');
var dataFilter = $(el).attr('data-filter');
if (dataFilter == 'all') {
$('.blog-list').show();
}
else {
$('.blog-list').hide()
$(dataFilter).show()
}
});
});
},
});
}
//on page load
getBlogLists("{{ $category->id }}");
Controller:
public function articles() {
$input = Request::all();
if(Request::isMethod('post') && Request::ajax()) {
if($input['category_id']) {
$articles = Article::select('select * from blog_categories where blog_category_id = ?', array($input['category_id']));
$returnHTML = view('blog.articles')->with('articles', $articles)->render();
return response()->json( array('success', 'html'=>$returnHTML) );
}
}
}
View:
#foreach($articles as $index => $article)
<div class="blog-list category_{{ $article->blog_category_id }}">
#if ($index % 2 === 1)
<div class="blog-article blog-article--right">
<h2 class="blog-article_title">{{ $article->title }}</h2>
</div>
#else
<div class="blog-article blog-article--left">
<h2 class="blog-article_title">{{ $article->title }}</h2>
</div>
#endif
</div>
#endforeach
You have this error because you have a problem in your URL.
function getBlogLists(category_id) {
var category_id = category_id;
$.ajax({
url: "{{ url('blog/articles') }}",
Here, the url is literally {{ url('blog/articles') }}, I mean, as a string.
You are sending the request to http://test.loc/{{ url('blog/articles') }}, which once encoded gives http://test.loc/%7B%7B%20url('blog/articles')%20%7D%7D.
That's why you are getting a 404 error (not found), obviously this url doesn't exist.
First, remove the url variabilization:
function getBlogLists(category_id) {
var category_id = category_id;
$.ajax({
url: "http://test.loc/blog/articles", //or whatever your url is
Then in your controller, you just have to return the HTML and it will be inside data in your javascript success callback.
Do a simple test first:
public function articles() {
return "<h1>HelloWorld</h1>";
}
If it works with this simple "hello world", it will work with the view you are rendering as well.

Refresh content in a for loop using jquery in Django

I am creating a website that allows users to search for a list of papers. Once a list of papers is returned, the user can click "like" or "dislike" to one or more papers. The like count should dynamically update as the user click the like button.
I am using jquery to handle the dynamic update of the like count. However, I am not sure how to tell the success function in the ajax WHICH id to update. The reason is that the id is generated on the fly, and it is determined by which papers are returned as search results to the user.
So far, I have the following in the template:
{% for result in results %}
<li >
{{ result.title}},
<span class="like_span fa fa-thumbs-up"></span>
<strong id="like_count_{{ result.pk }}">{{result.likes}} </strong>
</li>
{% endfor %}
As you can see, i specify the id of the part where I want the dynamic update to happen as "like_count_{{ result.pk }}". I am not sure if this is the best way to go about it.
The jquery part looks like this:
<script>
$(document).ready(function(){
$(".like_button").click(function(){
$.ajax({
type: "GET",
data: {'pk': $(this).data('pid'),
'liked': $("span").hasClass('fa fa-thumbs-up') },
url: "{% url 'search:paperpreference' %}",
success: function(response) {
var pk = $(this).data('pid');
$(?????).html(response.likes )
},
error: function(response, error) {
alert(error);
}
});
});
});
</script>
Simply put, I don't know how can i specify the ????? part such that when success, the new like count is only updated to that specific paper, not the first paper in the loop.
The views.py has the following so far:
def paperpreference(request):
# if request.method == "GET":
pid = request.GET['pk']
paper = Paper.objects.get(pk=pid)
likes = paper.likes + 1
paper.likes = likes
paper.save()
data = {'likes': paper.likes}
return JsonResponse(data)
I am new to Jquery, any help would be much appreciated!
Thanks to suggestions by #dirkgroten, the like count can now be dynamically updated by the following jquery function. The trick is to move the pk declaration to before the ajax.
<script>
$(document).ready(function(){
$(".like_button").click(function(){
var pk = $(this).data('pid')
$.ajax({
type: "GET",
data: {'pk': pk,
'liked': $("span").hasClass('fa fa-thumbs-up') },
url: "{% url 'search:paperpreference' %}",
success: function(response) {
$("#like_count_"+ pk).html(response.likes )
},
error: function(response, error) {
alert(error);
}
});
});
});
</script>
another option is return the id from the server.
def paperpreference(request):
# if request.method == "GET":
pid = request.GET['pk']
paper = Paper.objects.get(pk=pid)
likes = paper.likes + 1
paper.likes = likes
paper.save()
data = {'likes': paper.likes,'pid':pid}
return JsonResponse(data)
<script>
$(document).ready(function(){
$(".like_button").click(function(){
var pk = $(this).data('pid')
$.ajax({
type: "GET",
data: {'pk': pk,
'liked': $("span").hasClass('fa fa-thumbs-up') },
url: "{% url 'search:paperpreference' %}",
success: function(response) {
$("#like_count_"+ response.pid).html(response.likes )
},
error: function(response, error) {
alert(error);
}
});
});
});
</script>

AJAX Data not Posting to View in Django

I've implemented a basic checkout wherein a user may select a shipping address from a list of addresses via the 'address' class. It works on the server side, but I would like to use AJAX to avoid having the page refresh with each selection. The code is not posting any data, however. What am I doing wrong?
views.py
def pick_address(request):
if request.method == 'POST':
checkout = Checkout.objects.get(pk=request.POST.get('checkout'))
checkout.shipping_address = ShippingAddress.objects.get(pk=request.POST.get('address'))
checkout.save()
return HttpResponse('success')
pick_address.js
<script>
$('.address').click(function () {
$.ajax({
type: 'POST',
url: '{% url 'pick-address' %}',
dataType:'json',
data: {
checkout: {{ checkout.pk }},
address: {{ address.pk }},
csrfmiddlewaretoken: '{{ csrf_token }}'
},
success: function (data) {
if (data['success']) {
alert('success!');
}
}
});
});
</script>
In views.py
def pick_address(request):
if request.method == 'POST':
checkout = Checkout.objects.get(pk=request.POST.get('checkout'))
checkout.shipping_address = ShippingAddress.objects.get(pk=request.POST.get('address'))
checkout.save()
ctx={'success':True}
return HttpResponse(json.dumps(ctx),content_type='application/json')
in pick_address.js
success: function (data) {
if (data.success) {
alert('success!');
}
}
I was using the slim version of jQuery, which does not support AJAX. The code was otherwise (mostly) correct.

Handling async ajax calls within django session

I have a Django application, where the template contains for loop in javascript, which iterates all of the check-boxes in some table. For each check box, I send an ajax request to a view function, where I want to save the id of the check box in a list or remove the id from the list (depends on the check state). I need the list to be a part of the request.session dictionary.
The results show me that the ajax calls are asynchronous and that makes my list to be wrongly updated, and inconsistent.
Are there some thread safe data structures which I can store as part of the session, and ensure sync list updating?
JavaScript and Ajax:
function checkAll(source, type) {
checkboxes = document.getElementsByName(type);
for(var i=0, n=checkboxes.length;i<n;i++) {
if (checkboxes[i].checked != source.checked) {
checkboxes[i].checked = source.checked;
select_row(checkboxes[i], source.checked);
}
}
}
function select_row(row_selector, is_checked) {
is_box_checked = typeof is_checked !== 'undefined' ? is_checked : row_selector.checked;
request = {
url: "{% url 'set_check_box' %}",
type: "POST",
contentType: "application/x-www-form-urlencoded",
data: {
csrfmiddlewaretoken: "{{ csrf_token }}",
checked: is_box_checked,
check_box_id: row_selector.id,
type: row_selector.name
},
error: function(response, status, error_msg) {
console.log(error_msg);
}
};
$.ajax(request);
}
View function:
def set_check_box(request):
request.session.modified = True
check_box_list = list(request.session['connects_check_boxes_id_list'])
check_box_id = request.POST["check_box_id"]
is_checked = json.loads(request.POST['checked'])
if is_checked:
check_box_list.append(check_box_id)
else:
check_box_list.remove(check_box_id)
request.session['connects_check_boxes_id_list'] = list(check_box_list)
return HttpResponse("")
All I had to do is set async option to false as part of the request parameters.
function select_row(row_selector, is_checked) {
is_box_checked = typeof is_checked !== 'undefined' ? is_checked : row_selector.checked;
request = {
url: "{% url 'set_check_box' %}",
type: "POST",
contentType: "application/x-www-form-urlencoded",
async: false,
data: {
csrfmiddlewaretoken: "{{ csrf_token }}",
checked: is_box_checked,
check_box_id: row_selector.id,
type: row_selector.name
},
error: function(response, status, error_msg) {
console.log(error_msg);
}
};
$.ajax(request);
}

Show succes message from ajax

I have a question, So I create a sistem that update in database a row when onChange a select box. All goes well, but I want to drop a succes message if update was with succes.
My view :
<form action="" id="updateStatus" method="post">
<select id="statusSelect"
name="{{ gift.id_instant_gagnant }}"
class="form-control"
onChange="updateCadeauStatus({{ gift.id_instant_gagnant }})">
{% for key,statut in form_logistique.statut.choices %}
<option value="{{ key }}"
{% if gift.etat == key %}selected="selected"{% endif %}>
{{ statut }}
</option>
{% endfor %}
</select>
</form>
<script>
function updateCadeauStatus(id) {
var id = id;
var selectedName = $("#statusSelect option:selected").val();
var url_deploy = 'http:localhost/updateStatus'
console.log(id);
console.log(selectedName);
$.ajax({
url: url_deploy,
type: "POST",
async: true,
data: { id_cadeau:id, id_status:selectedName}
});
}
</script>
The controller :
public function updateStatus(){
$iGiftId = $_POST['id_cadeau'];
$iNewStatus = $_POST['id_status'];
$bUpdate = $this->updateStatusByGiftId($iGiftId, $iNewStatus);
return $this->render('logistique.twig');
}
The model :
public static function updateStatusByGiftId($iGiftId, $iStatusId){
$request = sprintf( ' UPDATE `%s` set etat = %d WHERE id = %d ', $table, $iStatusId, $iGiftId);
return Mysqli::query($request, $database);
}
So everything goes well but I want to drop a message after every update, too be displayed in the view. Please help me!!! Thx in advance, sorry for my english.
$.ajax({
url: url_deploy,
type: "POST",
async: true,
data: { id_cadeau:id, id_status:selectedName},
success : function(data){
console.log('success');
},
error: function(){
console.log('error');
}
});
You can drop the response of the check file on ajax.
$.ajax({
url: url,
type: "POST",
...
success: function(response){
window.alert(response);
}
})
To be more specific, if you want to give a message only when you successfully changed the row. Modify the validation file (url:) and print a messagge only when you had success..
There are other ways to do that..
You can print a "message id" and get it with the script and drop a message:
$.ajax({
url: url,
type: "POST",
...
success: function(response){
if(response == '1'){
window.alert('Successfully changed!!');
}else if(response == '0'){
$("#foo").html("Error, not changed :(");
}else{
------ something else ------
}
}
})
Hope I could help !
Im not sure if you have your response in another file.
Cuz your response now is in the var data in the line with the code:
}).done(function(data){
$.ajax({
url: url_deploy,
type: "POST",
async: true,
data: { id_cadeau:id, id_status:selectedName}
}).done(function(data){
$("[SuccesDiv]").append("[Succes MSG]");
});
The text between the [ - ] is ment to put there your own element or data.
[EDIT]
I did'nt look good...
You are not looking when it is changed.
To do that, do this:
$("select").on("change", function(){
$.ajax({
url: url_deploy,
type: "POST",
async: true,
data: { id_cadeau:id, id_status:selectedName}
}).done(function(data){
$("[SuccesDiv]").append("[Succes MSG]");
});
});

Categories

Resources