Hey guys, I am very new to AJAX and and working on a rating script, but I want to be able to pass multiple values back into my ajax function :
Right now it runs a to a php script called ratings, where it takes the total value of votes / votes and multiplies it by the width of each start to get an accurate current rating. What I'd like to do is also pass back the amount of votes so I can display them. I know how I could do this by making another function but that seems redundant and not very efficient.
My question is, is it possible to pass back not only the width (value / votes * 22) for my rating box, but also the total # of votes in 1 query. If not the better question would it be better to pass back a string in jquery that already has the votes & value, and do the width calculation with java script ?
$(document).ready(function() {
getRating();
function getRating(){
$.ajax({
type: "GET",
url: "../includes/rating.php",
data: "action=get&bookid="+$("#current").attr("value"),
cache: false,
async: false,
success: function($rating) {
$("#current").css({ width: "" + $rating });
},
error: function(result) {
alert("Error");
}
});
}
Thanks!
Yes you can pass back both values. Just send JSON using json_encode instead of text.
$(document).ready(function() {
getRating();
function getRating(){
$.ajax({
type: "GET",
dataType: 'json',
url: "../includes/rating.php",
data: "action=get&bookid="+$("#current").attr("value"),
cache: false,
async: false,
success: function(data) {
$("#current").css({ width: "" + data.rating });
$("#votes").html(data.votes);
},
error: function(result) {
alert("Error");
}
});
}
If your struggling to passback multiple values in one callback you could try inserting a random character (like a #, something your not going to use) inbetween the values then split it on the server side. For example.
Client Side...
var callback = value1##value2##value3;
Server Side...
$values = split($callback, "##");
$value1 = $values[0];
$value2 = $values[1];
Hope that helps...
Since the width is a derived value based on the number of votes, I would pass the number of votes and do the math in Javascript.