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.
Related
I've literally checked out every single ng-repeat question out there but a lot of them don't deal with databases and people just use arrays in JS and a simple $scope.array.push("stuff") works for them.
I've tried $scope.apply, $rootScope and even calling the GET request right after a successful POST request.
I have a form with 2 text inputs, date and content.
When the submit button is pressed, date and content are added into a MySQL database using PHP.
The data is added just fine to the MySQL database and retrieving also works properly.
Even the GET request inside the successful POST request is executed.
So I don't understand why it forces me to refresh the page to see the updated ng-repeat results.
Am I missing something?
Any help or suggestions is greatly appreciated, thanks!
Relevant HTML code
<div ng-controller="insertController">
<h2> What I learned today </h2>
<form>
Date <br>
<input type="text" ng-model="date"><br><br>
Content <br>
<textarea rows="10" cols="50" ng-model="content"></textarea><br><br>
<input type="button" value="Submit" ng-click="insertdata()">
</form>
</div>
<div ng-controller="fetchController">
<span ng-repeat="item in results">
{{item.date}}<br>
{{item.content}}<br><br>
</span>
</div>
insertController.js
var app = angular.module('myApp', []);
app.controller('insertController', function($scope, $http) {
$scope.insertdata = function() {
$http({
method: 'POST',
url: 'http://localhost/storestuff/insert.php',
data: {'date':$scope.date, 'content':$scope.content, 'in':'json-format'},
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.then(function(res) {
console.log("Successful response", res)
$scope.date = "";
$scope.content = "";
$http.get('http://localhost/storestuff/fetch.php')
.then(function successCallback(response) {
alert("GOT NEW DATA");
$scope.results = response.data; // Allow angular to access the PHP output data
});
$scope.apply;
})
.catch(function(err) {
console.error("Error with POST", err);
});
}
});
insert.php
<?php
header('Access-Control-Allow-Origin: *');
$theConnection = mysqli_connect("localhost", "root", "", "storestuff");
if(mysqli_connect_errno()) {
echo "Failed to connect to MySQL.";
}
$theData = json_decode(file_get_contents('php://input'));
$date = mysqli_real_escape_string($theConnection, $theData->date);
$content = mysqli_real_escape_string($theConnection, $theData->content);
mysqli_query($theConnection, "INSERT INTO thestuff(date, content) VALUES('$date', '$content')");
mysqli_close($theConnection);
?>
fetchController.js
app.controller('fetchController', function ($scope, $http) {
$http.get('http://localhost/storestuff/fetch.php')
.then(function successCallback(response) {
$scope.results = response.data; // Allow angular to access the PHP output data
});
});
fetch.php
<?php
header('Access-Control-Allow-Origin: *'); // clientside(Node) <-> serverside(PHP)
$mysqli = new mysqli("localhost", "root", "", "storestuff");
if($mysqli->connect_error) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$query = "SELECT * FROM thestuff";
$theData = array();
if($result = $mysqli->query($query)) {
while($row = mysqli_fetch_array($result)) {
$theData[] = array(
'date'=>$row['date'],
'content'=>$row['content']);
}
echo json_encode($theData); // Echo the output for the controller to access
$result->free(); // Free the result set
}
else {
echo "0 results.";
}
$mysqli->close(); // Close the connection
?>
The problem with this code is that you have two different controllers, both with separate scopes. Inserting/updating the $scope.results object/array in one controller, will not update the other $scope; they are separate distinct scopes, both with a copy of the data.
Using two controllers looks correct in your use case. However you should be using a service to access your remote data. Check out this answer for some advice on this https://stackoverflow.com/a/20181543/2603735.
Using a service like in that answer, will allow you to store the array/object of remote data in one place, and reference the SAME object from both controllers. Therefore updating from one controller, will also update the other.
For anyone who will ever stumble on my question, I don't want to just leave my broken code there with no answer but neither can I edit the question and put in my answer cause that would defy the purpose of StackOverflow.
So here is my answer to my own question.
I had to make quite a few changes to what I had before. The biggest change by far, is how I handled the data that was returned by fetch.php.
Instead of just taking the output into $scope.results = response.data;, which would work fine if I wasn't dynamically adding to the database, but for this case, I ended up using a service. (Thanks #jayden-meyer for suggesting Angular services.)
The service allowed me to access the same array from my insertController and from my fetchController instead of having a copy of the same array in both controllers which was my problem.
No changes in the HTML code.
No changes to insert.php.
No changes to fetch.php.
insertController.js
I removed the extraneous GET request I had inside the .then method which was completely unneeded since I can just push to the existing array.
(Thanks #charlietfl for the tip)
Instead I added resultsService.addItem($scope.date, $scope.content); inside of the .then method.
I also added my service as an argument.
app.controller('insertController', function($scope, $http, resultsService) {
result.js
app.service('resultsService', function() {
var results = new Array();
var addItem = function(date, content) {
var obj = new Object();
obj["date"] = date;
obj["content"] = content;
results.push(obj);
}
var getItems = function() {
return results;
}
return {
addItem: addItem,
getItems: getItems
};
});
fetchController.js
var size = 0;
var count = 0;
app.controller('fetchController', function ($scope, $http, resultsService) {
$http.get('http://localhost/storestuff/fetch.php')
.then(function successCallback(response) {
size = (response.data).length;
while(count < size) {
var date = response.data[count].date;
var content = response.data[count].content;
resultsService.addItem(date, content);
count++;
}
size = 0;
count = 0;
$scope.results = resultsService.getItems();
});
});
I know I've asked this question before but I still need help with this, basically:
I have a booking grid as shown below which is on bookings.php
On this booking grid I have a dblClick event:
ondblClickRow: function(rowid)
{
rowData = $("#bookings").getRowData(rowid);
var brData = rowData['bookref'];
getGridRow(brData);
$("#cp-bookings-dialog").dialog({ hide: 'slide', height: 625, width: 733, title: 'Booking Reference: - '+ brData});
},
This also opens a Jquery Dialog window on bookings.php:
<div class="cp-tiles-wrapper-dlg">
<div class="cp-booking-info left">
<p class="pno-margin">Booking Date: <strong>Booking Reference is = <? echo BookingDocket::get_bookref(); ?></strong></p>
<p class="pno-margin">Return Date: <strong><? echo BookingDocket::get_bookdate(); ?></strong></p>
<p class="pno-margin">Journey: <strong></strong></p>
<p class="pno-margin">Passenger Tel: <strong></strong></p>
<p class="pno-margin">E-mail: <strong></strong></p>
</div>
</div>
Where brData is the 'Booking Reference' value that I want to use in my PHP script. At the moment this dblClick event is being sent to the following Ajax request:
function getGridRow(brData) {
$.ajax({
url: 'scripts/php/bootstrp/all.request.php',
type: 'POST',
data: {
fnme: 'getDGRow',
rowdata: brData,
id: null,
condition: null
},
dataType: 'text/xml',
timeout: 20000,
error: function(){
alert("It failed");
$('#cp-div-error').html('');
$('#cp-div-error').append('<p>There was an error inserting the data, please try again later.</p>');
$('#cp-div-error').dialog('open');
},
success: function(response){
// Refresh page
//response = brData;
//alert(response); <-- This alerts the correct Booking Reference value
}
});
Which gets sent to all.request.php
// Switch to determine method to call
switch ($_REQUEST['fnme']) {
case 'getDGRow':
header('Content-type: text/xml');
GetBookings::getGridRow($_REQUEST['rowdata']);
break;
And finally to the PHP script where I want to use this Jquery value:
class GetBookings {
public static function getGridRow($rowdata) {
$pdo = new SQL();
$dbh = $pdo->connect(Database::$serverIP, Database::$serverPort, Database::$dbName, Database::$user, Database::$pass);
try {
$query = "SELECT * FROM tblbookings WHERE bookref = '$rowdata'";
//echo $query; <-- this passes the correct Booking Reference to £rowdata
$stmt = $dbh->prepare($query);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_BOTH);
BookingDocket::set_id($row['id']);
BookingDocket::set_bookref($row['bookref']);
BookingDocket::set_bookdate($row['bookingdate']);
BookingDocket::set_returndate($row['returndate']);
BookingDocket::set_journeytype($row['journeytype']);
BookingDocket::set_passtel($row['passengertel']);
BookingDocket::set_returndate($row['returndate']);
$stmt->closeCursor();
}
catch (PDOException $pe) {
die("Error: " .$pe->getMessage(). " Query: ".$stmt->queryString);
}
$dbh = null;
}
}
?>
I'm not sure why, but this doesn't seem to be working. Basically at the time when the Jquery Dialog window is opened, $rowdata is null, but when I echo the query, it shows that $rowdata has the correct value.
I have tried putting the code for the jquery window into a seperate php file and in the sucess ajax script I have added the following:
$('#cp-bookings-dialog').load('bookings-dialog.php', function() {
alert('Load was performed.');
});
but this doesn't make any difference. I know all the code is correct because if I set $rowdata to 'BR12345' for example, it displays the values I need in the jquery booking dialog. What I believe needs to be done is for the PHP query to run after the value $rowdata has been passed to the PHP script.
Anybody got any idea of how I can do this?
You need to return a JSON encoded object from your PHP script to use in your pop up. Your echo call is evaluated before the AJAX call is made, and worse, it does not know about GetBookings state at all (the state is only valid for a single request).
And why is everying static? That looks like a bad software design.
Here is the form to have ajax check out user existence.
<!DOCTYPE html>
<html>
<head><title>Register new user!</title>
<script src="jquery-1.7.1.min.js"></script>
</head>
<body>
Username:
<input type="text" name="username" id="username"/><span id="user"></span><br/>
Password:
<input type="password" name="password" id="password"/><br/>
<input type="button" value="Register" name="submit" id="submit" onclick="register_user();"/>
</body>
<script>
function register_user()
{
$.ajax(
{
type:"POST",
data:username,
url:"userexists.php"
})
.fail(function()
{
$('#user').html("This user already exists");
}
);
}
</script>
</html>
And here is the userexists.php module
<?php
// connection to the db
define(IPHOST,"localhost");
define(DBPASSWORD,"");
define(DBUSER,"root");
define(DATABASE,"ajaxtest");
define(TABLENAME,"at");
$conn=mysql_connect(IPHOST,DBUSER,DBPASSWORD) or die(mysql_error());
mysql_select_db(DATABASE) or die(mysql_error());
$username=$_POST('username');
$sql="SELECT username FROM ".TABLENAME." WHERE username=".$username;
$query=mysql_query($sql);
if(0!=mysql_numrows($query))
{
//
}
else
{
}
?>
But I am stuck to really figure out how the ajax function actually works, what should I enter the blank field after I know that the entered username has been used, for example ? I don't understand ajax at all.
[UPDATE]
Thank you, I understand it now, I have got several answers, don't know which one to choose as the best reply. No option to choose all.
You have a lot of mistakes in your code, try codes below:
<!DOCTYPE html>
<html>
<head><title>Register new user!</title>
<script src="jquery-1.7.1.min.js"></script>
</head>
<body>
Username:
<input type="text" name="username" id="username"/><span id="user"></span><br/>
Password:
<input type="password" name="password" id="password"/><br/>
<input type="button" value="Register" name="submit" id="submit" onclick="register_user();"/>
</body>
<script>
function register_user()
{
$.ajax({
type: "POST",
data: {
username: $('#username').val(),
},
url: "userexists.php",
success: function(data)
{
if(data === 'USER_EXISTS')
{
$('#user')
.css('color', 'red')
.html("This user already exists!");
}
else if(data === 'USER_AVAILABLE')
{
$('#user')
.css('color', 'green')
.html("User available.");
}
}
})
}
</script>
</html>
And for your php code:
<?php
// connection to the db
define(IPHOST,"localhost");
define(DBPASSWORD,"");
define(DBUSER,"root");
define(DATABASE,"ajaxtest");
define(TABLENAME,"at");
$conn=mysql_connect(IPHOST,DBUSER,DBPASSWORD) or die(mysql_error());
mysql_select_db(DATABASE) or die(mysql_error());
$username = mysql_real_escape_string($_POST['username']); // $_POST is an array (not a function)
// mysql_real_escape_string is to prevent sql injection
$sql = "SELECT username FROM ".TABLENAME." WHERE username='".$username."'"; // Username must enclosed in two quotations
$query = mysql_query($sql);
if(mysql_num_rows($query) == 0)
{
echo('USER_AVAILABLE');
}
else
{
echo('USER_EXISTS');
}
?>
Since you're new to AJAX, let me try and help you a bit better with some explanations as we go.
AJAX stands for Asynchronous Javascript And XML. Using it, you can make a request to another page and have your original page behave differently according to the results returned by the other page.
So how is this useful? Well; You could set an onblur even on a 'username' field to check a remote script to see if a username is already in use. (Which you are already doing in your current setup. Good work!)
Firstly; the .fail() is telling your current page "If the ajax request fails, lets do this code". This is called a callback. A callback is a function of javascript code to execute when the asynchronous request is finished.
So what you want to actually do is use the .done() method. This tells your jQuery request "Hey, when you're done doing this request, do this chunk of code. While you're doing that, im going to sit here and handle anything else that happens".
So you can see there is a slight difference between using .done() and .fail(), however I can see how you can be easily confused with .fail() being new to ajax.
So lets get back to your current problem. Lets modify the ajax to something more like this:
$("#submit").click(function()
{
$.ajax({
type: "POST",
data: "username="+$("#username").val(),
url: "userexists.php"
})
.done(function(response){
$('#user').html(response);
});
});
What this does is bind an onclick handler for your submit button with the id "submit". So now you can remove onclick="register_user". Secondly, it says, "Hey webpage, go send userexists.php the username textbox value with the parameter name username. When you've finished that request, set the html of #user to the response.
So off it goes and does it.
Now your PHP file, you can do:
<?php
// connection to the db
define(IPHOST,"localhost");
define(DBPASSWORD,"");
define(DBUSER,"root");
define(DATABASE,"ajaxtest");
define(TABLENAME,"at");
$conn = mysql_connect(IPHOST,DBUSER,DBPASSWORD) or die(mysql_error());
mysql_select_db(DATABASE) or die(mysql_error());
$username = mysql_real_escape_string($_POST['username']); // Stop some MySQL injections
$sql="SELECT username FROM ".TABLENAME." WHERE username='$username'";
$query=mysql_query($sql);
if(mysql_numrows($query) == 0)
{
echo 'Username is available!'
}
else
{
echo 'Sorry, username is in use.';
}
?>
So once your script does its query, if it finds a result it will say in the HTML div "Username is available!". Otherwise, if it finds a match, it says "Sorry, username is unavailable".
Hope this helps you understand ajax a little better!
It's technically up to you. (For example) You could return a "1" for "user exists" and "0" for "user doesn't exist", or return a more detailed XML. The client app (Javascript) will read the returned result and print out an appropriate message to the user.
The .fail method should be used in case your function actually fails (server side error etc). So it doesn't seem appropriate for what you're trying to do. I would put in your ".done()" code a test of the returned values as described above and print out the correct message.
Javascript:
.done(function ( data ) {
if(data == "0")
alert("Your username is OK");
else
alert("Your username is already used");
});
PHP:
if(0!=mysql_numrows($query))
{
echo "0";
}
else
{
echo "1";
}
Function .fail in ajax is used when server return unexpected datas. But your php code dont return anything. Use something like this:
function register_user()
{
$.ajax(
{
type:"POST",
data:username,
url:"userexists.php"
})
.done(function(_return)
{
if(_return)
{
if(_return['status']=='yes')
{
$('#user').html(_return['msg']);
}
}
})
.fail(function());
}
And in php:
if(0!=mysql_numrows($query))
{
$return = array('status'=>'yes',
'msg'=>"User alredy exist");
echo json_encode($return);
return true;
}
Now you can add more conditions with many statuses and parse it in javascript.
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...
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.