How to convert a django template variable into a javascript file - javascript

I created a django cart function. I need to create a javascript function. When I checkout from my page my cart should be empty when I post my checkout data has been saved but my boolean variable which is defined into a view function it not accessible into javascript code
**checkout.html **
<script>
if (localStorage.getItem('cart') == null) {
var cart = {};
} else {
cart = JSON.parse(localStorage.getItem('cart'));
};
$('#itemsJson').val(JSON.stringify(cart));
{% if thank %}
alert("Thanks for ordering with us. Your order id is {{id}}. Use it to track your order using our order tracker")
localStorage.clear();
document.location="/shop";
{%endif%}
</script>
there thank is a variable i need when form is submit my cart should be local storage.clear()
view.py
def checkout(request):
thank=False
if request.method=="POST":
items_json= request.POST.get('itemsJson', '')
name=request.POST.get('name', '')
email=request.POST.get('email', '')
address=request.POST.get('address1', '') + " " + request.POST.get('address2', '')
city=request.POST.get('city', '')
state=request.POST.get('state', '')
zip_code=request.POST.get('zip_code', '')
phone=request.POST.get('phone', '')
order = Order(items_json= items_json, name=name, email=email, address= address, city=city, state=state, zip_code=zip_code, phone=phone)
print(order)
order.save()
update=OrderUpdate(order_id=order.order_id,update_desc='Your Order Has Been Placed')
update.save()
thank=True
id=order.order_id
return render(request, 'myproj/checkout.html', {'thank':thank, 'id':id})
return render(request, 'myproj/checkout.html')

Related

Why is the colour not saved? If the data is saved correctly

I'm making it save the colour in localStorage to see a red heart if liked and no colour if disliked after refreshing the web page.
But I don't understand why it is not shown.
I have debugged and the localSotage values are correct.
Index.js
const color = ["#000000", "#FF0000"];
let colorIndex = parseInt(localStorage.getItem("colorIndex")) || 0;
console.log("Initial: " + colorIndex);
function like(elem) {
const postId = elem.attributes["data-id"].value
const csrftoken = getCookie('csrftoken');
fetch(`like/${postId}`, {
method: 'POST',
headers: { 'X-CSRFToken': csrftoken },
mode: 'same-origin'
}).then(res => res.json())
.then(data => {
document.getElementById(postId).innerText = data.numLikes
console.log(data.liked + ", color: " + color[data.numLikes - 1]);
if (data.liked == true) {
colorIndex = data.isLiked;
document.getElementById(`icon-${postId}`).setAttribute("fill", color[colorIndex]);
console.log("liked == true " + colorIndex);
} else if (data.liked == false) {
colorIndex = data.isLiked;
document.getElementById(`icon-${postId}`).setAttribute("fill", color[colorIndex]);
console.log("liked == false " + colorIndex);
}
localStorage.setItem("colorIndex", colorIndex);
})
}
views.py
if request.method == "POST":
postId = Post.objects.get(id = id) # Almacena los id de cada post
if not postId.likes.filter(id = request.user.id).exists(): # Si no existe un like por el usuario
newStatus = True
isLiked = 1
postId.likes.add(request.user) # AƱadelo
postId.save()
else:
newStatus = False
isLiked = 0
postId.likes.remove(request.user) # Si no lo quitas
postId.save()
return JsonResponse({"liked": newStatus, "isLiked": isLiked, "id": id, "numLikes": postId.likes.count()},status=200)
return JsonResponse({"message": "Wrong method"}, status=400)
You might have a syntax problem with your attribute setting.
Try:
setAttribute("style", "fill:" + color[colorIndex])
Bear in mind this may override any other style properties you don't include, so you can avoid that by settting fill directly:
document.getElementById(`icon-${postId}`).style.fill = color[colorIndex]
The other thing that might be causing you trouble is the fill is only being set in the like() function, presumably responding to clicking a like button of some sort. If the page is reloaded, there is nothing in the code shown that will test to see if the post has been liked - the colour set in the like() function won't persist after a page reload as it hasn't been called.
The best way to handle this is in the django template itself, seeing as you are storing the 'liked' data in the database. First, in your view, get a list of liked posts
In this example, 'likes' is a recordset passed to your template from your view - I'm assuming Likes is a ManyToMany field linking users to posts:
user_likes = Likes.objects.filter(id = request.user.id)
You can make the filter more specific for efficiency based on the page's requirements. Pass the result of this filter to the template via context.
When you come to display the post do something like:
<div class="post">
...
<img id="icon-{{post.id}}" class="
{% if post in user_likes %}
liked
{% else %}
notliked
{% endif %}
">
</div>
And have your classes defined in your CSS to include your fill values eg,
.liked {
fill:#FF0000
}
.notliked {
fill:#000000
}
This will handle your coloring without having to make any ajax type javascript calls

Data being duplicated when the update function is triggered - Firebase

I'm making a web app and trying to update data on Firebase. But when the update function is being triggered, data is being duplicated on the database. I want data to be updated only inside voter/voterId. I don't want the same data to be duplicated inside voter/. Here's my code:
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
var voterid, name, nic, mobile;
function Ready(){
voterid = document.getElementById("voterid").value;
name = document.getElementById("name").value;
nic = document.getElementById("nic").value;
mobile = document.getElementById("mobile").value;
}
document.getElementById("register").onclick = function(){
Ready();
if (voterid != null){
firebase.database().ref('voter/'+voterid).update({
name : name,
nic : nic,
mobile :mobile
});
}
}
It looks like voterid is an empty string, which you don't check for.
if (voterid != null && voterid.length > 0){
firebase.database().ref('voter/'+voterid).update({
name : name,
nic : nic,
mobile :mobile
});
}

Retrieve response informaton in view

I'm using ASP.NET Controller accessing account data to another database. I'm doing a login where it gets an ID and checks if it's a Mentor or Student.
With this information we want it to be used in a .js file we have thats makes a get request to our server. We want to send an ID here and later other informations.
We have this controller:
public IActionResult Calendar(LoginViewModel loginViewModel)
{
Student student = null;
Mentor mentor = null;
if (loginViewModel.UserType == 0)
{
student = db.GetStudentObject(loginViewModel.Id);
}
else if (loginViewModel.UserType == 1)
{
mentor = db.GetMentorObject(loginViewModel.Id);
}
if (student != null)
{
return View(student.Id);
}if(mentor != null)
{
return View(mentor.Id);
}
return View("Index");
}
When our view is initialized we want to send an ajax request where we use the Id we sent to the view
eventSources: [
{
url: '/api/Bookings?id=' + id, //we need to access the Id here
color: 'blue',
textColor: 'white'
}
],
How can we retrieve the Id from the controller we are sending to the view? I know this can be solved by making a static class however is there a better options?
//Accessing the Id on JS file:
'/api/Bookings?id=' + $('#Id').val();
#*
if the view is binding to a complex model, you must return View(model), instead of View(model.Id) on controller.
assuming that is a complex model, you have in your view (cshtml):
*#
#model Xpto.Models.MyViewModel
#Html.HiddenFor(i => i.ID) //to access the property on JS file.

Using Django and Jquery

In addition to this post https://stackoverflow.com/a/17732956 I want to change the order of a list via drag'n'drop and save it afterwards in django backend.
For test purposes and comprehension I've used following fiddle:
http://jsfiddle.net/LvA2z/#&togetherjs=LvHpjIr7L0
and updated the action of the form with my own action. So, instead of script.php, I used action="{% url 'save_order' %}".
In views my function looks like:
def save_order(request):
if (request.method == 'POST'):
list = request.POST['listCSV']
print(list)
Basically I want to change the order of list elements and save it afterwards with the result that after refreshing the page the saved order is given. However I do not know, how pass vars from jquery to django site. When I change the order, I have the sorted list in 'listCSV'. How do I pass this result to django site to save it in db?
EDIT:
If //$("#listsaveform").submit(); is not commented out and I fire this function referenced with my save_order function, I got this error:
jquery-1.10.2.min.js:6 POST http://localhost:8000/overview/saveOrder/ 405 (Method Not Allowed)
EDIT:
Okay, thanks for the hint. I have never worked with ajax and therefore I'm stucking a bit.
I have my list construct:
{% if habits %}
<ul id="sortable">
{% for habit in habits|dictsort:"priority" %}
<li class="ui-state-default">{{habit.title}}</li>
{% endfor %}
</ul>
{% endif %}
and this list construct is sortable with this lines of code:
$(function() {
$( "#sortable" ).sortable();
});
How does look my form?
Here is my solution based on https://impythonist.wordpress.com/2015/06/16/django-with-ajax-a-modern-client-server-communication-practise/.
In JS
// Sort & save order of habits
$(function () {
$('.sort').sortable({
handle: 'button',
cancel: '',
update: function(event, ui) {
var result = $(this).sortable( "serialize", {key: event.target.id});
// alert(result);
var csrftoken = getCookie('csrftoken');
$.ajax({
url : "/overview/saveOrder/", // the endpoint,commonly same url
type : "POST", // http method
data : { csrfmiddlewaretoken : csrftoken,
result : result,
}, // data sent with the post request
// handle a successful response
success : function(json) {
console.log(json); // another sanity check
//On success show the data posted to server as a message
// alert('Your list '+json['result']);
},
// handle a non-successful response
error : function(xhr,errmsg,err) {
console.log("FAILURE");
console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
}
});
}
});
// var sorted = $( ".selector" ).sortable( "serialize", { key: "sort" } );
// console.log(sorted)
})
//For getting CSRF token
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
and on Django side
def save_habit(request):
print('save_habit')
if (request.method == 'POST'):
if request.is_ajax():
habits = Habit.objects.filter(created_by=request.user.userprofile, is_active=True)
habit_title = request.POST.get('habit_title')
habit_trigger = request.POST.get('habit_trigger')
habit_routine = request.POST.get('habit_routine')
habit_targetbehavior = request.POST.get('habit_targetbehavior')
habit_image = request.POST.get('habit_image')
print(habit_image)
image = habit_image.split('http://localhost:8000/media')
print(image[1])
# TODO: was, wenn routine noch gar nicht existiert? --> speichern
obj_routine = Existingroutine.objects.get(name=habit_routine)
obj_targetbehavior = Targetbehavior.objects.get(name=habit_targetbehavior)
for habit in habits:
habit.priority += 1;
# habit.save();
habit = Habit(created_by=request.user.userprofile, is_active=True,
title=habit_title, trigger=habit_trigger, existingroutine=obj_routine,
targetbehavior=obj_targetbehavior, image=image[1])
#habit.save()
data = {"habit_title":habit_title,
"habit_trigger":habit_trigger,
"habit_routine":habit_routine,
"habit_targetbehavior":habit_targetbehavior };
return JsonResponse(data)
return redirect('display_habits')

Ajax dependent text field and dropdown menu (Php and Javascript)

I'm a student and still new with Javascript and php, i need to make a login page for my website that can check user input in the database using ajax.
Example: When the user enter their username and password into the field given,the system will automatically check in database either the user exist or not and return the data needed such as user responsibilty from the response table to the dropdown menu below, then they can login into the system.
Below is my basic coding:
Config.php:
e$host = "localhost";
$User = "root"
$Pass = "passw";
$db = "skm_spm";
Login.php:
<?
require ("config.php");
$conn=mysqli_connect($host,$user,$pass,$db);
$duser="select * from tab_user where user_name = '".$_POST["Lname"]."'";
$uresult=myqli_query($conn,$duser);
if(!$uresult)
die("Invalid query: ".mysqli_error());
else
if(mysqli_num_rows($uresult)== 0){
echo "User does not exist";
}
else
{
$row=mysqli_fetch_array($result,MYSQL_BOTH);
if($row["User_Password"] == $_POST["Lpass"])
{
$dresp="select resp_id,resp_name from tab_resp";
$result2 = mysqli_query($conn,$dresp);
}
else
{
}
}
?>
<html>
<b>Login</b><br>
Name : <input type = "text" name="Lname" id="Lname" placeholder="Username"/><br>
Password: <input type = "password" name="Lpass" id="Lpass" placeholder="password"/><br><br>
<div class = "optresp">
<select name="sresp" id="sresp">
<option>--Responsibility--</option>
<?
while (mysqli_fetch_array($result2)){
echo "<option value='$row[1]'>$row[1]</option>";
?>
</select>
</div>
</html>
I have learn on internet and try to code with my understanding,but still failed. I need a php ajax coding that can work with code above.
Thank you.
I will provide you with some code from my recent project and hopefully you will be able to understand it and adapt it to your needs.
Firstly, you should have the login form in a separate file to the PHP login code. Then have button on the page or an enter events that run a Javascript function, in my case Login(). In this Javascript function the text within the input fields are saved to two variables and some basic checks are done on them to ensure that they have been filled in. Next, the PHP login function file (it has no visible content in just processes some data in PHP) using the $.post line. This also passed the two input variables (under the same name) to the PHP file. You can also see that depending on what is returned/echoed from the PHP file as "data" several possible outcomes may occur (Login Success, Account Banned or Invalid Login). I personally call these outcomes error messages or success messages, for example error message 6 for incorrect password/username.
//FUNCTIONS
function Login(){
var StrUsername = $("#txtUsername" ).val();
var StrPassword = $("#txtPassword").val();
if (StrUsername == "" && StrPassword == ""){
$('#pError').text('Enter your Username and Password!');
}
else if(StrUsername == ""){
$('#pError').text('Enter your Username!');
}
else if(StrPassword == ""){
$('#pError').text('Enter your Password!');
}
else{
$.post('https://thomas-smyth.co.uk/functions/php/fnclogin.php', {StrUsername: StrUsername, StrPassword: StrPassword}, function(data) {
if (data == 0){
window.location.href = "https://thomas-smyth.co.uk/home";
}
else if (data == 1){
window.location.href = "https://thomas-smyth.co.uk/banned";
}
else if (data == 6){
$('#pError').text('Username & Password combination does not exist!');
}
});
}
}
Next the PHP function file. Firstly, the variables passed by the Javascript are collected using $_POST. My SQL class is then pulled into the file, this does all my SQL DB connections. I then have my SQL statement that will search to see if the account exists. Notice the ? in it. This prevents SQL injections as the variables is bound into the statement through the SQL server meaning it won't allow people to put SQL code within my input fields to break my database. I then check whether the account exists, if it doesn't I save data to 6, which will cause the error message 6 in the Javascript to run when data is returned. I have a field in my database that contains a rank. If the login is correct then I create a SESSION variable to store their username and rank in. This is later used on pages to check whether they are logged in before displaying a page (this speeds up navigation as it means that the DB doesn't need to be searched everytime the user switches page, however does bring some issues like if you ban a user while they are logged in they will stay logged in until their session dies). You could use this on your dropdown menu to ensure the user is logged in and/or get their username. Finally, I return 0 or 1, so that the Javascript then re-directs them to the correct page.
<?php
//Retrieves variables from Javascript.
$StrUsername = $_POST["StrUsername"];
$StrPassword = $_POST["StrPassword"];
require "sqlclass.php";
$TF = new TF_Core ();
$StrQuery = "
SELECT Username, Rank FROM tblUsers
WHERE Username = ? AND Password = ?";
if ($statement = TF_Core::$MySQLi->DB->prepare($StrQuery)) {
$statement->bind_param('ss',$StrUsername,$StrPassword);
$statement->execute ();
$results = $statement->get_result ();
if($results->num_rows == 0){
$data = 6;
}
else {
while ($row = $results->fetch_assoc()) {
//Other groups
if ($row["Rank"] == "Developer" || $row["Rank"] == "Staff" || $row["Rank"] == "Cadet"){
session_start();
$_SESSION["LoginDetails"] = array($StrUsername, $row["Rank"]);
$data = 0;
}
//Banned
else if ($row["Rank"] == "Banned"){
session_start();
$_SESSION["LoginDetails"] = array($StrUsername, "Banned");
$data = 1;
}
}
}
}
echo $data;
?>
Hopefully this helps you. Please say if you need more help!
You need to make ajax call on blur of username to check if user exists in database and on success of that you can make one more ajax to check for password match of that particular user. This will give you both cases whether a user exixts or not if exixts then does the password match or not only after that user will be logged in and then you can show the responsibilities of that particular user.
For username:
$('#Lname').blur(function(){
$.ajax({
url:'url where query for matching username from database',
data:'username collected from input on blur',
type:'POST',
success:function(data){
//Code to execute do on successful of ajax
}
})
})
For Password:
The ajax call remains the same only url, data and response changes

Categories

Resources