Error in Delete Function in Table using JSON - php

I am writing some functions for the delete button in my table, and I can't get it right. I don't know where did I go wrong and I hope it makes sense.
Here's my script:
function Delete(str){
if (confirm('Are you sure you want to Delete this Information ?') == 1) {
xhttp.onreadystatechange=function(){
if (xhttp.readyState == 4 && xhttp.status == 200) {
if (xhttp.responseText == 1) {
alert('Information that have you selected has already been Deleted');
}else{
alert('Error: Function');
}
}
}
xhttp.open("POST","DeleteInformation.php",true);
xhttp.send("ID=" + str);
}
}
Here's the php file
DeleteInformation.php
<?php
include_once('config.php');
include_once('mysql.php');
$OpenMysql = new MySqlConnect(Host,User,Pass,Database);
$ID = $OpenMysql->DataFilter(isset($_REQUEST['ID'])?$_REQUEST['ID']:'');
$query = "Delete From items where itemcodes = '$ID'";
$result = $OpenMysql->ExecuteQuery($query);
if (!$result) {
echo "True";
}else{
echo "False";
}
?>

The issue I think was the Delete function was trying to call an undeclared and undefined object xhttp - this should be assigned with a new instance of XMLHttpRequest so your ajax function would never have sent any data. Of course, if you had defined xhttp=new XMLHttpRequest before the code you have shown then that comment would not necessarily hold true.
As you did not show how you call the function I have emulated how it might be called to test the functionality in the demo below.
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' ){
ob_clean();
/* randomly echo 1 or 0 to emulate both states */
echo rand(0,1);
exit();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>ajax php delete</title>
<script>
function Delete(str){
if( confirm('Are you sure you want to Delete this Information ?') == 1 ) {
/* This variable was not defined so you should have had an error, unless it was defined globally elsewhere */
var xhttp=new XMLHttpRequest();
xhttp.onreadystatechange=function(){
if ( this.readyState == 4 && this.status == 200 ) {
if ( this.responseText == 1 ) {
alert('Information that have you selected has already been Deleted');
}else{
console.error('Whoops - an error! %s',this.response);
}
}
}
xhttp.open( "POST", location.href, true );//"DeleteInformation.php"
xhttp.send( "ID=" + str );
}
}
document.addEventListener('DOMContentLoaded',function(){
Array.prototype.slice.call( document.querySelectorAll('input[data-name="delete"]') ).forEach(function(bttn){
bttn.onclick=function(event){
/* call the `delete` function */
Delete.call( this, this.dataset.id );
}.bind( bttn )
})
},false);
</script>
</head>
<body>
<form>
<?php
for( $i=1; $i<=10; $i++ ){
echo "
<input type='button' data-name='delete' data-id='$i' value='Delete'>";
}
?>
</form>
</body>
</html>
With regards to your PHP code - by default the include_path is probably set something like this .;C:\php5\pear which is not obviously useful as such. It is likely that you have set these files below (config,mysql) in the same working directory ( though that is a guess ) so unless you have modified the include path these calls below will fail. Personally I like to use a full path to included files whenever possible ~ such as require __DIR__ . '/somescript.php'
If however you have altered the include_path using set_include_path then ignore previous comment and instead fcus upn the javascript - if you do not see a network(xhr) request in the console then the ajax function is not being called...
<?php
/* this may or may not be correct the files location is unknown */
require __DIR__ . '/config.php';
require __DIR__ .'/mysql.php';
$id=!empty( $_POST['ID'] ) ? filter_input( INPUT_POST, 'ID', FILTER_SANITIZE_NUMBER_INT ) : false;
if( $id ){
/*
Host, User, Pass, Database
Are these defined as constants in config.php or mysql.php??
*/
$OpenMysql = new MySqlConnect( Host, User, Pass, Database );
$ID=$OpenMysql->DataFilter( $id ); //? no idea what this does
$query = "Delete from `items` where `itemcodes` = '$ID'";
$result = $OpenMysql->ExecuteQuery( $query );
echo $result ? 'true' : 'false';
}
?>
Hope you find the above useful in resolving your issue

Related

PHP: Class not found

I'm getting this annoying error and haven't been able to fix it yet.
<b>Fatal error: Class 'Console' not found in /home/serellyn/public_html/HEIM/php/nieuwbeheer/console_overview.php on line 45.</b>
Let's first start with the hierarchy which is like this.
index (main page)
console_overview (section of page)
include/connect (connect to DB)
include/console.class (the class)
The index.php requires the connect.php and the console.class.php and loads the console_overview.php. Here's the code:
<?php
require_once('include/connect.php');
require_once('include/console.class.php');
var_dump(file_exists('include/connect.php'));
var_dump(file_exists('include/console.class.php'));
?>
<div id="mainpage" class="main-container inner">
<?php
if (isset($_GET['page'])) {
$page = $_GET['page'];
} else {
$page = "console_overview";
}
?>
</div>
<!-- end: MAIN CONTAINER -->
<script>
var page = "<?php echo $page;?>";
$( "#mainpage" ).load( page + ".php" );
</script>
I've used var_dumps to check if both file exists (and they do). The console_overview.php loads correctly. Now in the console_overview.php I'm trying to get data from the Console class, as following:
<?php
foreach(Console::getAllConsoles() as $aConsole) {
$consoleID= $aConsole->getID();
$consoleName = $aConsole->getName();
$consoleHostname = $aConsole->getHostname();
$consoleGameID = $aConsole->getGameID();
$consolePowerState = $aConsole->getPowerState();
echo "<tr>";
echo "1";
}
?>
The error I'm getting is caused by the foreach... but I can't find out what's wrong...
The Console class looks like this (I'm pasting the most important parts, otherwise the code would be too long).
<?php
class Console{
private $ID, $hostname, $mac, $ip, $roomID, $gameID, $register, $powerState, $dateUpdated;
public function Console($tID, $tHostname, $tMac, $tIp, $tRoomID, $tGameID, $tRegister, $tPowerState, $tDateUpdated) {
$this->ID = $tID;
$this->hostname = $tHostname;
$this->mac = $tMac;
$this->ip = $tIp;
$this->roomID = $tRoomID;
$this->gameID = $tGameID;
$this->register = $tRegister;
$this->powerState = $tPowerState;
$this->dateUpdated= $tDateUpdated;
}
...
public static function getAllConsoles() {
$sql = "SELECT * FROM `console` ORDER BY `hostname` ASC";
$result = mysql_query($sql);
$theResults = array();
while ($row = mysql_fetch_array($result)) {
$theResults[] = new Console($row[0],$row[1],$row[2],$row[3],$row[4],$row[5],$row[6],$row[7],$row[8],$row[9],$row[10]);
}
return $theResults;
}
}
?>
So can anyone see what the problem is?
Thank you for your help.
Edit: O and yes, I know MySQL is deprecated and will change this whenever the issue of not finding the console is fixed =).
Your console_overview.php does not include the required files. When you make an AJAX call with JavaScript from the client it is a separate HTTP request to the server, so you have to add the require() call again there:
<?php
require_once('include/connect.php');
require_once('include/console.class.php');
foreach(Console::getAllConsoles() as $aConsole) {
$consoleID= $aConsole->getID();
$consoleName = $aConsole->getName();
$consoleHostname = $aConsole->getHostname();
$consoleGameID = $aConsole->getGameID();
$consolePowerState = $aConsole->getPowerState();
echo "<tr>";
echo "1";
}
?>

Why does this undefined error occur when storing the first number to a $_SESSION[] variable?

I'm making a mini shopping cart for my project. Im storing the number of items chosen by the user, I don't understand that when i add one to my session variable I always get this error on the first go
Undefined index: cart_1 in D:\wamp\www\MiniCart\cart.php on line 100
And when I add again or refresh the same page it works fine. Why could this error be coming up? I removed the +=1 from the statement and it worked fine, apparently there is no syntax error too.
Cart.php
<!DOCTYPE>
<html>
<head></head>
<body>
<?php
session_start();
//The page where to jump to after adding/editing cart.
$page = 'mini_cart_index.php';
$link = mysqli_connect("localhost","root","","cart");
if(mysqli_connect_errno())
{
echo "Error:".mysqli_connect_error();
echo "<br/>";
} else {
echo "Connected to SQL<br/>";
}
//==================================================
if(isset($_GET['add']))
{
$obt=$_GET['add'];
$quantity_limit = 'SELECT id,quantity FROM products WHERE id='.mysqli_real_escape_string($link,(int)$_GET['add']);
$quantity = mysqli_query($link,$quantity_limit);
while($quantity_row=mysqli_fetch_assoc($quantity))
{
if($quantity_row['quantity']!=$_SESSION['cart_'.$_GET['add']])
{
$_SESSION['cart_'.$_GET['add']]+='1';
}
}
/*
echo 'id='.$obt.' '.'next<br/>';
echo 'Now storing info into session variable and adding one<br/>';
echo $_SESSION['cart_'.$_GET['add']];
echo '<br/>';
echo 'info stored<br/>';
*/
}
//***************************************************
function products()
{
GLOBAL $link;
$get ="SELECT id,name,description,price FROM products
WHERE quantity > 0 ORDER by id ASC";
if($result=mysqli_query($link,$get))
{
echo "Data Selected to be displayed<br/>";
} else {
echo "Error:".mysqli_error($link);
}
if(mysqli_num_rows($result)==0)
{
echo "There are no products to display!<br/>";
} else {
while($get_row=mysqli_fetch_assoc($result))
{
echo '<hr/><br/>';
echo 'displaying data from database<br/>';
echo '==================================';
echo '<p>'.$get_row['name'].'<br/>'.
$get_row['description'].'<br/>'.
number_format($get_row['price'],2).
' Add'.'</p>';
echo '<hr/><br/>';
}
}
}
echo 'outside'.$_SESSION['cart_1'];
?>
</body>
</html>
Mini_cart_index.php
<?php require 'cart.php';?>
<!DOCTYPE>
<html>
<head>
</head>
<body>
<?php products() ?>
</body>
</html>
That code is filled with SQL injection vulnerabilities, you should use PDO and prepare your statements.
PHP is warning you because it has to read the current value and add to it, but the first time you try to access it doesn't exist.
You could suppress the warning with:
#$_SESSION['cart_'.$_GET['add']]+='1';
A better way to do it though would be checking if it exists first
$name = 'cart_'.$_GET['add'];
if(isset($_SESSION[$name]) {
$_SESSION[$name] = 1;
} else {
$_SESSION[$name] += 1;
}
The problem is caused by the fact that...
$var['abc'] += 1
...is the same as
$var['abc'] = $var['abc'] + 1
So if you've got a clean session and $var['abc'] doesn't exist, you're going to get a warning because you're trying to read a non-existant value in order to add 1 to it.
While it's true that 0 + 1 = 1
...what's actually happening here is undefined + 1 = 1 with a warning.
As other answers have mentioned - to fix the issue, you can explicitly check that the array index exists before trying to increment it.
I'd do that with the ternary operator like this:
$key = 'card_' . $_GET['add'];
$_SESSION[$key] = (isset($_SESSION[$key]) ? $_SESSION[$key] : 0) + 1;
This is effectively saying
$val = ($val if it exists, otherwise 0) + 1;
Change your if statement to check if it's empty too:
if (!isset($_SESSION['cart_'.$_GET['add']])) {
$_SESSION['cart_'.$_GET['add']] = 1;
} elseif ($quantity_row['quantity'] != $_SESSION['cart_'.$_GET['add']]) {
$_SESSION['cart_'.$_GET['add']] += 1;
}

Variable not passing through to javascript and php

Working on a like/dislike function for my blogpost site, and the variables won't flow through. I've stared at this for days, and cannot find the break as all of the code looks fine and I've included all the necessary pages containing varibales. Any insights?
This is the "button" I'm using for a "like" button:
Like <span id="likes" class="likereadout">' . $likes . '</span>
The id variable shows up correctly when I "inspect element", but won't pass through to the following Javafunction:
function like_add(postid) {
$.post('like_add.php', {postid:postid}, function(data) {
if (data == 'success') {
alert('Woohoo');
} else {
alert('I need sleep.');
}
});
}
The Javascript is supposed to pass the variable to like_add.php, which reads:
<?php
include 'init.php';
if (isset($_POST['postid']) && article_exists($_POST['postid'])) {
$postid = $_POST['postid'];
if (previously_liked($postid) === true) {
echo 'You\'ve already liked this!';
} else {
add_like($postid);
echo 'success';
}
}
?>
Which refs the following php functions included in the init.php file:
function article_exists($postid) {
$postid = (int)$postid;
return (mysql_result(mysql_query("SELECT COUNT('id') FROM 'blabbing' WHERE 'id' = $postid"), 0) == 0) ? false : true;
}
and:
function add_like($postid) {
$postid = (int)$postid;
mysql_query("UPDATE 'blabbing' SET 'likes' = 'likes' + 1 WHERE 'id'= $postid");
mysql_query("INSERT INTO 'likes' ('user_id', 'id') VALUES ($ip, $postid)");
}
Realllll new to all of this, so please go easy on me. Thank you so much for your help!
function article_exists($postid) {
$postid = (int)$postid;
return (mysql_result(mysql_query(
When you send AJAX data throught $.post, it have to be stringified:
$.post('like_add.php', JSON.stringify({postid:postid}), function(data) {

jquery ajax success function works only once

I'm trying to implement a form that utilizes jquery's post feature to dynamically update the database. What I'm realizing is that after the user clicks the "update" button, the success function is called back just fine with a "Update successful" message.
The issue I have for the stackoverflow world is why on subsequent clicks (w/o refreshing the page) I'm not getting this same success message. Also, ironically my database is being updated, so I know the AJAX call is going through.
I've posted my code below:
JS
var TEAM = {
update: function() {
var form_data = $('form').serialize();
$.ajax({
type: "POST",
url: "../manager/edit_team.php",
data: form_data,
error: function() {
$('#status').text('Update failed. Try again.').slideDown('slow');
},
success: function() {
$('#status').text('Update successful!');
},
complete: function() {
setTimeout(function() {
$('#status').slideUp('slow');
}, 3000);
},
cache: false
});
}
}
// jQuery Code for when page is loaded
$(document).ready(function()
{
$("#update").on("click", function() {
TEAM.update();
});
});
PHP (I welcome any other comments as well)
require '../includes/config.php';
include '../includes/header.html';
// autoloading of classes
function __autoload($class) {
require_once('../classes/' . $class . '.php');
}
// Site access level -> Manager
$lvl = 'M';
// Assign user object from session variable
if (isset($_SESSION['userObj']))
{
$manager = $_SESSION['userObj'];
}
else
{
session_unset();
session_destroy();
$url = BASE_URL . 'index.php';
ob_end_clean();
header("Location: $url");
exit();
}
// Establish database connection
require_once MYSQL2;
// Assign Database Resource to object
$manager->setDB($db);
// Authorized Login Check
if (!$manager->valid($lvl))
{
session_unset();
session_destroy();
$url = BASE_URL . 'index.php';
ob_end_clean();
header("Location: $url");
exit();
}
// Check for a valid game sch ID, through GET or POST:
if ( (isset($_GET['z'])) && (is_numeric($_GET['z'])) )
{
// Point A in Code Flow
// Assign variable from myteams-m.php using GET method
$id = $_GET['z'];
}
elseif ( (isset($_POST['z'])) && (is_numeric($_POST['z'])) )
{
// Point C in Code Flow
// Assign variable from edit_team.php FORM submission (hidden id field)
$id = $_POST['z'];
}
else
{
// No valid ID, kill the script.
echo '<p class="error">This page has been accessed in error.</p>';
include '../includes/footer.html';
exit();
}
$team = new ManagerTeam();
$team->setDB($db);
$team->setTeamID($id);
$team->pullTeamData();
$flag = 0;
echo $flag . "<br />";
// Confirmation that form has been submitted:
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{ // Point D in Code Flow
// Assume invalid values:
$tname = FALSE;
// Validate team name
if ($_POST['tname'])
{
$tname = $_POST['tname'];
}
else
{
echo '<p class="error"> Please enter a team name.</p>';
}
// Validate about team information
if ($_POST['abouttm'])
{
$abtm = trim($_POST['abouttm']);
}
else
{
$abtm = '';
}
// Check if user entered information is valid before continuing to edit game
if ($tname)
{
if($team->editTeam($tname, $abtm) == True)
{
echo '<p>Team was successfully updated</p>';
$flag = 1;
}
else
{
echo '<p>No changes were made</p>';
$flag = 2;
}
}
else
{ // Errors in the user entered information
echo '<p class="error">Please try again.</p>';
}
} // End of submit conditional.
echo $flag . "<br />";
// Point B in Code Flow
// Always show the form...
// Get team name attribute
$team->pullTeamData();
$teamname = $team->getTeamAttribute('tmname');
$about = $team->getTeamAttribute('about');
if ($teamname != '') // Valid user ID, show the form.
{
// Headliner
echo '<h2>Edit Team</h2>';
// Create the form:
echo '
<div id="EditTeam"></div>
<div id="Team">
<fieldset id="TeamDetails">
<legend>Edit Team</legend>
<form method="post" id="information">
<p id="status"></p>
<input type="hidden" name="z" value="' . $id . '" />
<p>
<label for="tname">New Team Name:</label><br/>
<input type="text" name="tname" id="tname" size="10" maxlength="45" value="' . $teamname . '" />
</p>
<p>
<label for="abouttm">Team Information:</label><br/>
<textarea id="abouttm" name="abouttm" cols="30" rows="2">"' . $about . '"</textarea><br />
<small>Enter something cool about your team.</small>
</p>
<p>
<input type="hidden" name="id" id="id">
<input type="button" value="update" id="update" />
</p>
</form>
</fieldset>
</div>';
}
else
{ //Not a valid user ID, kill the script
echo '<p class="error">This page has been accessed in error.</p>';
include '../includes/footer.html';
exit();
}
// Close the connection:
$db->close();
unset($db);
include '../includes/footer.html';
?>
You'll notice I also have a $flag defined to help with the debugging, but ironically it outputs 0 no matter the number of clicks to the "update" button. So there's no indication that the database is being updated, yet when I check the tables it certainly is.
I appreciate any help or pointers. Thanks,
#status message is not showing because you've hidden it by slideUp(), to show it again you need to slideDown() them.
success: function() {
$('#status').text('Update successful!');
-ADD-> $('#status').slideDown('slow');
},
complete: function() {
setTimeout(function() {
$('#status').slideUp('slow');
}, 3000);
Do it same way as you have done in error handler:
success: function(){
$('#status').text('Update successful!').slideDown('slow');
...
It seems that you know it already and just forgot it...
Other method that may be useful is stop() to make sure that previous animation is stopped when new one is starting., especially important when using long timeouts/animations.
(useful = can prevent other problems with visibility and makes sure that messages does not start jumping in and out)
(long = somewhere around 0,5-1,5 sec or more, if during this time can happen something else then it is long...)
For example, this will clear fx queue, finish running animation immediately and slideUp():
$('#status').stop(true, true).slideUp('slow');
You also asked suggestions for other parts of code
If you are using same code at least twice or if it is general method that could be reused make it reusable:
function redirect_to( $page ) {
session_unset();
session_destroy();
$url = BASE_URL . $page;
ob_end_clean();
header("Location: $url");
exit();
}
if ($condition == true) {
redirect_to( 'index.php' );`
}

PHP + Javascript parent function not getting called

Alright I've been trying to find an answer to this for hours already but I couldn't resolve it myself.
I'm trying to call a Javascript parent function from a PHP function, however, it is not getting called.
When using the onclick method onclick='parent.dosomething(); everything seems to work fine but if I try to call the function by echo'ing it out, it would just fail for some reason.
echo "<script>parent.reloadprofmessages();</script>"; //this is what is not getting called
Here's the PHP function:
function checkactivity($username)
{
//These are just queries being executed (irrelevant)
$querystats = "SELECT users.fullname, activity.id, activity.sender, activity.receiver, activity.type, activity.dateposted, activity.seen, activity.related FROM activity, users WHERE activity.receiver = '$username' && activity.seen = '0' ORDER BY id DESC LIMIT 1";
$resultstats = mysql_query($querystats);
$num_stats = mysql_num_rows($resultstats);
$rowactivity = mysql_fetch_assoc($resultstats);
//End of queries
if($num_stats > 0) //If there are registries
{
$user = $_SESSION['Username'];
$activity_date = $rowactivity["dateposted"];
$activity_type = $rowactivity["type"];
$activity_sender = $rowactivity["sender"];
$timeactivity = strtotime( "$activity_date" );
$actualtime = time();
$timetoseconds = $actualtime - $timeposted;
$timetominutes = floor($timepassedtoseconds/60);
if($timetominutes < 2)
{
if($activity_sender != $user)
{
if($activity_type == 1) //Messages
{
echo "<script>parent.reloadprofmessages();</script>"; //this is what is not getting called
}
}
}
}
}
And this is my Javascript function at the parent page:
function reloadprofmessages()
{
$('#friendrequests').load('showprofmessages.php?username=<?php echo $actualuser; ?>').fadeIn("slow");
} //refreshes messages
I pressed CTRL + Shift + I in Google Chrome to get to the developer tools, Network > page that does the request that calls the PHP function > Preview and this was what I received:
<script>parent.reloadprofmessages();</script>
However, the function is not getting called.
Resolving this would solve me a lot of problems, to me it is actually still a mystery to know why it doesn't work since it has worked in other cases.
Thank you for your help in advance.
It's not a good idea to fetch javascript and execute it with AJAX. What I would suggest is to firstly change your PHP to this:
if($activity_type == 1) //Messages
{
echo "1";
}
else {
echo "0";
}
Then change your Javascript to this:
function reloadprofmessages()
{
var can_reload = $.ajax({ url: "showprofmessages.php?username=<?php echo $actualuser; ?>" });
if (can_reload) {
parent.erloadprofmessages();
}
}
Hope that helps
Add the type attribute for script tag
echo "<script type='text/javascript' >parent.reloadprofmessages();</script>";
and remember to define the javascript function before this line
So here is what was wrong: (Showing errors)
function checkactivity($username)
{
//These are just queries being executed (irrelevant)
$querystats = "SELECT users.fullname, activity.id, activity.sender, activity.receiver, activity.type, activity.dateposted, activity.seen, activity.related FROM activity, users WHERE activity.receiver = '$username' && activity.seen = '0' ORDER BY id DESC LIMIT 1";
$resultstats = mysql_query($querystats);
$num_stats = mysql_num_rows($resultstats);
$rowactivity = mysql_fetch_assoc($resultstats);
//End of queries
if($num_stats > 0) //If there are registries
{
$user = $_SESSION['Username'];
$activity_date = $rowactivity["dateposted"];
$activity_type = $rowactivity["type"];
$activity_sender = $rowactivity["sender"];
$timeactivity = strtotime( "$activity_date" ); //$timeactivity was not being used
$actualtime = time();
$timetoseconds = $actualtime - $timeposted; //$timeposted doesn't even exist, in other words I wasn't even converting the $activity_date timestamp to time.
$timetominutes = floor($timepassedtoseconds/60);
if($timetominutes < 2)
{
if($activity_sender != $user)
{
if($activity_type == 1) //Messages
{
echo "<script>parent.reloadprofmessages();</script>"; //this was not the correct way of calling a function from the parent page.
}
}
}
}
}
About the Javascript function:
This is what I ended with:
var auto_refresh = setInterval(
function reloadstring()
{
$.get("checknewactivity.php?vprofile=<?php echo $actualuser; ?>", function(activity){
if (activity == 1)
{
$('#profcommentsdiv').load('showprofmessages.php?vprofile=<?php echo $actualuser; ?>').fadeIn("slow");
}
});
}, 1000); // refresh every 1000 milliseconds
And now it works, thank you for your help, I really appreciate it, and as usual, I always get to a safer solution after asking it here.

Categories