Passing variable from javascript to django views - javascript

I am creating simple "rock paper scissors" game with some css animations and so on, where most of the stuff happens in javascript, as learning JS is what I am focusing on mostly at the moment.
User vs computer match also happens in javascript. When match is finished I am assigning users earned exp(points) to new variable.
What I am trying to do now is sending that data (earned exp) to the views, so I can save it back in a database (users.exp).
I think jQuery ajax or fetch api should do that if I am right but after hours of trying I probably just don't get it.
Any1 can give me some tips, explanation? Not just solution please.
Views:
#login_required
def profile(request):
if request.user.is_authenticated:
user = request.user
userObj = Profile.objects.filter(user=user)
usersLevel = userObj[0].level
usersPoints = userObj[0].points
context = {
'usersLevel': usersLevel,
'usersPoints': usersPoints,
}
return render(request, 'rps_app/game.html', context)
else:
print('No user logged in!')
return render(request, 'rps_app/game.html')
This is my template where Iam loading users data:
<script type="text/javascript">
var usersLevel = '{{usersLevel|safe}}';
var usersPoints = '{{usersPoints|safe}}';
</script>
js:
let users_level = Number(usersLevel);
let users_points = Number(usersPoints);
progressbar.style.width = `${users_points}%`;
...
javascript:
$(document).ready(function(){
$('#btn-ajax').click(function(){
$.ajax({
url: 'http://127.0.0.1:8000/game',
csrfmiddlewaretoken: "{{ csrf_token }}",
type: 'get',
success: function(data) {
console.log(data);
alert(data);
},
failure: function(data) {
alert('Your code is crap mate');
}
});
});
})
************ . E D I T E D . ***********
Thats what I got now:
js:
$(document).ready(function(){
$('#btn-ajax').click(function(){
$.ajax({
url: 'http://127.0.0.1:8000/test/earned_exp=100/',
csrfmiddlewaretoken: "{{ csrf_token }}",
success: function(data) {
alert('succes');
},
failure: function(data) {
alert('Your code is crap mate');
}}); });})
views:
def pass_variable(request, earned_exp=None):
some_variable = request.GET.get('earned_exp')
console.log(some_variable)
return HttpResponse('<h1>ok.{}</h1>'.format(earned_exp))
url:
path('test/<earned_exp>/', user_views.pass_variable, name='pass_variable'),

You can pass variables as URL parameters and get them through the request object.
$.ajax({
url: 'mycoolwebsite.com/path/?earned_xp=100'
success: function(e){
alert("success");
},
error: function(e){
alert("error")
}
});
class MyView(View):
def get(self, request):
xp = request.GET.get("earned_xp")
# do whatever you want with the XP now.
In case you want to send multiple URL parameters, you can seperate them by & here's an example url
https://example.com/?hello=world&goodbye=coding

Related

render_template is not redirecting to another page in Flask

I am currently working on the below flask code. I'm trying to redirect to another HTML page using render_template but it's not working. However, I have tried to send back the JSON response to the AJAX at the client-side and by using the AJAX success response at the Client JavaScript code and by using the window.location.href functionality I am giving the URL of that HTML it's working.
But I need to use the render_template to redirect to another URL which actually fulfills my requirement. Please help me out.
function myFunction() {
$.ajax({
url: '/ValidateOTP',
type: 'POST',
data: JSON.stringify($('#OTP').val()),
contentType: 'application/json;charset=UTF-8',
success: function(response) {
jsonvariable = response['success'].toString();
if (jsonvariable == 'true')
window.location.href = 'http://localhost:63342/ElectricMan/templates/electricprofwelcomepage.html';
else if (jsonvariable == 'false')
document.getElementById("div2").innerHTML = "OTP didn't match !! Please click the GET OTP button to re-generate OTP";
document.getElementById("div2").style.color = "Red";
},
error: function(response) {
alert(response)
}
});
};
#app.route('/ValidateOTP', methods=['GET','POST'])
def ValidateOTP():
OTP = request.get_json()
otpinstant=session['OTPINSTA']
if otpinstant==OTP:
Session = sessionmaker(bind=engine)
s = Session()
query = s.query(ElectricMan).filter_by(email_id=email).first()
result=query.first_name
if result:
session['logged_in'] = True
#return render_template('electricprofwelcomepage.html')
resp = jsonify(success=True)
return resp
else:
resp = jsonify(success=False)
return resp

How to upload a canvas image from javascript to Django

I am trying to send this toDataURL image to the server through AJAX. Unfortunately, every time it sends - no matter how I finagle it - I can only get either a 403 Forbidden error, a javascript error, or - at best - an empty dictionary item, while the other fields are accurate. Any ideas?
javascript
function SaveImage(n){
var imageFile = document.getElementById("img-file"+n);
// Set that you want to download the image when link is clicked
imageFile.setAttribute('download', 'image.png');
// Reference the image in canvas for download
imageFile.setAttribute('href', canvas.toDataURL());
addMeme(imageFile);
}
function addMeme(n){
var f= n;
var patch = '{% url "testing" %}';
var post_data = {
'csrfmiddlewaretoken':"{{ csrf_token }}",
imageBase64:f,
g: 'jjj',
};
$.ajax({
type: "POST",
url: patch,
data:post_data,
dataType: 'json',
success: function(data){
}
});}
views.py
def testing(request):
if request.method == 'POST':
response_json = request.POST
response_json = json.dumps(response_json)
data = json.loads(response_json)
print(data['imageBase64'])
return JsonResponse(data, safe=False)

AJAX post method working in one area but not another

I have an AJAX post method that works in two places both on "Ladder" page, but not another, a "matches" page. This method sets posts the "player ID" which php picks up and sets a session variable
$("form .singles-player-name").click(function (evt) {
evt.preventDefault();
var viewPlayer = $(this).val();
console.log(viewPlayer);
$.ajax({
url: '',
type: 'POST',
data: {
viewPlayerID: viewPlayer
}
}).done(function (data) {
console.log("Success");
//console.log(data);
window.location.href = "Player";
});
});
Working page form:
<form><button type='submit' id='playerInfo' class='singles-player-name' name='viewPlayer' value='",$sglsPlayerID,"'>", $curSGLSRankLName, ", ", $curSGLSRankFName, "</button></form>
Sets session variable
if (!empty($_POST['viewPlayerID'])){
$viewPlayer = isset($_POST['viewPlayerID']) ? $_POST['viewPlayerID'] : 'No data found';
$viewPlayerSql = "SELECT * FROM `PLAYERS` WHERE `ID` LIKE '".$viewPlayer."'";
$viewPlayerQuery = #$conn->query($viewPlayerSql);
$viewPlayerRow=mysqli_fetch_assoc($viewPlayerQuery);
$_SESSION['playerID'] = $viewPlayerRow["ID"];
echo "", $_SESSION['playerID'],"";}
Second working version that lives on the same page as the first but is for doubles players:
$("form .doubles-player-name").click(function (evt) {
evt.preventDefault();
var viewPlayer = $(this).val();
console.log(viewPlayer);
$.ajax({
url: '',
type: 'POST',
data: {
viewPlayerID: viewPlayer
}
}).done(function (data) {
console.log("Success");
//console.log(data);
window.location.href = "Player";
});
});
Form for that ajax method:
<form><button type='submit' id='playerInfo' class='doubles-player-name' name='viewPlayer' value='",$dblsPlayerID,"'>", $curDBLSRankLName, ", ", $curDBLSRankFName, "</button></form>
Then on complete, the ajax methods redirect to the player page and pulls up that players info on that page (ex. https://urlexample.com/Player). This part, from this point-up, works! However, I have another page, the "Matches" page, where I want it to do the same exact thing, and set that session variable, then redirect to the player page, so I have this method below. But for some reason, this one does not work:
$("form .singlesMatch-player1-name").click(function (evt) {
evt.preventDefault();
var viewPlayer = $(this).val();
console.log(viewPlayer);
$.ajax({
url: '',
type: 'POST',
data: {
viewPlayerID: viewPlayer
}
}).done(function (data) {
console.log("Success");
console.log(data);
window.location.href = "Player";
});
});
Not working form:
<form><button type='submit' id='playerInfo' class='singlesMatch-player1-name' name='viewPlayer' value='",$sglsPlayer1ID,"'>", $P1LN, ", ", $P1FN, "</button></form>
For some reason, all this second method does is post it to the URL (ex. https://urlexample.com/WeeklyMatchUps?viewPlayer=1) instead of setting the session variable and redirecting to the player page (ex. https://urlexample.com/Player). All thats different between the 2 is the class name of the button.
$sglsPlayer1ID should probably be $sglsPlayerID.
Also, try adding a success and error condition to your AJAX conditions instead of just using a done operator. This will allow you to dump helpful error codes on a failure to better resolve these kinds of issues in the future.
I had a function being called on the page that was commented out causing an error before jQuery was added in a script at the bottom of the page. removing that function from being called fixed the issue.
S/O to #line88 for the assistance!

laravel, ajax call from input to controller function 500 error

I'm not sure what's happening with this but when my ajax call is made to my php controller method, I'm getting a 500 error and I'm wondering if it's possibly a data type error or just simply syntax.
The value I'm passing from my form input through tha ajax call and into my function is being passed into a url endpoint in my service.php file.
The ajax itself is calling the function successfully but I can't verify the results from my $searchResults in the function because it seems to fail at the point of passing.
I started typing Test into my input with a breakpoint in the browser and it showed the value for my input as "T". Should I need to strip quotes or anything like that if it's being used in the query of the endpoint?
What else does it look like I could be doing wrong here?a
service.php
public function getSearch($query)
{
return $this->get("/search/search?query={$query}" );
}
I also set a new route for the controller and function
Route::post('autocomplete','Controller#autoComplete');
controller.php
public function autoComplete(Request $request)
{
$search_result = $request->search_result;
$service = new service();
//$search_result = "test"; /*this hard coded value works for passing*/
$searchResults = $service->getSearch($search_result);
return $searchResults;
}
view.blade.php
$('#productInput').on('input', function(){
if($(this).val() === ''){
return;
}else{
const searchResult = $(this).val();
$.ajax({ url: '/account/autocomplete',
data: {
'search_result':searchResult
},
type: 'POST',
success: function(response){
console.log(response);
}
});
}
});
Add this to your head
<meta name="csrf-token" content="{{ csrf_token() }}">
and pass the token to ajax:
$('#productInput').on('input', function(){
if($(this).val() === ''){
return;
}else{
const searchResult = $(this).val();
$.ajax({ url: '/account/autocomplete',
data: {
'search_result':searchResult
},
"_token": "{{ csrf_token() }}", // **** THIS LINE IS ADDED ***** //
type: 'POST',
success: function(response){
console.log(response);
}
});
}
});
I take the ajax part from this answer, so thanks to Deepak saini. If this answer solved your problem, give his answer a plus.

Passing data to the create method in rails with ajax

I'm pretty new to ruby on rails . I need to pass data from the view to create method in controller.
*view*
function setDeliveryDetails () {
var all_del_rate= $('#all_dr').val();
var all_del_period= $('#all_dp').val();
var array=[all_del_rate,all_del_period]
$.ajax({
type:"GET",
url:"save_delivary_details" ,
dataType:"json",
data: {deliveries: array},
success:function(result){
// alert(result);
},
error: function() {
}
});
}
*Controller*
def save_delivary_details
#deliaddr = params[:deliveries]
end
and in the create method i coded
logger.info("***#{#deliaddr} ")
but the parameters could not found in the rails console
Step 1: Define route of your controller:
# routes.rb
get '/save_delivary_details', controller: <:controller_name>, action: :save_delivary_details
Step 2: Define script with proper URL
function setDeliveryDetails () {
var all_del_rate= $('#all_dr').val();
var all_del_period= $('#all_dp').val();
var array=[all_del_rate,all_del_period]
$.ajax({
type:"GET",
url:"/save_delivary_details" ,
dataType:"json",
data: {deliveries: array},
success:function(result){
// alert(result);
},
error: function() {
}
});
}
Step 3: Get data inside controller action
Maybe you are looking for this (but it's nasty), more details:
$deliaddr = []
def save_delivary_details
$deliaddr = params[:deliveries]
end
And finally in create method:
logger.info("***#{$deliaddr} ")
UPDATE (maybe you are looking for this)
In controller why don't you save this seliveryDetails in DATABASE? Or if delivery address is temporary and don't want to save it permanently, maybe you can store it in session in this way:
# in controller
def save_delivary_details
session[:delivary_details] = params[:deliveries] # maybe you can make this `delivery_details` key unique by putting current_user id or something
end
And then inside create action you can retrieve it in this way:
def create
logger.info("***#{session[:delivary_details]} ")
end
Hope it'll help you. Cheers!
You have to mention the controller symbol when parsing data from AJAX
Change your code like this.
Your Controller is expecting the controller symbol in the beginning of parameters
$.ajax({
type:"GET",
url:"/save_delivary_details" ,
dataType:"json",
data: {delivary_details: {deliveries: array}},
success:function(result){
// alert(result);
},
error: function() {
}
});
This is my example
$.ajax '/schedules',
type: "POST",
data: { schedule: { days: day_id_array, schedule_title: schedule_name, schedule_type: schedule_type}},
async: true
success:(data) ->
if without_date == true
location.href = "/schedules_without_date/" + data.id + '?saved=true&type=' + getScheduleType schedule_type
else
location.href = "/schedules/" + data.id + '?saved=true&type=' + getScheduleType schedule_type
return false

Categories