How to get next pages in load more django - ajax

I get data using ajax with button load more, and if it's not have next pages, it will render "all data has been displayed"
index.html
<div class="panel-body">
<div id="display-data">
<span id="loading-help">Loading data. . .</span>
</div>
</div>
<script>
var page = 1
$(document).ready(function(){
$.get("{% url 'account:profile' %}?param=get_data&page="+page,
function(data){
$("#display-data").append(data)
$("#loading-help").remove()
page++
})
</script>
data-ajax.html
{% for data in datas %}
<div class="list-trx-data">
<div class="row align-items-center">
<div class="col-md-8">
<div class="row align-items-center">
<div class="col-md-4 col-sm-12 col-12 data-date">
{{data.get_formatted_date}}</div>
<div class="col-md-8 col-sm-12 col-12 data-name">
{{data.get_data}}</div>
</div>
</div>
<div class="col-md-4">
<div class="row align-items-center">
<div class="col-md-6 col-8 data-amount">
{{data.get_formatted_amount}}</div>
<div class="col-md-6 col-4 ">
<div class="data-progress">
<div class="pg-bar" style="width:
{{data.get_data.get_progress_str}}"></div>
</div>
</div>
</div>
</div>
</div>
</div>
{% endfor %}
{% if datas.has_other_pages %}
{% if datas.has_next %}
<a href="javascript:void(0)" class="btn btn-ghost btn-block mt-2"
id="load-more-btn">Load More</a>
{% else %}
<a href="javascript:void(0)" class="btn btn-ghost btn-block mt-2"
id="load-more-btn">All data has been displayed</a>
{% endif %}
{% endif %}
<script>
$("#load-more-btn").click(function(){
$.get("{% url 'account:profile' %}?param=get_data&page="+page,
function(data){
$("#display-data").append(data)
page++
})
})
</script>
I have try it but it's render all button
before click load more
after click load more
how to fix it ?

Firstly, don't place javascript in the data-ajax.html. All the javascript code should be placed in index.html, where all the logics need to be implemented. If there is not other data, data-ajax.html returned should be empty.
data-ajax.html
{% for data in datas %}
<div class="list-trx-data">
<div class="row align-items-center">
<div class="col-md-8">
<div class="row align-items-center">
<div class="col-md-4 col-sm-12 col-12 data-date">
{{data.get_formatted_date}}</div>
<div class="col-md-8 col-sm-12 col-12 data-name">
{{data.get_data}}</div>
</div>
</div>
<div class="col-md-4">
<div class="row align-items-center">
<div class="col-md-6 col-8 data-amount">
{{data.get_formatted_amount}}</div>
<div class="col-md-6 col-4 ">
<div class="data-progress">
<div class="pg-bar" style="width:
{{data.get_data.get_progress_str}}"></div>
</div>
</div>
</div>
</div>
</div>
</div>
{% endfor %}
{% if datas.has_other_pages %}
{% if datas.has_next %}
<a href="javascript:void(0)" class="btn btn-ghost btn-block mt-2"
id="load-more-btn">Load More</a>
{% endif %}
In your index.html, check if ajax call returned anything, if not, then change button text, else, remove the button element, since your data-ajax.html already has button based on {% if datas.has_other_pages %}.
index.html
<div class="panel-body">
<div id="display-data">
<span id="loading-help">Loading data. . .</span>
</div>
</div>
<script>
$(document).ready(function(){
var page = 1; //page defined in $(document).ready()
function getData(){
$.get("{% url 'account:profile' %}?param=get_data&page="+page, function(data){
$("#loading-help").remove();
if (data){
// data was received
$("#loading-help").remove();
$("#load-more-btn").remove(); # remove the load button if data is there.
$("#display-data").append(data);
page++;
} else {
$("#load-more-btn").text("All data has been displayed"); # else, change button text.
}
});
}
getData(); //Load data for the first time.
$("#load-more-btn").click(function(){
getData(); //Load data on button click.
});
</script>

Related

Foreach loop returns all results

I have a column of album covers. I want to take me to the album details after click on the cover. Actually it takes me to the album details but it shows all results, not only this one which was clicked.
AlbumDetailsController
public function index(): View
{
return View("details.index", [
'albums' => Album::paginate(1)
]);
}
AlbumDetails Blade view
#extends('layouts.app')
#section('content')
<div class="container">
#foreach ($albums as $album)
<h1 class="my-4">{{ $album->name }}</h1>
<div class="row">
<div class="col-lg-6 mb-4">
<div class="card h-100">
<div class="card-body">
<h4 class="card-title">
</h4>
{{ $album->artist }}
</div>
</div>
</div>
<div class="col-lg-6 mb-4">
<div class="card h-100">
<img src="{{asset('storage/' . $album->image_path)}}" alt="" class="img-fluid card-img-top">
<div class="card-body">
<h4 class="card-title">
{{ $album->artist }}
</h4>
{{ $album->description }}
</div>
</div>
</div>
</div>
#endforeach
#endsection
I've tried to solve this in differents ways but everything is not working. I think problem is with my controller but I'm really don't know how to modify it to show only this item which was clicked.

The POST method is not supported for this route. Supported methods: GET, HEAD."

How to pass the route in ajax in laravel without form?
I have a link or route without form.
<div class="row" id="markets">
#foreach($markets as $market)
<div class="col-lg-3">
<div class="card">
<img src="{{ asset('images/markets/'.$market->image) }}" class="card-img-top">
<div class="card-body">
<h5 class="card-title">{{ $market->title }}</h5>
<p class="card-text">{{ Str::words($market->body, 10) }}</p>
<p class="card-text">{{ $market->price }} $</p>
Add to cart
Continue
</div>
</div>
</div>
#endforeach
</div>
I want to do it with ajax.
<a role="button" class="card-text add-to-cart">Add to cart</a>
<script>
$(document).ready(function(){
$('.add-to-cart').on('click', function(event){
event.preventDefault();
var Route = $(this).attr('href');
$.ajax({
url: '{{ route("cart", $market->id) }}',
});
});
});
</script>
I see this error
My goal is to make this page.
try changing in web.php
Route::get('/cart/{market}',"MarketController#cart")->name('cart');
to
Route::match(['get', 'post'],'/cart/{market}',"MarketController#cart")->name('cart');
it seems you are using both get and post on same route if so then this may be it
EDIT:
try this
$('#markets').load('{{ route('cart') }} #markets')
What the above function does is it will load the cart route's market id and will replace the current route markets id
also i think it will be better to add
<div id="markets">
<div class="row">
#foreach($markets as $market)
<div class="col-lg-3">
<div class="card">
<img src="{{ asset('images/markets/'.$market->image) }}" class="card-img-top">
<div class="card-body">
<h5 class="card-title">{{ $market->title }}</h5>
<p class="card-text">{{ Str::words($market->body, 10) }}</p>
<p class="card-text">{{ $market->price }} $</p>
Add to cart
Continue
</div>
</div>
</div>
#endforeach
</div>
</div>
ie to create a div outside of the one you want to replace so the classes wont get mixed as for the for loop it will be only server sided so what you will load is loaded for-looped data

django AttributeError: 'str' object has no attribute 'field'

I am getting this error while submitting an ajax request using django.
The funny thing is if I execute these commands by hand when the debugger hits it works.
Here is the views.py
def lhr_search_custodians(request):
print request
print request.GET
print "blah"
# pdb.set_trace()
if request.method == 'GET':
search_text = request.GET.get('search_text')
else:
search_text = ''
custodians = Person.objects.filter(last_name__contains=search_text)
context = {'custodians': custodians}
return render(request, 'corpsec/legalholdrequests/create.html', context)
Here is the javascript query.js
$(function () {
$('#custodian_search').keyup(function (){
console.log("search fired!!!");
$.ajax({
url: "new/search_custodians",
type: "GET",
data: {
'search_text' : $('#custodian_search').val(),
'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val()
},
success : searchSuccess,
dataType: 'html',
error: function(xhr, errmsg, err) {
$('#results');
}
});
});
});
function searchSuccess(data, textStatus, jqXHR) {
$('$search_results').html(data);
}
this is the template create.html
{% extends "blackbox/show.html" %}
{% load static from staticfiles %}
{% load formtags %}
{% block title %}
New Legal Hold Request | {{ block.super }}
{% endblock title %}
{% block javascript %}
{{ block.super }}
{% endblock javascript %}
{% block show_header_title %}
<h4>
New Legal Hold Request
</h4>
{% endblock show_header_title %}
{% block tab_menu %}
<li class="tab">
<a id="id_modal_matter"
href="#matter">
Matter
</a>
</li>
<li class="tab">
<a id="id_modal_custodians"
href="#custodians">
Custodians
</a>
</li>
<li class="tab">
<a id="id_modal_electronic_databases"
href="#databases">
Electronic Databases
</a>
</li>
<li class="tab">
<a id="id_modal_collection"
href="#collection">
Collection
</a>
</li>
{% endblock tab_menu %}
{% block tab_content %}
<form action="/corpsec/legalholdrequests/new"
role="form"
method="post">
<span id="csrfmiddlewaretoken">{% csrf_token %}</span>
{% if form.errors %}
<div class="alert alert-dismissable alert-danger">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>Error.</strong> Please correct the following errors:
<small>{{ form.errors }}</small>
</div>
{% endif %}
<div class="row">
<div class="col s12">
<button id="id_form_submit"
type="submit"
class="btn right">
Submit
</button>
</div>
</div>
<div class="row">
<div id="matter" class="col s12">
<div class="row">
<div class="col s12 m8 offset-m2">
<div class="card">
<div class="card-content">
{{ form.matter_name|bsf_field }}<br/>
{{ form.matter_number|bsf_field }}<br/>
{{ form.matter_category|bsf_field }}<br/>
{{ form.priority_rating|bsf_field }}<br/>
{{ form.preservation|bsf_field }}<br/>
{{ form.issue_start|bsf_field }}<br/>
{{ form.issue_stop|bsf_field }}<br/>
{{ form.market_area|bsf_field }}<br/>
{{ form.attorney|bsf_field }}<br/>
{{ form.paralegal|bsf_field }}<br/>
{{ form.risk_manager|bsf_field }}<br/>
{{ form.category|bsf_field }}<br/>
</div>
</div>
</div>
</div>
</div>
<div id="custodians" class="col s12">
<div class="row">
<!-- search card -->
<div class="col s12 m3">
<div class="card">
<div class="card-content">
<span class='card-title'>Search Custodians</span>
<script src="{% static 'js/ldap-lookup.js' %}" type="text/javascript"></script>
<script src="{% static 'js/custodian_query.js' %}" type="text/javascript"></script>
{% csrf_token %}
<input type="text" id='custodian_search' name="search">
</div>
</div>
</div>
<!-- results section placeholder for now-->
<div class="col s12 m6">
<div class="card">
<div class="card-content">
<span class="card-title"> Results</span>
<ul id="search_results">
</ul>
</div>
</div>
</div>
<!-- action section -->
<div class="col s12 m3">
<div class="card">
<div class="card-content">
<span class="card-title">Action</span>
</div>
</div>
</div>
</div>
</div>
<div id="databases" class="col s12">
<div class="row" class='database_1'>
<div class="col s12 m8 offset-m2">
<div class="card">
<div class="card-content">
<div class="row">
{{ database_and_criteria_1.database|bsf_field }}<br/>
{{ database_and_criteria_1.criteria|bsf_field }}<br/>
</div>
</div>
<div class="card-action">
<button class='btn waves-effect waves-light' id='show_next_button' type="button" name="button">Add Database and Criteria</button>
</div>
</div>
</div>
</div>
<div class="row" id='database_2' style="display: none;">
<div class="col s12 m8 offset-m2">
<div class="card">
<div class="card-content">
<div class="row">
{{ database_and_criteria_2.database|bsf_field }}<br/>
{{ database_and_criteria_2.criteria|bsf_field }}<br/>
</div>
</div>
<div class="card-action">
<button class='btn waves-effect waves-light' id='show_next_button_2' type="button" name="button">Add Database and Criteria</button>
<button class='btn waves-effect waves-light red' id='remove_db_criteria_2' type="button" name="button">Remove</button>
</div>
</div>
</div>
</div>
<div class="row" id='database_3' style="display: none;">
<div class="col s12 m8 offset-m2">
<div class="card">
<div class="card-content">
<div class="row">
{{ database_and_criteria_3.database|bsf_field }}<br/>
{{ database_and_criteria_3.criteria|bsf_field }}<br/>
</div>
</div>
<div class="card-action">
<button class='btn waves-effect waves-light red' id='remove_db_criteria_3' type="button" name="button">Remove</button>
</div>
</div>
</div>
</div>
</div>
<div id="collection" class="col s12">
<div class="row">
<div class="col s12 m8 offset-m2">
<div class="card">
<div class="card-content">
<h4>Files<br/></h4>
{{ collection_form.email|bsf_field }}<br/>
{{ collection_form.netshare|bsf_field }}<br/>
{{ collection_form.computer_data|bsf_field }}<br/>
{{ collection_form.group_shares|bsf_field }}<br/>
{{ collection_form.pst_files|bsf_field }}<br/>
{{ collection_form.mobile_device|bsf_field }}<br/>
{{ collection_form.drive_cam_event_number|bsf_field }}<br/>
{{ collection_form.other_data_instructions|bsf_field }}<br/>
<h4>Processing</h4><br/>
{{ collection_form.processing_deadline|bsf_field }}<br/>
{{ collection_form.emails_attachments|bsf_field }}<br/>
{{ collection_form.everything|bsf_field }}<br/>
{{ collection_form.dedupe_matter|bsf_field }}<br/>
{{ collection_form.dedupe_custodian|bsf_field }}<br/>
{{ collection_form.keywords|bsf_field }}<br/>
{{ collection_form.archive_start|bsf_field }}<br/>
{{ collection_form.archive_stop|bsf_field }}<br/>
{{ collection_form.review_platform_external|bsf_field }}<br/>
{{ collection_form.delivery_instructions|bsf_field }}<br/>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
<script type="text/javascript">
$('#show_next_button').click(function() {
document.getElementById('database_2').style.display = 'block';
});
$('#show_next_button_2').click(function() {
document.getElementById('database_3').style.display = 'block';
});
$('#remove_db_criteria_2').click(function() {
document.getElementById('database_2').style.display = 'none';
});
$('#remove_db_criteria_3').click(function() {
document.getElementById('database_3').style.display = 'none';
});
</script>
{% endblock tab_content %}

AJAX Form won't update after being submitted

I have been toubleshooting an ajax request for a contact form. The form will load field errors with an ajax request, but it wont submit the form after the response. One thing to note is that I am trying to submit the form with a button outside the form tag, but even with one inside the tag it only submits once.
My ajax script:
$('#modal-form').submit(function(e) {
e.preventDefault();
var form = $(this);
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: form.serialize(),
success: function(data) {
if (!(data['success'])) {
// Here we replace the form, for the
form.replaceWith(data['form_html']);
$('#modal-form').off("submit");
}
else {
// Here you can show the user a success message or do whatever you need
$('#myModal').modal("hide");
}
},
error: function () {
$('#error-div').html("<strong>Error</strong>");
}
});
});
My form:
{% load crispy_forms_tags %}
<div class="container">
<!-- Modal -->
<div class="modal fade container-fluid" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4><span class="glyphicon glyphicon-envelope"></span> Email Me</h4>
<div id="success-div"></div>
</div>
<div class="modal-body">
<div class="row-fluid">
<div id="form">
<form id="modal-form" class="form-horizontal" method="POST" action="{% url 'emailme_success' %}">
{% csrf_token %}
{% crispy emailme_form emailme_form.helper %}
</form>
</div>
</div>
</div>
<div class="modal-footer">
<div id="error-div" class="pull-left"> </div>
<button name="submit" type="submit" class="btn btn-success pull-right" id="modal-submit" form="modal-form"><span class="glyphicon glyphicon-send"></span> Send</button>
</div>
</div>
</div>
</div>
</div>

Get template block contents and call from ajax

I'm using django 1.9 and python 3. My english also isn't the best, so excuse the question if it is formulated bad.
I'm working on making my website a single-page application. I need to get the {% block %} contents of a given template, and then send that as a HttpResponse so that ajax can pick it up and inject it into the page.
I've tried using the answer from this question: Django - how to get the contents of a {% block %} tag from a template
But upon trying to fetch the contents of a block in my view like so:
response_data[content] = get_block_source('profile/login.html', 'content')
if request.is_ajax():
return HttpResponse(
json.dumps(response_data),
content_type="application/json"
)
I just get this error from django, no matter what I do:
ValueError at /login/ Template block content not found
The contents of the block don't even make it to the ajax call, what gives?
EDIT:
I'll include my "content" block here:
in my template:
{% extends 'base.html' %}
{% block content %}
<div class="big-title text">Log in</div>
<div class="form-container">
<form name="login-form" id="user" method="post" action="/login/" enctype="multipart/form-data" class="text">
{% csrf_token %}
<div class="title">Enter your credentials</div>
<div class="form-row">
<div class="form-flex">
<div class="field-container">
<div class="field-input-container">
<div class="field-label accent">Username</div>
<div class="field-input">
<input class="field-input-element" type="text" name="username" />
</div>
</div>
<div class="field-help">Your username is always lowercase.</div>
</div>
</div>
<div class="form-flex">
<div class="field-container" style="height: 110px">
<div class="field-input-container">
<div class="field-label accent">Password</div>
<div class="field-input">
<input class="field-input-element" type="password" name="password" />
</div>
</div>
<div class="field-help"></div>
</div>
</div>
</div>
<div class="form-button-container">
<div class="form-error"></div>
<div class="form-message"></div>
<input type="submit" name="submit" value="Accept" class="button form-button"/>
</div>
</form>
</div>
{% endblock %}
In my base (base.html)
<body>
<div id="modal-container">
<div id="modal-overlay">
<div id="modal-items">
</div>
</div>
</div>
<div id="wrapper">
<header>
<div id="header-title" class="text accent">App name</div>
<div id="header-nav">
<nav>
{% if user.is_authenticated %}
Home
Feed {% if request.user.is_superuser %}
Admin {% endif %}
N
<a href="/{{ request.user }}" class="header-avatar-small-a">
<div class="text header-greeting">Hi, {{ user.userprofile.display_name }}</div>
<div class="header-avatar-small">
{% if not user.userprofile.avatar == '' %}
<img src="{{ MEDIA_URL }}users/{{ user }}/avatar" alt=""> {% else %}
<img src="{{ MEDIA_URL }}users/avatar" alt=""> {% endif %}
</div>
</a>
{% else %}
Log in
Create account {% endif %}
</nav>
</div>
<div class="progress">
<div id="header-progress" class="fill"></div>
</div>
</header>
<main>
{% block content %} {% endblock %}
</main>
<footer></footer>
</div>
</body>
</html>
Template source is the template actual HTML, not the file reference

Resources