Use the result of an ajax request in my views.py, Django - javascript

Thanks to a javascript function and an ajax request, I have a count indicating the number of points a user makes when he uses my app. He can see that count on the page where he 'plays'.
Now, what I would like to do, is to pass this number into my views.py so that it modifies the object "Score" of my user.
I explain. Thanks to this function, I get the count:
var count = parseInt(0);
setInterval(function() {
$.ajax({
type: "GET",
url: "http://myxml",
success: Escore
});
}, 60000);
function Escore(xml){
$(xml).find("user").each(function() {
if($(this).attr("id") === id ) {
count += parseInt($(this).attr("count"));
$(".PlayerScore").html(count)
}
});
}
displayed in my html:
<div class="PlayerScore"> </div>
Now, I would like to modify the object "score" of my user thanks to that. Every minute, I have a request that gives me the number of points the player makes in my div. How can I take this count in order to modify my "request.user.userprofile.score" in my views.py?
I hope my question is not too confusing. Any help would be really welcome. thanks!

Hm If I understand the question, you need to do the following:
Create your view function, and create a URL pattern in URL.conf that attaches to this view function. Something like /points/save/
This function will likely require the points of the user and the user ID (so you can make changes to the specific user in the database)
You need to make an ajax request that sends the point data and the user ID To the URL that points to your view function. Sent through GET/POST
Your view function will lookup the user from the user id sent from jquery ajax call, then edit the user points with the points sent from the ajax call
Here are a few guides to help
Ajax with Jquery and Django
Django and Jquery

Related

Calling Golang from HTML

I'm helping with an open source project. It's a small Go webserver running on a device containing a Raspberry Pi. I want to be able to have a user click a button on an html screen, which calls a routine in Go, which returns 2 values, a boolean and a string.
What we are wanting to do is see which network interfaces are up on the raspberry pi e.g. is the lan connection up?
To do this I really need to ping a site from each interface. This takes a few seconds for each of 3 interfaces: Lan, WiFi, and 3G.
I can do this when the page is requested and fill in an html template as the page loads, but it means waiting maybe 10 to 15 secs for the page to load, so it seems like something is broken.
So I want to be able to list each of the 3 interfaces on the page and have the user click 'test' which then calls a routine in the underlying Go webserver.
I then need to be able to display the results from the call in a couple of text areas for each interface.
What I have tried:
I have tried registering a Go function (in this case IsLANConnectionUp) using funcmap from the net/html package and calling it from the html template from a JavaScript function, like this:
<button onclick = "getLANStatus()" class="btn btn-primary">Test</button>
<script>
function getLANStatus() {
var status = document.getElementById('status');
{{ if IsLANConnectionUp }}
status.innerHTML = "Lan is up!"
{{ else }}
status.innerHTML = "Lan is down!"
{{ end }}
}
</script>
But having the template code inside the javascript code doesn't seem to work. Also, I'd like the text output from the ping command (which my Go function getLANStatus and I don't know how to extract that data from the function call. The documentation says only one value can be returned.
Searching on StackOverflow I see this: calling Golang functions from within javascript code
$.ajax({
url: "http://www.example.com/signup",
data: {username: "whatever"} //If the request needs any data
}).done(function (data) {
// Do whatever with returned data
});
But it says things like "// Do whatever with the returned data" I'm new to web programming and so don't know how to use that code. If this is the way to go, could someone please expand on this a little?
Any help would be much appreciated.
So couple different concepts here.
Render: On the initial request to your html that generates the Test button. Your go server will render that html 1 time and return it to your browser. It does not re-request dynamically unless you wire some stuff up to make the web page change.
Client: So when someone clicks your button, the function getLANStatus will be ran. You will want that function to do a few things
Through ajax, communicate with your go server through an api that will return the status of your connections as a json object. Something like
{
"3g": "up",
"lan": "down",
"wifi": "up"
}
Second, in the done part of your ajax, you will manipulate something in the DOM in order to convey that the status of the interfaces is what it is. You could do that by finding the element, then changing the text to what is returned by the object.
As a simple first step, you can alert the payload in the function that would look like this
$.ajax({
url: "http://YOUR_GO_SERVER_IP_OR_DNS:PORT/interfaces_status.json"
}).done(function (data) {
alert(data);
console.log(data);
debugger;
});
Then if you request that with the console open in chrome, you will be able to directly play with the returned data so that you know what all it reponds to.

Why is it adding when it’s not being called

I made a JavaScript code that I’m building to make a shopping cart, but this code is run even if I don’t click it:
function addProduct(prodId) {
var sessionDivId = document.getElementById(prodId);
if (prodId) {
sessionDivId.innerHTML = '<?= $_SESSION['product_id_1']+=1 ?>';
}
}
<div onclick="addProduct('testSession1');">ADD</div>
<div id="testSession1"></div>
Everytime I refresh the website it adds 1 to session testSession1 even if I don’t click the button “ADD”.
Your PHP logic will be run on the server before the user loads the page. To add a product, you will need to store it somehwere else (since the PHP has no longer any control to put +=1 to the cart).
I would make an AJAX request to post a product id to the user shopping cart:
function addProduct(prodId) {
// using jQuery for simplicity of writing
$.ajax({
type: "POST",
url: "/cart/item/" + prodId, // or other backend API endpoint
success: displayNiceUserMessage()
});
}
And of course some error handling in case something goes wrong.
Update
I saw that you did not want to use Ajax. Just so you know, it doesn't need to be any more complex than the code I wrote above. Then in the backend you just add +1 to the session if any user makes a POST request to that url.
But if you do not want ajax, you will need to reload the page when clicking the add button. Like was said in the comments, put a form of type post around the add button (and with a good url to make your server know that it was an added item event that took place), and make the add button a submit type. Then no javascript is needed at all.

AJAX call how to retrieve my javascript variable

I work with Rails 4 and basically I am searching a value on my html webpage traversing the DOM with jquery.
I store the value in a variable named key and I want to use this value to then make a request that would look like this :
Record.find(id: key).name
I perform an AJAX call and it works well (I checked it rendering status json ok). But now how can I use/retrieve the parameter key in my controller ?
I have a User and a Record model. In the app/views/usersdirectory I have the partial _form.html.erb in which I am doing some javascript.
var key = $('input#record_id').val();
And I want this variable to be available in the method search of my user controller, so that I can make a request with the parameter key.
So I am doing an AJAX call that looks like this :
$.ajax({
url: "/search",
type: "POST",
data: {
value: key
},
complete: function(){
console.log('success');
}
});
And in my config routes file I wrote this route :
post '/search' => 'users#search'
In my User controller I wrote the method like this :
def search
#record = Record.find(params[:key])
end
Is #record available in my partial ? How can I print in my view the result of my request ?
Can anyone tell me if I am doing right or wrong for my AJAX call ? Thanks for any help. If I forgot to mention any information you might need tell me and I'll edit my post.
I added a complete function in my AJAX call, that is supposed to show successif the AJAX call had been done and in my console log I have this message 'success' that appears
For 404 not found the url must be wrong.
And to get the param key in your controller you must change data to data: {key: key} or if you use data: {value: key} then your action must change the name of the param like #record = Record.find(params[:level])
Basically, you are not using the right param name in your controller which is why the issue arises. Hope it helps.
To answer your second question:
#GDMN, you need to get your basics right! Every ajax has a success and failure callback.You could return json from your action which will be used by success callback and you could do whatever you want from there. Essentially in rails you might want to render a js file like this
Create a file named search.js.erb and use your javascript code in it like below
$('.some_id_or_class').html("<%= #record.name %>")
that will simply replace the element of that class with the value that is returned by #record.name
put the full url
url: "http://yoursite.domain/search",

Send javascript array to SQL then get info back to the HTML

I have a javascript array which stores seat numbers (in a cinema), which are selected by the user via clicking and added to the array each time using a function. I want the page to show the total cost of these seats, which means accessing an sql table inside some php.
So I have e.g. seatNumbers = ["a1", "d6", "e3"] and three sql query like 'select cost from seat where seat_number='a1';'. The function that adds to the array on clicking a seat and prints the seats is something like:
var seatArray = [];
function addSeat(seat) {
seatArray.push(seat);
document.getElementById("textarea").innerHTML="Seats : ";
for (x in arraytest) {
document.getElementById("textarea").innerHTML+=arraytest[x];
document.getElementById("textarea").innerHTML+=" ";
}
}
And I want to show the total cost in the HTML.
I'm wondering if what I'm trying to achieve is possible? What would be the general method and would I need to load a new page instead? And if it's not possible, what would be a better way to go about this?
Your question is very broad, and to answer it, quite some stuff needs to be known and used.
What you want is very possible though. In fact, there are technologies that in their core focus on providing solutions to problems like yours! What you need is some solid info (and possibly experience with) AJAX and maybe even REST. By using AJAX your page wont have to reload, and in your situation AJAX is probably the best choice anyway.
To point you in the right direction: AJAX javascript W3Schools Tutorial and PHP AJAX W3Schools tutorial
Then, use jQuery to make it all a LOT easier: jQuery (i'd go for 1.x)
You'll have to create an API that accepts an HTTP (preferably GET) request and returns the cost for the seat that you refer to in your URL like (more REST like, should return a whole seat object with price included): /seat/200, or (not REST like)/seat/cost/200).
Your choice if you want to follow (if you haven't read up on it, possibly confusing) REST rules. In your situation i'd just begin with some good old AJAX, it just works and is even better suited for stuff like this.
You should use AJAX. Try using jQuery library and ajax function.
Covert Your array with seats on JSON string and send it by AJAX to page which check the whole price. Then, You can update Your HTML code with total cost.
var json_data = '{...}';
$.ajax({
url: "total_cost.php",
dataType: "json",
type: 'POST',
data: { json: json_data },
success: function(response) {
// .. on success
var json_response = jQuery.parseJSON(response);
var cost = json_response.total_cost;
}
});

Voting box (plus/minus, not star rating)

I'm looking for a voting script/widget (preferably jQuery), but not a star rating one, one with +1 and -1 options like this (admire my profesionnal MSPaint skills ^^) :
Anyone know about one ?
Thanks a lot !
you can do this using ajax.
Recommend you set up some ajax listener page and ping with some userID and vote (1,-1) or something along those lines.
This assumes you have a userID and login credentials etc. Or you can register it against their IP or something.
Basically:
ajaxListener.php?ID=123456&vote=1
send the ajax listener, and then have the total vote count update when the ajax is complete (have your ajax listener echo back a string of data lets say):
voteTotal=10~totalVote=95
Once you read this with ajax, split it with javascript:
var split1=responseText.split("~");
var voteScore=split1[0];
var voteCount=split1[1];
not tested but this should work and complete what you are thinking.
ajax:
http://api.jquery.com/category/ajax/
$.ajax({ url: "ajaxTool.php?id="+idVariable, context: document.body,
success: function(){
$(this).addClass("done");
}});

Categories

Resources