I am currently using the JQuery ajax function to call an exterior PHP file, in which I select and add data in a database. Once this is done, I run a success function in JavaScript. What's weird is that the database is updating successfully when ajax is called, however the success function is not running. Here is my code:
<!DOCTYPE html>
<head>
<script type="text/javascript" src="jquery-1.6.4.js"></script>
</head>
<body>
<div onclick="addtask();" style="width:400px; height:200px; background:#000000;"></div>
<script>
function addtask() {
var tid = (Math.floor(Math.random() * 3)) + 1;
var tsk = (Math.floor(Math.random() * 10)) + 1;
if(tsk !== 1) {
$.ajax({
type: "POST",
url: "taskcheck.php",
dataType: "json",
data: {taskid:tid},
success: function(task) {alert(task.name);}
});
}
}
</script>
</body>
</html>
And the PHP file:
session_start();
$connect = mysql_connect('x', 'x', 'x') or die('Not Connecting');
mysql_select_db('x') or die ('No Database Selected');
$task = $_REQUEST['taskid'];
$uid = $_SESSION['user_id'];
$q = "SELECT task_id, taskname FROM tasks WHERE task_id=" .$task. " LIMIT 1";
$gettask = mysql_fetch_assoc(mysql_query($q));
$q = "INSERT INTO user_tasks (ut_id, user_id, task_id, taskstatus, taskactive) VALUES (null, " .$uid. ", '{$gettask['task_id']}', 0, 1)";
$puttask = mysql_fetch_assoc(mysql_query($q));
$json = array(
"name" => $gettask['taskname']
);
$output = json_encode($json);
echo $output;
Let me know if you have any questions or comments, thanks.
Ibelieve it runs but alert wont show because of error -
success: function(task) {alert(task.name);}
You have to decode JSON first with jQuery.parseJSON(), task is just a string
it shoudld look somthing like this
function(m)
{
var task = jQuery.parseJSON( m );
alert(task['name']);
}
Edit:
Ok ...
Try to use developer tools in your browser and place breakpoint on your success function, if it doesnt even lunch try to add error callback for your ajax call
error: function(xhr, exc)
{
alert(xhr.status);
alert(exc);
}
Edit2:
and there is your problem - your ajax is not only returning json data, but php warning too, and now I see where is your problem - you are fetching data after insert, delete
$puttask = mysql_fetch_assoc(mysql_query($q));
Now I feel bad for not noticing it sooner...
Related
I have a web application where I need to get values from a MySQL database.
The series of event is as follows:
PHP code creates HTML page (works fine)
Click a button on the page, updating a cookie (works fine)
Use cookie in a MySQL query (This does not work)
Get a record from the above MySQL query result and pass to HTML page with jQuery
The problem with bullet 3 is that the MySQL query is only run when I load the page (of course). But I need a method to run a query, based on user input (stored as the cookie), without reloading the PHP script.
How can this be done?
My engineering c-coding brain has a really hard time wrapping this ajax thing. Here is the code so far, still not working:
The popup(HTML) I want to update with new strings when a button on the same page, is clicked:
<div id="popup" class="popup" data-popup="popup-1">
<div class="popup-inner">
<h2 id="popup-headline"></h2> //Headline, created from a cookie. Could be "Geography"
<div id="dialog"></div> //From Will's suggestion
<p id="question"></p> //String 1 from online MySQL DB goes here "A question in Geography"
<p id="answer"></p> //String 2 from online MySQL DB goes here "The answer to the question"
<p class="popup-small-button"><a data-popup-close="popup-1" href="#"><br>Close</a></p> // Hides the popup
<a class="popup-close" data-popup-close="popup-1" href="#">x</a>
</div>
</div>
Then i have my file with custom functions. It executes whenever the popup is shown:
<script>
jQuery(function() {
jQuery('[data-popup-open]').on('click', function(e) {
function myfunction(myparams) {
// your logic here: testing myparams for valid submission, etc.
alert("hey");
jQuery.ajax({
type: 'post',
url: 'server.php',
data: {
my_var1: 'question',
my_var2: 'answer'
},
success: function(data) {
data = JSON.parse(data);
jQuery('#question').html(data["question"]);
jQuery('#answer').html(data["answer"]);
},
error: function(jqxhr, status, exception) {
alert('Exception:', exception);
}
});
}
});
});
</script>
My server.php file contains now this:
<?php
require("db.php");
if(isset($_POST['my_var1']) && isset($_POST['my_var2'])) {
myfunction($_POST['my_var1'], $_POST['my_var2']);
}
?>
And my db.php contains this:
<?php
function myfunction($var1, $var2) {
$db = mysqli_connect('MyOnlineSQLPath','username','password','database1_db_dk');
$stmt = $db->prepare("SELECT question, answer FROM t_da_questions WHERE category_id=?;");
$stmt->bind_param("s", $_COOKIE('category'));
$stmt->execute();
$retval = false;
if($result->num_rows > 0) {
$row = $result->fetch_assoc();
if(!is_null($row['question']) && !is_null($row['answer'])) {
$retval = new stdClass();
$retval->question = row['question'];
$retval->answer = row['answer'];
}
}
mysqli_close($db);
return $retval;
}
?>
What I need, is the "question" and "answer" from the SELECT query.
TL;DR I need question and answer strings to go into <p id="question"></p> and <p id="answer"></p> in the HTML, both without refreshing the page. The getCookie('category') is a cookie stored locally - It contains the last chosen category for a question. The function getCookie('category') returns an integer.
Let me know if you need any more info on this.
Here is some template AJAX that may help you out. I used this in another project. This won't require a page refresh. You will have to include the code to send your cookie's data in the 'data' section.
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<meta charset="utf-8">
</head>
<body>
// your HTML here
<script>
<div id="dialog"></div>
function myfunction(myparams) {
// your logic here: testing myparams for valid submission, etc.
$.ajax({
type: 'post',
url: 'myphpfile.php',
data: {
my_var1: 'myval',
my_var2: 'myval2'
},
success: function(data) {
$("#dialog").html("<span>Success!</span>");
$("#dialog").fadeIn(400).delay(800).fadeOut(400);
}
});
}
</script>
</body>
</html>
Then in the file 'myphpfile.php', you'll have code like the following:
<?php
require("../mycodebase.php");
if(isset($_POST['my_var1']) && isset($_POST['my_var2'])) {
myfunction($_POST['my_var1'], $_POST['my_var2']);
}
?>
Finally, in mycodebase.php (which is stored in a place inaccessible to the public/world), you'll have a function that actually runs your query and returns your result:
function myfunction($var1, $var2) {
$db = mysqli_connect('localhost','myuser','mypass','dbname');
$stmt = $db->prepare("UPDATE mytbl SET col1=? WHERE col2=?;");
$stmt->bind_param("ss", $var1, $var2);
$stmt->execute();
$result = (($db->affected_rows) > 0);
mysqli_close($db);
return $result;
}
UPDATE
That function above is to run an UPDATE query, so the result returned just indicates whether you successfully updated your data or not. If you want to return an actual result, you have to extract the result from the query as follows:
function myfunction($cat) {
$db = mysqli_connect('localhost','myuser','mypass','dbname');
$stmt = $db->prepare("SELECT question, answer FROM t_da_questions WHERE category_id=?;");
$stmt->bind_param("s", $cat);
$stmt->execute();
$retval = false;
if($result->num_rows > 0) {
$row = $result->fetch_assoc();
if(!is_null($row['question']) && !is_null($row['answer'])) {
$retval = new stdClass();
$retval->question = row['question'];
$retval->answer = row['answer'];
}
}
mysqli_close($db);
return $retval;
}
Then your server.php file will look like:
<?php
require("db.php");
if(isset($_COOKIE['category'])) {
json_encode(myfunction($_COOKIE['category']));
}
?>
Here's the JS:
jQuery('[data-popup-open]').on('click', function(e) {
function myfunction(myparams) {
// your logic here: testing myparams for valid submission, etc.
alert("hey");
jQuery.ajax({
type: 'post',
url: 'server.php',
// data section not needed (I think), getting it from the cookie
success: function(data) {
data = JSON.parse(data);
jQuery('#question').html(data["question"]);
jQuery('#answer').html(data["answer"]);
}
});
}
});
This is untested -- I may have gotten an argument wrong, but this is at least very close if it's not already there.
I am a newbie to PHP and MySQL development. I have built an app in Cordova using Visual Studio. The app works in the following way:
User selects a serial number from a drop down
After selecting a serial number, the data is showed on the chart
There is a toggle switch in the app, through which i am inserting the on or off state in the database based on the serial number
What I want to do?
When a user select any serial number, the switch will show the last ON or Off state based on Command Name of that particular serial number.
For this, I have generated a msql query and this query shows me the last command name of selected serial number
Below is my PHP code:
<?php
require_once('config.php');
$dsn = $_REQUEST['Device_Serial_Number'];
$cmd_Name = $_REQUEST['Command_Name'];
$sqlFet = "select ADC.Server_Device_Command_ID , ADC.Device_ID ,
ADC.Server_Command_ID as Server_Command_ID, ASD.Command_Name
from ADS_Server_Device_Command ADC
inner join ADS_Server_Command ASD on adc.Server_Command_ID = asd.Server_Command_ID
inner join ADS_Device dsn on adc.Device_ID = dsn.Device_ID
where dsn.Device_Serial_Number = '$dsn'
order by adc.Server_Device_Command_ID desc LIMIT 1";
$result = mysqli_query($con,$sqlFet);
mysqli_close($con);
echo $cmd_Name;
?>
Below is my AJAX call in JavaScript:
$.ajax({
method: "GET",
url: "http://localhost:MyPort/server/toggleFetch.php",
data: { Command_Name: tData , Device_Serial_Number: selectedVal },
success: function (data) {
var dt = data;
if (dt.Command_Name == "On") {
$("#cmn-toggle-7").prop('checked', true);
}
else if (dt.Command_Name == "Off") {
console.log('else');
$("#cmn-toggle-7").prop('checked', false);
}
},
error: function (xhr, status, error) {
alert(xhr.responseText, status, error);
//toastr.success('Data not fetched', '', { timeOut: 2000 })
//alert('Error');
}
});
But it doesn't show the required result and gives error as shown in below image:
Updated Code:
Bellow is my php updated code
require_once('config.php');
$dsn = $_REQUEST['Device_Serial_Number'];
//$cmd_Name = $_REQUEST['Command_Name'];
$sqlFet = "select ADC.Server_Device_Command_ID , ADC.Device_ID ,
ADC.Server_Command_ID as Server_Command_ID, ASD.Command_Name
from ADS_Server_Device_Command ADC
inner join ADS_Server_Command ASD on adc.Server_Command_ID = asd.Server_Command_ID
inner join ADS_Device dsn on adc.Device_ID = dsn.Device_ID
where dsn.Device_Serial_Number = '$dsn'
order by adc.Server_Device_Command_ID desc LIMIT 1";
$result = mysqli_query($con,$sqlFet);
$row = mysqli_fetch_array($result, MYSQLI_BOTH);
mysqli_close($con);
echo $row["Command_Name"];
Bellow is the ajax
$.ajax({
method: "GET",
url: "http://localhost:MyPort/server/toggleFetch.php",
//dataType: "json",
data: { Command_Name: tData , Device_Serial_Number: selectedVal },
success: function (data) {
var dt = data;
if (dt == "On") {
$("#cmn-toggle-7").prop('checked', true);
}
else if (dt == "Off") {
console.log('else');
$("#cmn-toggle-7").prop('checked', false);
}
},
error: function (xhr, status, error) {
alert(xhr.responseText, status, error);
//toastr.success('Data not fetched', '', { timeOut: 2000 })
//alert('Error');
}
});
Now when running the code i am not getting any error but still i am not getting my required result i.e. the toggle doesn't change it's state
For more information please see the image bellow
I don't know what's the problem, any help would be highly appreciated.
This error means, that AJAX didnt send Command_Name via GET. You will have to check variable tData if it contains some value.
First step: dont send command_name with AJAX to PHP script (This causes Error on Line 5!!), it is not needed. Second step: in Php script you will have to change echo $command_name, to echo result from DB based on $dsn. So echo result from DB.
$row = mysqli_fetch_array($result, MYSQLI_BOTH);
echo $row["Command_name"]; //This should show ON/OFF state from DB to AJAX.
I'm developing live auction site, with real-time bidding system. I'm using LONG POLLING when user bids on item. I've chose long polling because WebSockets are not yet very supported and NODEJS is to complicated for me to implement right now. So I'm stuck with this simle ajax long polling, which works great for about five bids.
So the problem is: Bidding works great for 5-6 item bids in 1 second intervals (I get instant response from server-ajax), but the 7th (click) on bid button this response-long polling hangs for about 16-22 seconds and then completes the request. At the end everything is updated in database and completed but after every 5-6 bids response/ajax call hangss for about 16-22 seconds.
How could I reduce this time, that everything should go smoothly no matter how many times user bids, without lag...
I'm using Apache/PHP/MySql on localhost/wamp
My code:
index.php
<script type="text/javascript" charset="utf-8">
var old_timestamp = <?php echo $old_timestamp;?>; //here i'm echoing last timestamp of auction
function waitForMsg(){
jq.ajax({
type: "POST",
url: "http://localhost/bid/comet/poll.php",
data: {"old_timestamp" : old_timestamp},
async: true,
cache: false,
success: function(data){
var json = eval('(' + data + ')');
if(json['msg'] != "") {
jq('#comet_display').html(json['msg']); //here I show ID of which auction item was bidded
}
old_timestamp = json['old_timestamp'];
setTimeout('waitForMsg()',100);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
setTimeout('waitForMsg()',1000);
}
});
}
jq(window).load(function(){
waitForMsg();
jq("#a_loader").show();
var url = "http://localhost/bid/auctions-ajax"; // the script where you handle the form input.
jq.ajax({
type: "POST",
url: url,
data: {au978 : true},
async:false, //to sem dodal za Ĩasovni zamik
success: function(data)
{
jq("#a_loader").hide();
jq("#show-category").html(data); // show response from the php script.
},
error: function(result) {
jq("#show-category").html("Sorry, something went wrong. Please try again later.");
}
});
});
function bid(id){
var url = "http://localhost/bid/comet/update-auction.php"; // the script where you handle the form input.
var user_id=<?php echo $user_id;?>; //user id from session
jq.ajax({
type: "POST",
url: url,
data: {"auct_id" : id, "user_id" : user_id}, // serializes the form's elements.
success: function(data)
{
//it updates in user table its remaining number of bids
},
error: function(XMLHttpRequest, textStatus, errorThrown){
alert("Something went wrong. Click OK to refresh.");
}
});
}
</script>
poll.php
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
require_once($_SERVER['DOCUMENT_ROOT'] . 'bid/include/DEFINES.php');
require_once(CLASS_AUCTION);
require_once(CLASS_DB);
$a=new Auction();
$old_timestamp = $_POST['old_timestamp'];
$bidded_id=0;
$db=DB::getInstance();
$sql="SELECT timestamp, id FROM auction ORDER BY timestamp DESC LIMIT 1"; //desno doda tabelo kategorija
$stmt=$db->db->prepare($sql) or die("Prepare Error");
$stmt->execute();
$result2=$stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($result2 as $rez){
$current_timestamp=$rez['timestamp'];
$bidded_id=$rez['id'];
}
$stmt->closeCursor();
while($current_timestamp <= $old_timestamp){
usleep(1000);
clearstatcache();
$db=DB::getInstance();
$sql="SELECT timestamp, id FROM auction ORDER BY timestamp DESC LIMIT 1";
$stmt=$db->db->prepare($sql) or die("Prepare Error");
$stmt->execute();
$result=$stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($result as $rez){
$current_timestamp=$rez['timestamp'];
$bidded_id=$rez['id'];
}
$stmt->closeCursor();
}
$response = array();
$response['msg'] = 'BID na avkciji: '.$bidded_id;
$response['old_timestamp'] = $current_timestamp;
echo json_encode($response);
}else{
require_once($_SERVER['DOCUMENT_ROOT'] . 'bid/errors/404.html');
}
?>
and the update-auction.php
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
require_once($_SERVER['DOCUMENT_ROOT'] . 'bid/include/DEFINES.php');
require_once(CLASS_AUCTION);
require_once(CLASS_USER);
require_once(CLASS_DB);
$u=new User();
$a=new Auction();
$auction_id=$_POST['auct_id'];
$user_id=$_POST['user_id'];
$date = new DateTime();
$timestamp=$date->getTimestamp();
$a->updateAuction($auction_id,$user_id,$timestamp/*,$bid_price,$bids_spent,$total_paid*/);
$u->updateUserBids($user_id);
}else{
require_once($_SERVER['DOCUMENT_ROOT'] . 'bid/errors/404.html');
}
?>
Thank you for viewing my problem!
Consider switching to WebSockets. It was designed to fix the long polling issue.
Ok, I have find a solution which fixes this 17-22 seconds LAG-HANGING problem. Now it's almost instant, regardless how many times you click. But I'm still not sure, if this is the best solution of long polling.
I'm posting it, if someone would have the same problem.
I've changed LONG POLLING function in my poll.php to this:
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
require_once($_SERVER['DOCUMENT_ROOT'] . 'bid/include/DEFINES.php');
require_once(CLASS_AUCTION);
require_once(CLASS_DB);
$a=new Auction();
$db=DB::getInstance();
$sql="SELECT timestamp, id, last_username FROM auction ORDER BY timestamp DESC LIMIT 1";
$response = array();
while(1)
{
$stmt=$db->db->prepare($sql) or die("Prepare Error");
$stmt->execute();
$result=$stmt->fetch(PDO::FETCH_ASSOC);
if (!empty($result)){
$current_timestamp=$result['timestamp'];
$response['msg'] = 'New BID';
$response['old_timestamp'] = $current_timestamp;
echo json_encode($response);
break;
}
sleep(3000);
clearstatcache();
}
}else{
require_once($_SERVER['DOCUMENT_ROOT'] . 'bid/errors/404.html');
}
?>
and now i'm polling in my index.php like this:
<?php
$db=DB::getInstance();
$sql="SELECT timestamp FROM auction ORDER BY timestamp DESC LIMIT 1";
$stmt=$db->db->prepare($sql) or die("Prepare Error");
$stmt->execute();
$result2=$stmt->fetch(PDO::FETCH_ASSOC);
$old_id=0;
$last_timestamp=$result2['timestamp'];
?>
<script type="text/javascript" charset="utf-8">
var last_timestamp = <?php echo $last_timestamp;?>;
var old_timestamp=0;
function waitForMsg(){
jq.ajax({
type: "POST",
url: "http://localhost/bid/comet/poll.php",
async: true,
cache: false,
success: function(data){
var json = eval('(' + data + ')');
if(old_timestamp==0 || last_timestamp==old_timestamp){
}else{
if(json['msg'] != "") {
jq('#comet_display').html(json['msg']);
}
}
old_timestamp = json['old_timestamp'];
setTimeout('waitForMsg()',500);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
setTimeout('waitForMsg()',1000);
}
});
}
jq(window).load(function(){
waitForMsg();
});
function bid(id){
var url = "http://localhost/bid/comet/update-auction.php"; //here I update auction and user's bids
var user_id=<?php echo json_encode($user_id);?>;
var user_name=<?php echo json_encode($user_name); ?>;
jq.ajax({
type: "POST",
async: true,
cache: false,
url: url,
data: {"auct_id" : id, "user_id" : user_id, "username" : user_name}, // serializes the form's elements.
success: function(data)
{
setTimeout('waitForMsg()',100);
var cnt = parseInt(jq(".db_bids").text());
if (!isNaN(cnt))
{
cnt--;
jq(".db_bids").text(String(cnt));
}
},
error: function(XMLHttpRequest, textStatus, errorThrown){
alert("Something went wrong. Click OK to refresh.");
}
});
}
</script>
I'm still developing this on localhost & will see how this behaves on real server with 100+ users.
If anyone have better and faster solution with LONG POLLING from databases, please let me know :)
I am making a notification system similar to the red notification on facebook. It should update the number of messages sent to a user in real time. When the message MYSQL table is updated, it should instantly notify the user, but it does not. There does not seem to be an error inserting into MYSQL because on page refresh the notifications update just fine.
I am essentially using code from this video tutorial: http://www.screenr.com/SNH (which updates in realtime if a data.txt file is changed, but it is not written for MYSQL like I am trying to do)
Is there something wrong with the below code:
**Javascript**
<script type="text/javascript">
$(document).ready(function(){
var timestamp = null;
function waitForMsg(){
$.ajax({
type: "GET",
url: "getData.php",
data: "userid=" + userid,
async: true,
cache: false,
success: function(data){
var json = eval('(' + data + ')');
if (json['msg'] != "") {
$('.notification').fadeIn().html(json['msg']);
}
setTimeout('waitForMsg()',30000);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
setTimeout('waitForMsg()',30000);
}
});
}
waitForMsg();
</script>
<body>
<div class="notification"></div>
**PHP***
<?php
if ($_SERVER['REQUEST_METHOD'] == 'GET' )
{
$userid = $_GET['userid'];
include("config.php");
$sql="SELECT MAX(time) FROM notification WHERE userid='$userid'";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
$currentmodif = $row['MAX(time)'];
$s="SELECT MAX(lasttimeread) FROM notificationsRead WHERE submittedby='$userid'";
$r = mysql_query($s);
$rows = mysql_fetch_assoc($r);
$lasttimeread = $rows['MAX(lasttimeread)'];
while ($currentmodif <= $lasttimeread) {
usleep(10000);
clearstatcache();
$currentmodif = $row['MAX(time)'];
}
$response = array();
$response['msg'] = You have new messages;
echo json_encode($response);
}
?>
there is a problem with your javascript line below
url: "getData.php",
data: "userid" + userid,
async: true,
remove the = sign and try again.
i have not read the whole code but found this is the cause test and feel free to reply if still got more issues.
You're not re-executing the SQL statement in the loop so the value in "$row['MAX(time)']" is never going to change.
If you re-execute the query in the loop this example may work--but executing a query every 10ms is not going to be a very efficient way to implement real-time notification.
Also, if the PHP script runs longer then the time configured in php.ini (max_execution_time, 30 secs by default), you'll get an error.
I'm assuming I have to put something in the success option. However what I have isn't working.
I declare this JS function on the page:
<script type="text/javascript">
function performAjaxSubmission() {
$.ajax({
url: 'addvotetotable.php',
method: 'POST',
data: {
},
success: function() {
}
});
}
</script>
Then in the ajax call which is working properly I declare this for the success:
success: function(data) {
performAjaxSubmission();
},
addvotetotable.php looks like:
<
?php
// If user submitted vote give the user points and increment points counter
require_once("models/config.php");
//Check to see if there is a logged in user
if(isUserLoggedIn()) {
$username_loggedin = $loggedInUser->display_username;
}
if (strlen($username_loggedin)) {
include_once "scripts/connect_to_mysql.php";
$query = mysql_query("SELECT vote FROM points_settings WHERE id=1")or die (mysql_error());
while($info = mysql_fetch_array($query)){
$points_value=$info['vote'];
}
include_once "scripts/connect_to_mysql.php";
$query = mysql_query("INSERT INTO points (id,username,action,points) VALUES ('','$username_loggedin','vote','$points_value')")or die (mysql_error
());
include_once "scripts/connect_to_mysql.php";
$query = mysql_query("UPDATE userCake_Users SET points=points + $points_value WHERE Username='$username_loggedin'")or die (mysql_error());
}
?>
You have to provide a value that you want to store in your database in the "data" of the ajax-request. Than you can use this in your php-code using $_POST["something"], check if it's valid... and return f.e. html or json which you than handle in the success-function.
<script type="text/javascript">
function onSubmitVote()
{
$.ajax({
url: 'addvotetotable.php',
method: 'POST',
data: "theVoteValue=" + <read_your_vote_value_here>,
success: function(result) {
>>>return something in your addvotetotable.php which indicate success and show a message whether the vote was successful or not.<<<
}
});
return false; // prevent submit if it is a submit-type button.
}
</script>
What this does is post data of the vote (it's value) to the php-file. There you can read it with $_POST["theVoteValue"] and put it in the database. You check if the value is valid and may insert, else you return an error-message or something so that in javascript you can notify the user of it's failure.