I am using jquery to feed variables to a php page.
I want the php to clear a table in the database, load new data based on the variables, query the new data and echo out results.
The problem is, the php doesn't seem to be clearing the table each time I hit the php page. When I feed two sets of variables to the php page, the same results appear for both queries. The results are a combination of what I want. What am I doing wrong, anyone know?
jquery:
$.ajax({
url: "php/getTotals.php",
method: "POST",
data: {year : strYear, race: 'USP', type: strType},
success: function(data) {
var objPrez = jQuery.parseJSON(data);
fillTotal(objPrez, tbl_prezresults);
},
error: function(jxhr, statusText, err) {
console.log(statusText + " " + err);
}
});
//get gov totals
$.ajax({
url: "php/getTotals.php",
method: "POST",
data: {year : 2010, race: 'GOV', type: strType},
success: function(data) {
var objGov = jQuery.parseJSON(data);
fillTotal(objGov, tbl_govresults);
},
error: function(jxhr, statusText, err) {
console.log(statusText + " " + err);
}
});
getTotals.php:
require_once ('constants_test.php');
$db = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (mysqli_connect_errno()) {
printf("Connect failed: %s", mysqli_connect_error());
exit;
}
if( $_POST) {
$type = mysqli_real_escape_string($db, $_POST['type']);
$year = mysqli_real_escape_string($db, $_POST['year']);
$race = mysqli_real_escape_string($db, $_POST['race']);
$db->query("delete from elections_temp");
$data = array();
$q = "INSERT INTO elections_temp (SELECT * FROM elections where electionOffice = '" . $race . "' AND electionYear = '" . $year . "' AND electionType = '" . $type . "')";
$db->query($q);
$q_sums = "select firstName, lastName, party, sum(votes) as totvotes from elections_temp group by lastName order by totvotes desc";
$result = $db->query($q_sums);
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
//Add this row to the reply
$data[] = $row;
}
echo json_encode($data);
$db->close();
} else {
echo "You shouldn't be here.";
}
What you are doing is the following:
2 ajax calls that call the php script at the same time (probably a delay of a few ms between them).
The server then does what you want it to do, but strange things happen because of your temp table that is created/truncated every request.
What happens is the following:
request1 enters
runs the php code
request2 enters
runs request2 code
request1run locks tem table in database and starts creating it and stuff
request2run wants to create the same temp tabel but can't because request1run is still doing stuff
request1run ends doing his stuff in the db temp table
request2run now does his thing with the temp table, delete all records and add stuff
request1run has to wait before he can select stuff from the temp table because request2run is still doing his business.
request2run finished creating the temp table and request1run can slect his data and return it to the client
request2run select data and returns it to the client
So, because you fire both ajax call at the same timen they end up messing with each other on the server.
Your server is probably not fast enough to handle request1 before request2 kicks in.
I think you do not need the extra table. You can all do it in one sql
$query = 'select firstName, lastName, party, sum(votes) as totvotes from elections
where electionOffice = "' . $race . '" AND electionYear = ' . $year . ' AND electionType = "' . $type . '"
group by lastName, firstName, party order by totvotes desc';
If performance is a problem, add an index to electionOffice, electionYear and electionType (all in one index).
Related
I am having a problem trying to get around a "parsererror" that is returned from my ajax request, despite a response in devtools which is an array of strings. I have a click event that makes an ajax request to pull in information from a database. The result in dev tools is:
1["1","admin","admin#admin.com","test","2017-01-11 00:00:00"]
I was expecting it to be a json object { }.
The code I wrote for the click event is:
$('#viewProfile').on('click', function() {
$.ajax({
type: 'GET',
url: 'api.php',
data: "",
cache: false,
dataType: 'json',
success: function(data) {
var id = data[0];
var name = data[1];
$('#userDetails').html("<p>ID: " + id + " Name: " + name + "</p>");
},
error: function(request, error) {
$('#userDetails').html("<p>There was a problem: " + error + "</p>");
}
});
});
The php I wrote for api.php
session_start();
echo $_SESSION['user_session'];
//DECLARE VARS FOR DB
$db_host = "localhost";
$db_name = "dbregistration";
$db_user = "root";
$db_pass = "";
$db_tablename = "tbl_users";
//CONNECT TO DB
include 'dbconfig.php';
$db_con = mysqli_connect($db_host,$db_user,$db_pass,$db_name);
$dbs = mysqli_select_db($db_con, $db_name);
//QUERY DB FOR DATA
$result = mysqli_query($db_con, "SELECT * FROM $db_tablename where user_id = '".$_SESSION['user_session']."' ");
$array = mysqli_fetch_row($result);
//RETURN RESULT
echo json_encode($array);
I have tried in api.php to use json_encode($array, JSON_FORCE_OBJECT) along with changing the datatype to HTML, which obviously did not work. In short, my goal was to be able to fire the click event, send an ajax request to retrieve information from the database, based on the user id then return that to the #userDetails id on the page. I am stuck trying to get around the array of strings that seems to be the roadblock for me.
Remove this line:
echo $_SESSION['user_session'];
and change this:
$array = mysqli_fetch_row($result);
to this:
$array = mysqli_fetch_assoc($result);
EDIT: you should also be checking for success/failure of your various db-related statements:
$db_con = mysqli_connect($db_host,$db_user,$db_pass,$db_name) or die("there was a problem connecting to the db");
$dbs = mysqli_select_db($db_con, $db_name) or die("Could not select db");
and also
$result = mysqli_query($db_con, "SELECT * FROM $db_tablename where user_id = '".$_SESSION['user_session']."' ");
if (!$result) {
die("query failed");
}
This needs to be removed echo $_SESSION['user_session'] it is getting returned to ajax call and because it is on json the return is incorrect.
I want to check if a user has favourited an item but I'm unsure how to return the result of a database query to ajax.
I will show different html depending on the result.
Php
$query = "SELECT itemID from favourites WHERE userid = '" . $user. "'";
$result = mysql_query($query);
echo json_encode($result);
Jquery
$.ajax({
url: "inc/functions.php",
type: "POST",
data: {--result--},
success: function () {
// if result found in database
$('favourite').hide();
// if result not found
$('favourite').show();
}
});
I can't figure out how to display $result in the jquery code.
Any help much appreciated.
$result in this case is a PHP object representing a result.
You will have to use a fetch() method in order to extract the result before sending it back to your JS.
See this link. There's a list of all fetch-family method right above the comments.
Also, you will need to make a connection with you database beforehand using mysqli_connect (or mysql_connect in your case).
As stated in the comments, you should however use mysqli* functions family instead of mysql*.
Thanks to the comments for info regarding mysqli. I updated the code and solved the ajax part.
For anyone else stuck, I got it working like this:
PHP
require ("../../connection.php");
$sql = "SELECT * FROM favourites WHERE userID = ? AND itemID = ?";
$user = $_POST['userID'];
$item = $_POST['itemID'];
$statement = $db->prepare($sql);
if($statement === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $db->error, E_USER_ERROR);
}
$statement->bind_param('ii',$user,$item);
$statement->execute();
$statement->bind_result($user,$item);
while($statement->fetch()){
echo 1;
}
$statement->close();
Jquery
$.ajax({
url: "inc/userList.php",
data: userList,
type: "POST",
success: function (result) {
if (result == 1){
$('#addItem').css('display', 'none');
$('#removeItem').css('display', 'inline-block');
} else {
$('#addItem').css('display', 'inline-block');
$('#removeItem').css('display', 'none');
}
}
});
<img id="image" src="jj.png" onclick="randomizeImage();"/>
<h2 id="Score" name="Score1">0</h2>
<script>
var counter=0;
function randomizeImage() {
counter++;
var test= document.getElementById('Score');
test.innerHTML= counter;
}
</script>
<?php
$con = mysql_connect("localhost","root");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("database", $con);
$user_Name = $_COOKIE["username"]; //i stored the username as a cookie and retrieved it here
echo $user_Name; //echo it so i can check if it is right
$New= $_POST["Score"]; //**this is the part which is undefined**
$sql = "UPDATE User SET Score = '$New' WHERE ID='$user_Name'";
if (!mysql_query($sql,$con))
{
die('Error please try again ' . mysql_error());
}
mysql_close($con)
?>
I have an image that whenever i click on it, it will call a function which will increase a counter by 1. This score will be reflected on the html side and increase whenever i click on the image. However now i want to bring this counter data into php where i can upload it onto a database where it matches the user's username which he/she entered in a previous phpfile. I cant bring the value of score over? It keeps saying undefined index.
I have two colums called ID and Score. ID is where i score the user's username and Score is the score from the counter. I want the Score to updated everytime the image is pressed with respect to the username.
Database name is :database
Table name is: User
Is there anyway to do this without AJAX?
You need to hook an ajax request to the randomizeImage() function. With the AJAX request, you can make a post request to the PHP page which you have created so it would save the score.
See AJAX
function randomizeImage() {
counter++;
var test= document.getElementById('Score');
test.innerHTML= counter;
$.post("yourphpfile.php", {score: counter}, function(result) {
//should be saved
}
}
This is the JS side. PHP side - you have to check if there is a POST request with the variable score.
<?php
if (isset($_POST['score'])) {
$score = intval($_POST['score']);
//check if user already has score.
$scoreQuery = "SELECT score FROM tbl WHERE username = '$username'";
//run the query, if user has score:
$query = "";
if (user has score already) {
$query = "UPDATE tbl SET score = score + $score WHERE username = '$username'";
} else {
$query = "INSERT INTO tbl (score, username) VALUES ($score, '$username');
}
//run the query
}
This is how you can send an ajax request to the server. Make sure to include jquery first.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
var counter=0;
function randomizeImage() {
counter++;
var test= document.getElementById('Score');
test.innerHTML= counter;
$.ajax
(
"ajax.php",
{
method: "POST",
data: { score: counter}
}
);
}
</script>
Next you have to put your PHP code into a separate file, I call it "ajax.php".
<?php
$score = filter_input(INPUT_POST, "score");
if (isset($score) && $score != "") {
$con = mysql_connect("localhost","root");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("database", $con);
$user_Name = $_COOKIE["username"]; //i stored the username as a cookie and retrieved it here
echo $user_Name; //echo it so i can check if it is right
$sql = "UPDATE User SET Score = '$score' WHERE ID='$user_Name'";
$result =mysql_query($sql) or die("could not update" . mysql_error);
if (!mysql_query($sql,$con))
{
die('Error please try again ' . mysql_error());
}
mysql_close($con)
}
?>
I want delete a record from database and to do it I want use ajax..
So I have a table where I put into last td this:
<input type='image' src='./img/delete.png' onClick='deleteUser(".$utentiIscritti[$i][0].");' />
this is my deleteUser function:
function deleteUser(id){
$.ajax({
type:"post",
url: "deleteUserAjax.php",
data: {'id':id},
success: function(data){
console.log("OK");
location.reload();
},
error: function(xhr, status, error){
alert(xhr+"\n\n"+status+"\n\n"+error);
console.log("KO");
}
});
}
And this is my php page to connect to db and delelte the record:
<?php
$USERDB = "u";
$PASSWORDDB = "p";
$NAMEDB = "d";
$queryDeleteUser = 'delete from user where id = "'.$_POST['id'].'"';
$conn = mysql_connect("localhost", $USERDB, $PASSWORDDB)
or die("Errore nella connessione al database: " . mysql_error());
mysql_select_db($NAMEDB) or die("Errore nella selezione del database: " . mysql_error());
mysql_query($queryDeleteUser) or die("Errore nella query: " . $queryDeleteUser . "\n" . mysql_error());
dbDisconnect($conn);
But I obtain always (from every ajax request) error:
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
iscritti.php:80
Why???
You can consider two solutions.
Your code is buggy. Try to execute it on it's own. Just call it in your browser and check the result!
You have specified a relational path for your script. url: "deleteUserAjax.php", try instead an absolute path and check the result (url: "http://yourdomain.com/deleteUserAjax.php")
Maybe make it more cleaner:
HTML part:
<input type='image' src='./img/delete.png' value='<?=$id?>'>
jQuery part:
$(document).ready(function(){
$("#delete").on("click", function(){
var data = $(this).val();
$.ajax({
method: "POST",
url: "page_you_handle_it.php?action=delete",
data: {'id':id}
}).done(function(data){
//here you get response of your delete function!
});
});
});
PHP part:
$host = "[HOST]"; //Like localhost
$user = "[USER]"; //Like root
$pass = "[PASS]"; //Like 123
$db = "[DB]"; //Like users
$con = mysqli_connect($host, $user, $pass, $db) or die ("Conntecting the Database gone wrong");
$id = $_POST['id'];
$query_str = "DELETE FROM user WHERE id = '$id'";
$query = mysqli_query($con, $query_str);
if (!$query) //Do not run the `$query` in the return parts because it already runs when you say `if (!$query)`
{
echo 'Delete gone wrong';
}
else
{
echo 'Delete succes!';
}
* Resolved *
I implemented SimpleCart(js) to my one project.
One can register and login.
Once logged in you can use the cart to purchase items.
I have one problem, because simplecart(js) saves the cart to localstorage, if you login with a other account. You see the same cart results.
Does anyone have a php sql solution for this, to store the cart results into sql for each individual session user?
I resolved this issue with this,
It's a basic technique, but it works perfectly for what I need, I'll still tweak the php to check if the cart item exists in the db, whether to update or create.
jQuery
$(".saveCart").click(function(){
$(".itemRow").each(function(){
var custId = "<?php echo $_SESSION['Username'] ?>";
var itemName = $(this).find(".item-name").text();
var itemPrice = $(this).find(".item-price").text();
var itemQty = $(this).find(".item-quantity").text();
var itemTotal = $(this).find(".item-total").text();
$.ajax({
// Enter below the full path to your "cart" php file
url: "cart.php",
type: "POST",
data: {custId: custId, itemName: itemName, itemPrice: itemPrice, itemQty: itemQty, itemTotal: itemTotal},
cache: false,
success: function (html) {
// If form submission is successful
if ( html == 1 ) {
}
// Double check if maths question is correct
else {
}
}
});
});
});
PHP
<?php
$con = mysql_connect("localhost","root","pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("test", $con);
$sql="INSERT INTO cart (Id, itemName, itemPrice, itemQty, itemTotal)
VALUES
('$_POST[custId]','$_POST[itemName]','$_POST[itemPrice]','$_POST[itemQty]','$_POST[itemTotal]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
if ($sql) { echo "1"; }
else {echo "2"; }
mysql_close($con);
?>
mysql_query("UPDATE table SET sessid = ".session_id()." WHERE user = ".$user_id);
Something like that?