ko_00
ko_00

Reputation: 118

On click (image/button) store data in ... to render another html template live

I would like to retrieve the img.id or img.alt data when an image is clicked in my (x.html) template. The retrieved data will then be used to fill another template (dashboard.html). My only question is how to retrieve the data on an 'onclick' event. Once i have the data stored somewhere, I will be able to figure out how to fill another template based on that information. And does your answer change if i would add that the 'dashboard.html' should be a live stat dashboard.

I already have the following working js that returns the id of the clicked image. How do I use that data in views.py for example?

function ImgDetails(img){
    var name = img.src;
    var id = img.id;
    console.log(id);
    }

Below the html (x.html) in which i would like to add a onclick function on each image that is imported via views.

{% include 'navigation.html' %}

    <div id="Content">
        <div id="List-Content">
            <!--- All_Test  -->
                {% for key, value_list in Drank.items %}
                        <div id ="Content-List">
                            <div id ="Title-Box">
                                <h1 class="hero_header">{{ key }}</h1>
                            </div>
                            {% for value in value_list %}
                                <div id ="Menu-Item">
                                    <div id ="Menu-Item-Wrap">
                                        <img style="margin: 0 auto;" id="{{ value }}" src="{{ value }}">
                                    </div>
                                </div>
                            {% endfor %}
                        </div>
                {% endfor %}
            </div>
        </div>
    </div>

</div>
</body>

{% include 'footer.html' %}

And here my views.py:

# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render
from django.template import loader
from django.db import models
from django.contrib.staticfiles.templatetags.staticfiles import static
import pandas as pd
import os
from os import walk
#C:\PythonProjects\DjangoApp\djangonautic
#C:/PythonProjects/DjangoApp/djangonautic

#Get dirs in imagefolder, files in dirs and create dictionairy for render
def smaakjes_list(request):
Temp_Directory_Path = []
#TempDic -> can later be replaced in the loop below, so that key                 values will be added as dir names
path_to_option_images =     '/Users/kolinmac/AnacondaProjects/DjangoApp/djangonautic/smaakjes/static/options/'
    #'/Users/kolinmac/AnacondaProjects/DjangoApp/djangonautic/smaakjes/static/options/'
super_dict = {}

#for each folder in options -> get all directory names
for (dirpath, dirnames, filenames) in walk(path_to_option_images):
    Temp_Directory_Path.extend(dirnames)
    print(Temp_Directory_Path)
    break


#for each directory in the list with directories
for dir_name in Temp_Directory_Path:
    #create path for file names - to iterate with walk()
    Temp_Path = path_to_option_images + dir_name
    #create title and dict - for later use
    Dict1 = {dir_name : []}
    super_dict_temp = {}
    TempList = []

    #for each image in path + dir_name
    for (dirpath, dirnames, filenames) in walk(Temp_Path):
        TempList.extend(filenames)
        break

    for values in TempList:
        #currently only .png allowed
        if values[-4:] == ".png":
            value = "/static/options/" + dir_name + "/" + values
            Dict1[dir_name].append(value)

    super_dict_temp = Dict1.copy()
    super_dict.update(super_dict_temp)


#print(super_dict)

return render(request, 'smaakjes/smaakjes.html', {'Drank': super_dict})

Upvotes: 1

Views: 621

Answers (2)

ko_00
ko_00

Reputation: 118

I found the solution in different posts. Also thanks to @Conan for pointing me in the right direction. The following json code worked for me:

function PostImageDetails(element) {
    var imageSrc = element.src;
    var imageId = element.id;
    console.log(imageSrc);
    console.log(imageId);

    //String manipulate ID
    imageId = imageId.split("/");
    imageId = imageId[4];
    imageId = imageId.split(".");
    imageId = imageId[0];
    imageId = imageId.replace(/[^a-zA-Z ]/g, "");

    console.log(imageId);
    //CREATE HTTP REQUEST
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("POST", "/api/users/", true);
    xmlhttp.setRequestHeader("X-CSRFTOKEN", getCookie('csrftoken')); //HTTP_X_CSRFTOKEN
    xmlhttp.setRequestHeader("Content-Type", "application/json");
    xmlhttp.send(JSON.stringify({'url':imageSrc, 'username': imageId}))

    //GET THE RESPONSE FROM THE SERVER
    xmlhttp.onload = function(){
        var csrftoken = getCookie('csrftoken');
        console.log(csrftoken);
        console.log(xmlhttp.status);
        console.log(xmlhttp.statusText);
        console.log(xmlhttp.responseText);
        console.log(xmlhttp);
    };
}
    //Create Cookie/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 = cookies[i].trim();
            // 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;
}

Upvotes: 0

Conan
Conan

Reputation: 319

To retrieve the data you will :
HTML:

<p id="malek" onclick="getAttribute(this)" >malek</p>

JS:

 function getAttribute(elem){
       //get an attribute value of the element
       idElement = elem.getAttribute('id');//src or howerver you want
    }
//then you should submit it with ajax request
var xmlhttp = new XMLHttpRequest();   // new HttpRequest instance 
xmlhttp.open("POST", "/YourRouteHere");//here you paste the route where u can receive data
xmlhttp.setRequestHeader("Content-Type", "application/json");
xmlhttp.send(JSON.stringify({src:idElement})); //And here ur data in Json Format

Upvotes: 1

Related Questions