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");
}});
Related
1 week ago, i decided to start adding AJAX and more jquery to my Website.
I think, the "combination" of PHP / Jquery / AJAX is the best thing ever.
Now i want to create a "like - system" in my community board. I did something similar already:
$(function(){
$('.action-button.like').click(function(){
//ajax part
var articleId = $('.article-Id').html();
$.ajax({
type: "GET",
async: true,
url: '/wiki/parts/likeArticle.php',
data: { 'articleId': articleId },
//change button
success: function (msg){
$('.action-button.like span').fadeOut(400);
},
error: function (err)
{ alert(err.responseText)}
});
});
});
as you can see, the button / element disappears after a click() on it.
PHP data: the .php file "inserts the like" into the database ...
So - this works great !
Back to my question: After an user likes the post, i want to display a container with all users, which did this before.
I'm asking this, because i know how to do this / I have an Idea how i can realise my little project, but i dont know, if this is the propper way :)
My solution:
in $.ajax:
I want to create a function on "success:" (and a new .php file, which loads all users / "likers")
the function uses .load() and loads the file, so everything should be done right, shouldn't it ?
I hope you understand my problem,
Greets :)
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;
}
});
DISCLAIMER: This question is a question about question. So that makes this question a meta question. It does not have any connection to the previously asked questions. If you find any resemblance, lemme tell you one thing- it's purely coincidental.
I want to make an AJAX request from my web page. I have been trying to do this, but none of the methods worked perfectly. The only post that I found something close to reality is this.
I tried various other methods from SO & other similar sites, but all of those posts said only one thing to me.
"No 'Access-Control-Allow-Origin' header is present on the requested resource."
I know now you are gonna mark this question as duplicate since there are loads of questions similar to this. Now..Lemme tell ya' one thing. I tried every piece of sh*t I found in SO, but none of 'em gave me the result that I was looking for. It's not because they all are wrong. It because I ain't got no knowlegde on how to use 'em. Then finally...I settled on the link I provided above. It's easy..but I need to know certain things about the code.This is the first time I am hearing the beautifully sodding acronym- CORS. So, if anyone can help me understand the questions I raise, Up votes for all of ya'. I wanna resolve this son-of-a-b*tch question before I celebrate my birthday for the third time this year. I will tell ya' what all I have-in form of resources & questions.
1) A rotten server located at Elizabeth town.
2) I need to access it.
3) I am planning to make a HTTP GET request.
4) I have a url. (eg. http://whereismyweed.com)
5) I store it into a JavaScript variable. var stoner='http://whereismyweed.com'
6) I have a HTML div tag in my webpage. (<div id="myprecious"></div>)
7) I wanna display the response I get from the server inside of 'myprecious' div.
8) And last but not the least... my AJAX function. (Courtesy: some website I visited)
$.ajax({
url: stoner,
data: myData,
type: 'GET',
crossDomain: true, // enable this
dataType: 'jsonp',
success: function() { alert("Success"); },
error: function() { alert('Failed!'); },
beforeSend: setHeader
});
What is 'myData'?? What does it contain. How can I get the response for this request? What is 'setHeader'?? Does it have any significance??? How can I display the response inside myprecious div? What changes should I make in the function? Is this function correct?
Too many question, Right???? Well...I need only one common answer for it?
Your function is correct.Follow below steps do achieve your goal-
//for getting response modify your code like
success:function(response){
alert(response);
$('#myprecious').html(response); //myprecious is id of div
}
// myData variable is jSon object which contains request parameter has to send.Eg.
var myData = {'first_name':'Foo','last_name':'Bar'} // now on server first_name and last_name treated as request parameter.
// If server not required any special headers to validate request 'setHeader' does not require. by default $.ajax will take care of it. you can remove it.
/// final code looks like
$.ajax({
url: stoner,
data: myData,
type: 'GET',
crossDomain: true, // enable this
dataType: 'jsonp',
success: function(response ) { $('#myprecious').html(response);
},
error: function() { alert('Failed!'); }
});
I need to build a very simple button on a website that toggles a boolean on the server. When the boolean is True, I want to show a green icon, when it's False, I want to make it red. When a user clicks the icon, it should send a command to the server and update, then the icon should only change colors (image src) when the server has replied that the boolean has in fact been toggled.
I'm not very experienced with web apps, but I'm wondering what framework would work best for this? Is there an easy-to-use HTML5 way to do this? AJAX? Websocket? I'm using websockets on another page of the app and it's working, but it might be overkill for something this simple?
Websockets are complete overkill for this, however you said you have another part of the application done...what is your backend? If you like C#, ASP.NET has a lot of choices for you (MVC4 is my personal favorite).
In MVC you would create an action inside your pages controller to interpret some JSON passed from an AJAX call kind of like this:
public JsonResult FooData(int _id)
{
var dataContext = true;
if(_id == 7)
dataContext = false;
return Json(dataContext, JsonRequestBehavior.AllowGet);
}
...and on your client side you would call the FooData method like this:
$.ajax({
url: "MyController/FooData",
data: { _id: obj.id },
dataType: 'json',
async: true,
success: ChangeImage
});
Where ChangeImage is a javascript function set as your ajax calls' success callback function, so it might look like this:
function ChangeImage(data) {
if(data == true)
document.getElementById('myImg').src = "red.jpg";
else
document.getElementById('myImg').src = "green.jpg";
}
It's short, sweet and to the point. There's a learning curve but it's well worth the time and effort. I can't live without this framework anymore!
EDIT: Forgot to add data to pass in the ajax call, fixed now!
EDIT EDIT: I didn't add the logic of if click check bool -> if true, set false -> send flag -> if flag == 'change' change color -> if click ... etc etc etc because that's just busy work. This is more than enough to get you there though.
You don't want to send loads of data, or want pushing from the server, so I would recommend AJAX.
jQueries ajax is fine, but you might want to look at google if you want something more fancy.
Websockets are only usefull when you want much data, and really live.
Now you only want to send data from the client once and then, instead of keeping both sides up-to-date all the time.
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