Symfony 3 Infinite Scrolling Ajax - javascript

I'm trying to make an infinite Scrolling in Ajax.
I really don't know what is missing.
Html Index:
<div class="container">
<!-- Menu -->
{% include '::announce/menu.html.twig' %}
{% for announce in announces|slice(0, 4) %}
<!-- Announce Preview -->
{% include '::announce/' ~ game ~ '/preview.html.twig' %}
{% endfor %}
</div>
<div id="content"> loop content </div>
<nav id="pagination">
<p>Page 2</p>
</nav>
{% endblock %}
{% block javascripts %}
<script src="{{ asset('js/jquery-ias.min.js') }}"></script>
{% endblock %}
My controller index:
public function indexAction(Request $request, $game)
{
$em = $this->getDoctrine()->getManager();
$announces $em->getRepository('PlatformBundle:Announce')->byGame($game);
return $this->render('announce/index.html.twig', array(
'announces' => $announces,
'game' => $game
));
}
With this i have my index page with 4 announce
Now i show you my code for scrolling and adding more announce
Ajax File:
$(window).scroll(function () {
if($(window).scrollTop() + $(window).height()>= $(document).height()){
getmoredata();
}
})
function getmoredata() {
$.ajax({
type: "GET",
url: "{{ path('announce_page', {'id': '2', 'game': game}) }}",
dataType: "json",
cache: false,
success: function (response) {
$("#content").append(response.classifiedList);
$('#spinner').hide();
console.log(response);
},
error: function (response) {
console.log(response);
}
});
}
And this is the controller for page:
public function pageAction(Request $request, $game)
{
$em = $this->getDoctrine()->getManager();
$announces = $em->getRepository('PlatformBundle:Announce')->byGame($game);
$list = $this->renderView('announce/result.html.twig', array(
'announces' => $announces,
'game' => $game
));
$response = new JsonResponse();
$response->setData(array('classifiedList' => $list));
return $response;
}
Last code, it's the html content for ajax (result.html.twig)
{% for announce in announces|slice(4, 4) %}
<!-- Affichage Annonce -->
{% include '::announce/' ~ game ~ '/preview.html.twig' %}
{% endfor %}
For resume, i have my index with 4 announce, when i scroll in bottom, i have a positive ajax request without error. But nothing appear after the 4 announce.
If i go to announce page 2 directly with pagination, i can see 4 other announce. So my routing is working but something don't works in ajax code i think.
Any idea? :)
Thanks

Related

Django and Javascript - Like Button Not Working

I am new to Django and Javascript - I am making a project that has posts on a site, and I want to create a 'like' button on each post. So far here is my code - I am not getting any errors at all. No console errors in the browser either. But nothing happens. When you click the heart image, if it is liked, it should be a red image. When it is not liked, it is the white heart image. Currently when I click the image, it just stays white. It is always defaulting to that white image. The code doesn't work. Any help is appreciated.
views.py for the like button:
#csrf_exempt
def like(request):
if request.method == "POST":
post_id = request.POST.get('id')
is_liked = request.POST.get('is_liked')
try:
post = Post.objects.get(id=post_id)
if is_liked == 'no':
post.like.add(request.user)
is_liked = 'yes'
elif is_liked == 'yes':
post.like.remove(request.user)
is_liked = 'no'
post.save()
return JsonResponse({'like_count': post.like.count(), 'is_liked': is_liked,
"status": 201})
except:
return JsonResponse({'error': "Post not found", "status": 404})
return JsonResponse({}, status=400)
views.py for the page to show all the posts:
def index(request):
list_of_posts = Post.objects.all().order_by('id').reverse()
paginator = Paginator(list_of_posts, 10)
page_number = request.GET.get('page', 1)
page_obj = paginator.get_page(page_number)
return render(request, "network/index.html", {
"list_of_posts": list_of_posts,
"page_obj": page_obj
})
Javascript file:
like = document.querySelectorAll(".liked");
edit = document.querySelectorAll(".edit");
text_area = document.querySelectorAll(".textarea");
like.forEach((element) => {
like_handeler(element);
});
function like_handeler(element) {
element.addEventListener("click", () => {
id = element.getAttribute("data-id");
is_liked = element.getAttribute("data-is_liked");
icon = document.querySelector(`#post-like-${id}`);
count = document.querySelector(`#post-count-${id}`);
form = new FormData();
form.append("id", id);
form.append("is_liked", is_liked);
fetch("/like/", {
method: "POST",
body: form,
})
.then((res) => res.json())
.then((res) => {
if (res.status == 201) {
if (res.is_liked === "yes") {
icon.src = "https://img.icons8.com/plasticine/100/000000/like.png";
element.setAttribute("data-is_liked", "yes");
} else {
icon.src =
"https://img.icons8.com/carbon-copy/100/000000/like--v2.png";
element.setAttribute("data-is_liked", "no");
}
count.textContent = res.like_count;
}
})
.catch(function (res) {
alert("Network Error. Please Check your connection.");
});
});
}
html file for each post: index.html:
{% extends "network/layout.html" %}
{% load static %}
{% block body %}
<h3> Welcome. Here is your news feed: </h3>
{% for i in page_obj %}
<div class='card mb-3' style="max-width: 530px;" id="card-posts">
<div class="row no-gutters">
<div class="col-md-8">
<div class="card-body">
<h5 class="card-title"><a href="{% url 'profile' username=i.username
%}">{{i.username}}</a></h5>
<p class="card-text">{{i.text}}</p>
<div class="like mt-3">
<img
data-id="{{i.id}}"
id="post-like-{{i.id}}"
class="liked"
{% if not request.user in i.like.all %}
data-is_liked="no"
src="https://img.icons8.com/carbon-copy/100/000000/like--v2.png"
{%else%}
data-is_liked="yes"
src="https://img.icons8.com/plasticine/100/000000/like.png"
{%endif%}
/>
<span id="post-count-{{post.id}}">{{i.like.count}}</span>
</div>
</div>
</div>
</div>
</div>
{% endfor %}
{% block script %}
<script src="{% static 'network/network.js'%}"></script>
{% endblock %}
When I click the 'like' heart button on the page this is what I get. Each instance of 2, happens when I click it once. So this image is from clicking the heart button 3 times:

Anybody see the problem? #Bootoast script

Trying to get Bootoast to work on my website, where I try to pass a message. You can see the code below. Using Django-bootstrap for front-end.
BASE.HTML
<script srs="https://unpkg.com/bootoast#1.0.1/dist/bootoast.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/bootoast#1.0.1/dist/bootoast.min.css">
<script>
function toast(message, type) {
bootoast.toast({
position: 'bottom-center',
message,
type,
});
}
{% if messages %}
{% for message in messages %}
toast('{{ message }}', '{{ message.tags }}')
{% endfor %}
{% endif %}
</script>
VIEWS.PY
#login_required(login_url="/sign-in/?next=/customer/")
def profile_page(request):
user_form = forms.BasicUserForm(instance=request.user)
customer_form = forms.BasicCustomerForm(instance=request.user.customer)
if request.method == "POST":
user_form = forms.BasicUserForm(request.POST, instance=request.user)
customer_form = forms.BasicCustomerForm(request.POST, request.FILES, instance=request.user.customer)
if user_form.is_valid() and customer_form.is_valid():
user_form.save()
customer_form.save()
messages.success(request, 'Your profile has been updated')
return redirect(reverse('customer:profile'))
return render(request, 'customer/profile.html', {
"user_form": user_form,
"customer_form": customer_form
})
So the error I'm getting is this:
(index):197 Uncaught ReferenceError: bootoast is not defined
I'm blind or isn't this defined?
<script srs="https://unpkg.com/bootoast#1.0.1/dist/bootoast.min.js"></script>
Should have been
<script src="https://unpkg.com/bootoast#1.0.1/dist/bootoast.min.js"></script>

automatic refreshing <div> with django

I have a form that when it is posted the content of console.html gets changed. for refreshing the page I used the following code but this does not refresh console.html
javascript
function autorefresh() {
// auto refresh page after 1 second
setInterval('refreshPage()', 1000);
}
function refreshPage() {
var container = document.getElementById("console");
container.innerHTML= '<object type="text/html" data="../../templates/snippets/console.html" ></object>';
//this line is to watch the result in console , you can remove it later
console.log("Refreshed");
}
index.html
<script>autorefresh()</script>
<div id="console" >
{% include 'snippets/console.html' %}
</div>
view.py
def index(request):
if request.method == "GET":
return render(request, 'index.html')
if request.method == "POST": # If the form has been submitted...
form=InputForm(request)
form.do_function()
return render(request, 'index.html')
I rewrote html with the help of jquery:
<script type="text/javascript" src="{% static "js/jquery.js" %}"></script>
<script>
function autorefresh() {
// auto refresh page after 1 second
setInterval('refreshPage()', 1000);
}
function refreshPage() {
$.ajax({
url: '{% url 'console' %}',
success: function(data) {
$('#console').html(data);
}
});
}
</script>
.
.
.
<script>autorefresh()</script>
<div id="console" ></div>
view.py
def console(request):
data=
return render(request, 'snippets/console.html',{"data": data})
console.html
{% for line in data %}
{{ line }}
{% endfor %}
and finally add console to urls.
urls.py
urlpatterns = [
path('', views.index, name='index'),
path('console', views.console, name='console'),
]
I hope you don't spend a day finding the solution :))

Symfony 3/4 : delete a table row from a database through AJAX

I am a little bit stuck on my Symfony code.
Let me explain,
I have a todo-list table in my database containing :
An ID called : id
A name field called : todo
And 3 others fields that don't matter : "completed", "created_at", "updated_at".
Before going further : here is my codes,
The concerned Controller :
/**
* #Route("/todos/delete/{id}", name="todo.delete", methods={"POST"})
* #param Todo $todo
* #param ObjectManager $manager
* #param Request $request
* #return \Symfony\Component\HttpFoundation\RedirectResponse
*/
public function delete(Todo $todo, ObjectManager $manager, Request $request)
{
$manager->remove($todo);
$manager->flush();
if ( $request->isXmlHttpRequest()) {
return $this->redirectToRoute('todo.home', [
'id' => $todo->getId()
]);
}
throw $this->createNotFoundException('The todo couldn\'t be deleted');
}
The view :
{% extends 'base.html.twig' %}
{% block title %}Todos{% endblock %}
{% block content %}
<br>
<form action="{{ path('todo.create') }}" method="post">
<input type="hidden" name="token" value="{{ csrf_token('todo-create') }}"/>
<label for="todo">Todo</label>
<input type="text" id="todo" name="todo" class="form-control input-group-lg" placeholder="Create a new todo">
</form><br>
{% for todo in todos %}
{{ todo.todo }}
Update
x
{% if todo.completed %}
Completed !
{% else %}
Mark as completed
{% endif %}
<hr>
{% endfor %}
{% endblock %}
We focus on :
x
The JavaScript :
$(document).ready(function () {
$('.js-delete-todo').on('click', function (e) {
e.preventDefault();
var url = $(this).attr('href');
delTodo(url);
function delTodo(url) {
$.ajax({
type: "POST",
url: url
}).done(function (data) {
$('#id').remove();
}).fail(function () {
alert('Could not be deleted');
});
}
});
});
Actually,
Everything seems to work : it does a POST ajax request, and delete the row in my table in my database.
The only issue is that I have to hit F5 to see it.
How can I make it work without reloading the page nor hitting the F5 hotkey?
In your symfony code you should return JSON format like here.
Wrap your todo in container like this
{% for todo in todos %}
<div id="todo-{{todo.id}}">
// your todo staff here
</div>
{% endfor %}
Then change your javascript to
function delTodo(url) {
$.ajax({
type: "POST",
url: url
}).done(function (data) {
var id = JSON.parse(data).id;
$('#todo-' + id).remove();
}).fail(function ()
alert('Could not be deleted');
});
}

Cannot pass variable to JS script for PayPal Payments Rest API

The problem is that I cannot pass the paymentID variable that the PayPal script needs from PHP to JS. (Either this or the PHP script never runs).
I am following the steps here: https://developer.paypal.com/docs/integration/direct/express-checkout/integration-jsv4/advanced-integration/#set-up-the-payment
and I'm stuck on step 4.
I've used the code from this tutorial: http://paypal.github.io/PayPal-PHP-SDK/sample/doc/payments/CreatePaymentUsingPayPal.html
Here is the HTML:
{% extends 'layout/master.twig' %}
{% block title %} {{ parent() }}PayPal {% endblock title %}
{% block head %}
<script src="https://www.paypalobjects.com/api/checkout.js"></script>
{% endblock %}
{% block header %} Testing PayPal {% endblock header %}
{% block content %}
<div id="paypal-button"></div>
{% endblock content %}
{% block scripts %}
<script>
paypal.Button.render({
env: 'sandbox', // Optional: specify 'production' environment
payment: function(resolve, reject) {
var CREATE_PAYMENT_URL = 'http://patch-request.app/paypal/payment/create';
paypal.request.get(CREATE_PAYMENT_URL)
.then(function(data) {
alert(data);
console.log(data);
resolve(data.paymentID);
})
.catch(function(err) {
alert(data);
console.log(data);
reject(err);
});
},
onAuthorize: function(data) {
// Note: you can display a confirmation page before executing
var EXECUTE_PAYMENT_URL = 'http://patch-request.com/paypal/execute-payment';
paypal.request.post(EXECUTE_PAYMENT_URL,
{ paymentID: data.paymentID, payerID: data.payerID })
.then(function(data) { /* Go to a success page */ })
.catch(function(err) { /* Go to an error page */ });
}
}, '#paypal-button');
</script>
{% endblock scripts %}
And here is the script I'm trying to run:
public function create_payment ()
{
$payer = new Payer();
$payer->setPaymentMethod("paypal");
$item1 = new Item();
$item1->setName('Ground Coffee 40 oz')
->setCurrency('USD')
->setQuantity(1)
->setSku("123123")// Similar to `item_number` in Classic API
->setPrice(7.5);
$item2 = new Item();
$item2->setName('Granola bars')
->setCurrency('USD')
->setQuantity(5)
->setSku("321321")// Similar to `item_number` in Classic API
->setPrice(2);
$itemList = new ItemList();
$itemList->setItems([$item1, $item2]);
$details = new Details();
$details->setShipping(1.2)
->setTax(1.3)
->setSubtotal(17.50);
$amount = new Amount();
$amount->setCurrency("USD")
->setTotal(20)
->setDetails($details);
$transaction = new Transaction();
$transaction->setAmount($amount)
->setItemList($itemList)
->setDescription("Payment description")
->setInvoiceNumber(uniqid());
// $baseUrl = getBaseUrl();
$baseUrl = "http://patch-request.app";
$redirectUrls = new RedirectUrls();
$redirectUrls->setReturnUrl("$baseUrl/ExecutePayment.php?success=true")
->setCancelUrl("$baseUrl/ExecutePayment.php?success=false");
$payment = new Payment();
$payment->setIntent("sale")
->setPayer($payer)
->setRedirectUrls($redirectUrls)
->setTransactions([$transaction]);
$request = clone $payment;
try
{
$payment->create($this->apiContext); //$payment is a JSON
}
catch (Exception $ex)
{
echo 'Sth went wrong';
}
$approvalUrl = $payment->getApprovalLink();
return json_encode(['paymentID' => $payment->id]);
}
Any ideas?
I've got no idea what templating system you're using but you could try this
{% block head %}
<script src="https://www.paypalobjects.com/api/checkout.js"></script>
// add it here
<script>
window.paymentID = '<?= getPaymentID(); ?>'; // you need to implement this
</script>
{% endblock %}
Now you can access window.paymentID anywhere in you other JS

Categories

Resources