How can i post some ajax data to the controller function and get it back? For I want to post one integer to the function, and get another integer (total votes for the item which ID is posted), and on success i want to echo that vote count. I dont know how can i post the "id" to the controller function. Please see my code:
//post this integet
the_id = $(this).attr('id');
$.ajax({
type: "POST",
data: the_id,
url: "http://localhost/test/index.php/data/count_votes",
success: function(){
//the controller function count_votes returns an integer.
//echo that with the fade in here.
}
});
click(function() { var userID = $(this). attr('id'); //alert($(this). attr('id')); $. ajax({ type: "POST", url: 'logtime.
ajax() method allows you to send asynchronous http requests to submit or retrieve data from the server without reloading the whole page.
Start Using AJAX Today In our PHP tutorial, we will demonstrate how AJAX can update parts of a web page, without reloading the whole page. The server script will be written in PHP. If you want to learn more about AJAX, visit our AJAX tutorial.
So what does count_votes look like? Is it a script? Anything that you want to get back from an ajax call can be retrieved using a simple echo (of course you could use JSON or xml, but for this simple example you would just need to output something in count_votes.php like:
$id = $_POST['id'];
function getVotes($id){
// call your database here
$query = ("SELECT votes FROM poll WHERE ID = $id");
$result = @mysql_query($query);
$row = mysql_fetch_row($result);
return $row->votes;
}
$votes = getVotes($id);
echo $votes;
This is just pseudocode, but should give you the idea. What ever you echo from count_votes will be what is returned to "data" in your ajax call.
$.ajax({
type: "POST",
data: {data:the_id},
url: "http://localhost/test/index.php/data/count_votes",
success: function(data){
//data will contain the vote count echoed by the controller i.e.
"yourVoteCount"
//then append the result where ever you want like
$("span#votes_number").html(data); //data will be containing the vote count which you have echoed from the controller
}
});
in the controller
$data = $_POST['data']; //$data will contain the_id
//do some processing
echo "yourVoteCount";
Clarification
i think you are confusing
{data:the_id}
with
success:function(data){
both the data
are different for your own clarity sake you can modify it as
success:function(vote_count){
$(span#someId).html(vote_count);
For the JS, try
data: {id: the_id}
...
success: function(data) {
alert('the server returned ' + data;
}
and
$the_id = intval($_POST['id']);
in PHP
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With