pari palepu
pari palepu

Reputation: 29

How to pass the javascript variable value from one html page to the another html page?

I am creating the quiz application using JavaScript and Django. Actually entire logic was done in the JavaScript . For the quiz application ,I have a score variable that score variable value i am showing in the index.html as show below:

          resultCont.innerHTML = 'Your Score:- ' + score + '/80' ;

Here score is the JavaScript variable.

Another thing I need to store this score variable into my DB . So that I need to use the ajax to post the score variable to my views.py file where my function is running to submit the score along with username to the Django models.

models.py:

class Results(models.Model):
    username = models.CharField(max_length=50,default='')
    score = models.IntegerField()

    def __str__(self):
        return self.username

Here I have taken the username and score variable . And the username is the foreign key.

views.py

def score(request):
    if request.method == 'GET':
        return render(request, 'quiz/html/end.html',{'form':Score()})
    else:
        try:
            form = Score(data=request.POST)
            newscore = form.save(commit=False)
            newscore.owner = request.user
            newscore.save()
            return redirect('category')
        except ValueError:
            return render(request, 'quiz/html/end.html',{'form':Score(), 'error' :'please fill the form properly'})

end.html: Here I have used the form to submit the score along with name . I hidden the username so that user cannot change the name.

<form method="POST">
        {% csrf_token %}

        <div>
            <p style="display:none;">
                <label for="id_username">Username:</label>
                <input type="text" name="username" value={{user.username}} placeholder="{{user.username}}" maxlength="50" required="" id="id_username">
            </p>

            <p>
                <label for="id_score">Score:</label>
                <input type="number" name="score" placeholder ='' value='I want the score value here from javascsript' required="" id="id_score">         
            </p>
        </div>
        <button type="submit">Submit</button>

    </form>

I wrote the ajax post request but i tried of showing score in the same index.html. It is displaying but i want that score value in the end.html. Is it possible to show the score of index.html(score storing in the #result) into the end.html (where the score need to store )

function scoresubmit(){
          $.ajax({
            url: '/',
            method : 'POST',
            // data: {score: $('#score').val(), "csrfmiddlewaretoken" : "{{csrf_token}}"},
            success: function() {
              $('#name').html(score);
            }
             });
            }

index.html: (from here)

resultCont.innerHTML = 'Your Score:- ' + score + '/80' ;

end.html:(to Here)

 <input type="number" name="score" placeholder ='' value='I want the score value here from javascsript' required="" id="id_score">         

urls.py:

path('home', views.home,name = "home"),
    path('main',views.main, name='main'),
    path('', views.score, name = "score"),
    path('profile/',views.profile, name = "profile"),
    path('category/',views.category, name = "category"),

Only thing I want here is store the score along with the user name in my DB (Django).

What is the wrong in my ajax code . How to pass the value from one to another html using ajax post request?

Upvotes: 0

Views: 144

Answers (2)

ms394
ms394

Reputation: 109

Hey below is the code i tried. I created a form in index.html. Took dummy input, marks and performed some operation on it and sent variable score to the end.html and also stored it in the db. Since i was working with JS ajax, i used djano-rest framwork for the same. Below is the code

models.py

from django.db import models
from django.contrib.auth.models import User


# Create your models here.
class Results(models.Model):
    user = models.ForeignKey(User, default=None, on_delete=models.CASCADE)
    score = models.IntegerField()
    marks = models.IntegerField()

index.html

body>
    <form id="scoreform" method="POST">
        {% csrf_token %}
        <p class="marks">
            <label for="marks">Marks</label>
            <input type="number" name='marks' id="id_marks">
        </p>

        <input type="submit"  id="submit" value="Submit">
    </form>
</body>

<script src="{% static 'main.js' %}"></script>

end.html

<body>
    <form id="scoreform" method="POST">
        {% csrf_token %}
        <p class="username">
            <label for="username">Label</label>
            <input type="text" name="username" value={{score.user}}>
        </p>
        <p class="scores">
            <label for="score">Score</label>
            <input type="number" name='score' id="score-value" value={{score.score}}>
        </p>

    </form>
</body>

views.py

from django.shortcuts import render, redirect
from .models import Results
from .forms import Score
from django.contrib.auth.decorators import login_required
from rest_framework.decorators import api_view
from rest_framework.response import Response
from .serializers import ResultSerializer

# Create your views here.
@api_view(['GET','POST'])
@login_required(login_url='users:login')
def score(request):
    form = Score()
    print(1)
    if request.method == 'POST':
        serializer = ResultSerializer(data=request.data)
        print(serializer)
        if (serializer.is_valid()):
            print(3)
            serializer.save(user = request.user)
            return Response(request.user.pk)
    return render(request, 'index.html', {'form': form})
    #return redirect('score:end', pk=request.user.pk)   

@login_required(login_url='users:login')
def end(request, pk):
    score = Results.objects.get(pk=pk)
    return render(request, 'end.html', {'score':score})

This also has login feature, as i wanted to tag a user to the score. I dunno who clear this would be for you. But i seriously hope this helps

Upvotes: 1

ms394
ms394

Reputation: 109

Can you try this
In the views.py file if the method is GET, then create an instance of the Result Model like result = Result.objects.get(pk = pk) the pk refers to primary key to get the result of a particular user, and pass in some unique identified to your views method like pk. Then use template tag to display in the end.html

Upvotes: 0

Related Questions