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.
Related
I have an ajax function that retrieve two values for a given post: one for the number of likes, another one for the div that contains all the people that liked that post.
Everything seems to work fine, the json retrieved is correct, but the printing result is incorrect. Every time I try to get the number of likes (data.numDiLikes) I always get undefined even though the json is saying {"numDiLikes":"1","personeACuiPiace":"div info and stuff"}, how do I fix this?
AJAX with JSON
$.ajax({
dataType: "json",
type: 'POST',
cache: false,
url: "lib/ottieniCose.php",
data: { like: "", id: valCOR, comOrisp: comOrisp },
dataType: "html",
success: function(data, textStatus){
trova.find('.numDiLikes').first().replaceWith('<p class="numDiLikes">' + data.numDiLikes + ' mi piace</p>' + data.personeACuiPiace);
}
});
PHP
if ($_POST['comOrisp'] == 'commento') {
$commento->set_likes($_POST['id'], true);
// number of people that liked the post
$return_data['numDiLikes'] = $commento->get_likes($_POST['id'], true);
// div with all the people who liked the post
$return_data['personeACuiPiace'] = $commento->posso_fare_qualcosa($_SESSION['auth'], 'cancRisp', $_POST['id']);
echo json_encode($return_data);exit;
}
Use dataType: "json" to tell $.ajax that it returns JSON, and that it should parse it. dataType: "html" means that it returns HTML text, and data will be a string, not an object.
I want to get twitter counts of my website and article pages. After getting them I want to store them in database. I tried getting counts and posting them on my query.php using ajax but its showing me Cross Origin Block Error. Is there any way to do this? or am I missing something?
$.ajax({
url: "https://cdn.api.twitter.com/1/urls/count.json?url=<?php the_permalink(); ?>",
crossDomain: true,
crossOrigin: true,
success: function(data) {
var count = JSON.parse(data);
$("#dd").html(count);
$.ajax
({
type: "POST",
url: "post.php",
data: { stats: count, paralink:'<?php echo $rows['link_id'];?>', social:'2' },
success: function(data) {
},
dataType: 'json'
});
}
});
It would probably be more efficient / faster if you just made one ajax call to your server and a request to twitter directly from your php script.
And it would solve your problem as well:
// you should validate the input, but for simplicity:
$link = $_POST['paralink'];
// ^^^^^^^^ I am not sure if this is the page you want, you need to check that.
// get twitter json
$json = file_get_contents('https://cdn.api.twitter.com/1/urls/count.json?url=' . $link);
Now you just need the inner ajax call.
If you do an ajax call to retrieve info from a MySQL database and you time the function so it runs every X seconds, I am a bit confused about where do the GET values reside, in order to empty them.
I have this code in test.js:
var fill = function () {
$.ajax({
type: "GET",
url: "refresh.php",
dataType: "html",
success: function( data ) {
$( "#tb" ).append( data );
setTimeout( fill, 5000);
}
});
} ;
and in refresh.php I have the SQL query to retrieve the info. After the query, I setting the table like this:
printf( "<tr><td>".$row['name'].
"</td><td>".$row['surname'].
"</td><td>".$row['phone'].
"</td><td>".$row['date'].
"</td></td></tr>");
How can I stop the table from populating the same row every 5 seconds? I can pass the $row['name'] values to regular php values if needed, but I don't fully get in which moment I should empty them.
There might be another solution to this, but I think that my problem could be easily solved by removing the contents of the table before adding another. For instance:
var fill = function () {
$.ajax({
type: "GET",
url: "refresh.php",
dataType: "html",
success: function(data) {
$('#tb').empty().append(data);
}
});
};
setInterval(fill, 5000);
You can also make use of setInterval() so that you don't need to define a timeout on every execution.
That will do.
Thanks!
I'm not sure if there is any way to do this or not, but this would solve so many of my problems if there is a simple solution to this.
What I need/want to be able to do is return HTML and JSON in my success of ajax request. The reason being, I want to request a file and return all of that page, but I also want to be able to return a specified set of information from the page in json, so I can use it for other things.
This is what I'm doing now:
$.ajax({
type: "POST",
url: "inc/"+page+".php",
data: "id="+encodeURIComponent(pageID),
success: function(html){
$("body > .container").html(html);
}
});
This is what I'd like to be able to do:
$.ajax({
type: "POST",
url: "inc/"+page+".php",
data: "id="+encodeURIComponent(pageID),
success: function(html){
$("body > .container").html(html);
$("title").html(json.PageTitle)
}
});
on the page that is being returned, I would specify what I want the title to be. (For instance, if it's a profile, I would return the user's name)
HTML and data wrapped in JSON
You can do it by returning a 2 element JSON array.
The first element contains HTML and the second element contains another JSON array with the data inside. You just need to unwrap it carefully without breaking anything.
Serverside
$html = '<div>This is Html</div>';
$data = json_encode(array('page_title'=>'My Page'));
$response = array('html'=>$html, 'data'=>$data);
echo json_encode($response);
Clientside
//Ajax success function...
success: function(serverResponse){
$("body > .container").html(serverResponse.html);
var data = JSON.parse(serverResponse.data);
$("title").html(data.page_title)
}
Note 1: I think this is what #hakre meant in his comment on your question.
Note 2: This method works, but I would agree with #jheddings that its probably a good idea to avoid mixing presentation and data. Coding karma will come back to bite.
Trying to mix the retun value to contain presentation and data seems like a potential for confusion. Why not split it into two calls and fetch the data on success of the other?
Something like:
$.ajax({
type: "POST",
url: "inc/"+view_page+".php",
data: "id="+encodeURIComponent(pageID),
success: function(html) {
$("body > .container").html(html);
$.ajax({
type: "POST",
url: "inc/"+data_page+".php",
data: "id="+encodeURIComponent(pageID),
success: function(json) {
$("title").html(json.PageTitle);
}
});
});
You also have the option of including the data in html5 data attributes
For instance, if you're returning a list of Animals
<ul id="ZeAnimals" data-total-animals="500" data-page="2">
<li>Cat</li>
<li>Dog</li>
...
</ul>
You can then collect the data you require using
$('#ZeAnimals').data('total-animals')
Sometimes separating your request into two different ajax calls makes sense also.
You may use a library that does that automatically, like http://phery-php-ajax.net. Using
Phery::instance()->set(array(
'load' => function(){
/* mount your $html and $json_data */
return
PheryResponse::factory()
->json($json_data)
->this() // points to the container
->html($html);
}
))->process();
$(function(){
var $container = $('body > .container');
$container.phery('make', 'load'); // or $container.phery().make('load')
$container.bind('phery:json', function(event, data){
// deal with data from PHP here
});
$container.phery('remote');
});
You may, as well, use phery.views to automatically load a portion of the site automatically, without having to worry about client-side specific code. You would have to put a unique ID on the container, container in this example:
$(function(){
phery.view({
'#container': {}
});
});
Phery::instance()->views(array(
'#container' => function($data, $params){
/* do the load part in here */
return
PheryResponse::factory()
->render_view($html)
->jquery('.title')->text($title);
}
))->process();
I have this for loop in jquery
$(document).ready(function() {
for(i=0; i<counter; i++)
{
dataCounter = i;
$.ajax({
url: 'file.php',
dataType: 'json',
data: dataCounter,
error: function(){
alert('Error loading XML document');
},
success: function(data){
$("#contents").html(data);
}
});
}
});
And then I want to bring in my dataCounter into the file.php as a variable and have it change each time so I can get different records in mysql in file.php, am I doing this right? How would the php portion look like? I know how pass variables to a php file with this method if I had a form, but I don't have a get or a post form to work with. Also, my variables are going to change.
Can someone help me? Thank you!
While I don't recommend running an ajax query inside of a loop, I am wiling to explain the data option for $.ajax(). Ideally, you pass an object as the data option, and it is translated by jQuery into a query string where each object property name is a key and its value is the value:
data: {
count: dataCounter
}
becomes
?count=1
in the query string of the ajax request if datacounter is equal to 1.
In PHP you would access it as $_GET['count'].
data needs to be a key-value pair, not just a value as you have it here. Try something like: (not tested)
$.ajax({
url: 'file.php',
dataType: 'json',
data: ({dataCounter : dataCounter}),
error: function(){
alert('Error loading XML document');
},
success: function(data){
$("#contents").html(data);
}
});