Can not write to MySQL-DB with PHP triggered by JQuery - javascript

Hello there overflowers!
I´m new to asking on here,
but i´ve been reading a lot on here, which has helped me already.
This time though i am encountering a problem,
to which i can not seem to find a thread nor a solution.
So the following situation occured:
I have a frontend in which people can change the design to use by clicking on a button.
That does work quite well. But it should save the themename to database.
It says it does, but it does not - if that saving is triggered on the site with JS/JQuery.
It does though, if i trigger it manually with the PHP-file:
./lib/savetheme.php?user=username&theme=themename
If i trigger it via JS it goes through the php, which really echoes the needed TRUE.
But it does not save to database. It does not throw any errors (it would die - but it echoes true..).
So here comes the code...
common.php
<?php
function m($str) {
$str = mysql_escape_string($str);
return "'".$str."'";
}
?>
db-connect-data.php
<?php
$dbname = "dbname";
$dbuser = "dbuser";
$dbpw = "dbpw";
$dbhost = "localhost";
$dbport = "3306";
?>
db-connect.php
<?php
if (!mysql_connect($dbhost.":".$dbport, $dbuser, $dbpw)) {
die();
}
if (!mysql_select_db($dbname)) {
die();
}
?>
savetheme.php
require "./common.php";
require "./db-connect-data.php";
require "./db-connect.php";
if(isset($_GET)) {
$user = "";
$theme = "";
if($_GET['user'] != "") {
$user = $_GET['user'];
}
if($_GET['theme'] != "") {
$theme = $_GET['theme'];
}
$sql = "UPDATE users SET
theme = ".m($theme)."
WHERE username = ".m($user);
if(mysql_query($sql)) {
echo "TRUE";
} else {
echo mysql_error();
}
}
?>
profile.php
<?php
foreach (glob("./themes/*",GLOB_ONLYDIR) as $file) {
$output = str_replace("./themes/", "", $file);
echo '<button class="buttons themebuttons" id="'
.$output.'">'.$output.'</button>';
}
?>
<div class="ui-widget" id="savethemeok">
<br>
<div class="ui-state-green ui-corner-all">
<p>
Theme saved successfully!
</p>
</div>
</div>
<div class="ui-widget" id="savethemeerror">
<br>
<div class="ui-state-red ui-corner-all">
<p>
Error! Theme could not be saved!
</p>
</div>
</div>
main.js
$(document).ready(function() {
$(".buttons").button();
$(".themebuttons").click(function() {
var themename = $(this).attr("id");
var themepath = "./themes/" + themename + "/jquery-ui.css";
console.log("Saving new theme...");
$.get( "./lib/savetheme.php" , {
user: $("#loggeduser").attr("value"),
theme: "'" + themename + "'",
}, function(status) {
if(status == "TRUE") {
console.log("New theme: " + themename);
$("#theme").attr({href: themepath});
$("#savethemeok").show();
window.setTimeout(function() {
$("#savethemeok").fadeOut();
}, 2500);
} else {
console.log("Error: " + status);
$("#savethemeerror").show();
window.setTimeout(function() {
$("#savethemeerror").fadeOut();
}, 2500);
}
});
});
});
There is more code, i hope i got all the relevant code out,
but i do not think it will be any more overseeable
if i copy the almost 1000 lines of code not regarding this particular issue.
If needed i will do though.
I am happy and thankful with any suggestions, as i have already buried some time into that issue and seemingly i do not have any clue as to why it does not save to db when i trigger it via JS but works just fine when manually triggering it with the php...
I am sorry if there is a thread about this somewhere which i have missed out on.
If there is, please let me know. I did not find any though.
Then again, maybe I´m too stupid to look for it,
i did struggle a bit with putting my problem in words...
Thank you all in advance!

the problem is fixed.
i had changed the user variable to another user - so naturally it did not save to the user i was looking at.
im sorry to have alerted you.
thanks for viewing into it - and in the honor of Robin Williams: CARPE DIEM.

From what you've posted in the question, your columns theme and username appear to be of varchar type. Try and modify your query to the following:
$sql = "UPDATE users SET theme = '".m($theme)."' WHERE username = '".m($user)."'";

Related

server sent events unexpected stop

let me first say that I'm no expert in web development so I might have made a stupid mistake but no amount of googling seems to be helping. I need to have a single html page (preprocessed in php) to display occasional events fired by a "server" page residing on the same machine.
I've readapted the basic w3schools server sent events example as follows and it seemed to be working fine until last night, but today (still working when first tested) I added a simple table and a ref to an external (empty) js file to the html and events stopped being caught by the page. I decided to roll back to the working code but even that doesn't work anymore. I had to remove the files and restore from a backup!
I'm sure the sse.php code is being run since part of what it does is removing records from a sqlite3 database and that's happening.
Here's the code, I really hope you can help me because I really have no idea what's happening.
This was tested on Linux + Xampp + Firefox and sadly this is a mandatory combination, having it work under other conditions is not useful at the moment. (fyi: opening the mon.php page in Opera gave me a single event and then stopped working as well)
Thank you all.
mon.php
<?php
if ( ! isset($_GET['mon']) ) {
die('mon code missing');
}
?>
<html>
<head>
<script type="text/javascript">
var evtSourceUrl = "sse.php?mon=" + <?php echo '"'.$_GET['mon'].'"'?>;
if(typeof(EventSource) !== "undefined") {
var source = new EventSource(evtSourceUrl);
source.onmessage = function(event) {
document.getElementById("info").innerHTML += event.data + "<br>";
};
} else {
document.getElementById("info").innerHTML = 'sse not supported';
}
</script>
</head>
<body>
<p>
<span id="info"></span>
</p>
</body>
</html>
sse.php
<?php
function output_sse($msg) {
echo "data: " . $msg . "\n\n";
ob_end_flush();
flush();
}
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header('Connection: keep-alive');
$mon = null;
if ( isset($_GET["mon"]) ) {
$mon = $_GET["mon"];
} else {
output_sse('mon code missing');
die();
}
while ( true ) {
usleep(1000 * 100);
$db = new PDO("sqlite:ch.sqlite3");
if ( $db === false ) {
output_sse('err:PDO');
die();
}
$stmt_select = $db->query("SELECT * FROM CH WHERE IDMON='$mon';");
$stmt_delete = $db->prepare("DELETE FROM CH WHERE IDMON='$mon';");
$db->beginTransaction();
$res = $stmt_select->fetch();
$stmt_delete->execute();
$db->commit();
$db->close();
if ( strlen($res['TK']) > 0 && strlen($res['SP']) > 0 ) {
$msg = "$res['TK'] :: $res['SP']";
output_sse($msg);
}
}
?>
add.php (to add new records to be displayed - this works)
<?php
$mon = isset($_GET["mon"]) ? $_GET["mon"] : die ('mon code missing') ;
$tk = isset($_GET["tk"]) ? $_GET["tk"] : die ('tk code missing') ;
$sp = isset($_GET["sp"]) ? $_GET["sp"] : die ('sp code missing') ;
$db = new SQLite3('ch.sqlite3');
if ( $db === false ) {
die('Cannot open db');
}
$res = $db->exec("INSERT INTO CH('IDMON','TK','SP') VALUES('$mon','$tk','$sp');");
if ( $res != 1 ) {
echo 'insert failed';
}
if ( $db->close() === false ) {
die('Cannot close connection to db');
}
echo('ok');
?>
This seems to be a problem related to the PDO interface in the sse.php file. I replaced it with the SQLite3 class like the add.php file and everything started working fine. The transaction seemed to get stuck.

Issue with Captcha system on PHP, AJAX Contact form

In 2011, I bought a PHP contact form from codecanyon that uses AJAX to process the form. After reporting my problem to them today, they responded saying that they no longer offer support for their 'old' product (so much for the life time support they generally offer as a rule) ... so they aren't going to help me hence this post on SO.
I would say that this isn't a normal issue but I think it's very important that it gets sorted out - here it is (this is my email to the seller but does explain the problem):
=================
I have an unusual issue with your AJAX Contact Form (you're going to have to read carefully and slowly).
Okay everything works 100% fine BUT ... let me explain (basically this has everything to do with the Captcha and verification of it)
My website has many pages with your online form on each of those pages.
Now I also have a listings page that has links going to all of those pages with forms.
EXAMPLE:
Lets say I am on a listings page (a page with a whole load of links going to other pages) and I right click on Link A to open page A in a new tab ... and then I also right click on Link B to open page B in a new tab. Right, so we have the listings page (that's still opened in front of me) and those 2 other pages that opened up in new tabs (Page A and Page B) ... as explained above, both those pages has your online form.
Now, I fill in both forms and click submit.
The first page that I right clicked to open in a new tab (Page A) - that form's Captcha doesn't work even when I've verified it correctly... however the form's Captcha on Page B does work (like it should). Why is it that the Captcha on Page A (the first page I opened) doesn't work?
I get the feeling that in the whole verification system, because Page B was opened up last, the verification is taking that page's captcha code into account, using that captcha for verification (throughout the session surfing on my website) thus making the Captcha on the first opened page (Page A) to not work.
So what I did as an experiment:
I restarted and did the same thing again, IE: I right clicked Link A to open page A in a new tab ... and then I also right click on Link B to open page B in a new tab.
I filled in Page B's Captcha code in Page A's Captcha verification field and what do you know - there's a match!
So this is my problem because I know when some people surf internet (I do this all the time and maybe you do too), they like to right click links to open them in new tabs so that they can get back to them later after browsing the listings page. So the person may have 6 tabs open in the browser and each of those pages has your online form. If the user wants to submit each of those forms, then he/she will experience the exact problem I am reporting above. They will be able to send through 1 form (the last page that was opened in a new tab) but the other page's Captchas won't work unless they refresh the page ... but most people won't think to do that - instead, they will think somethings wrong with the my website - which I am afraid of.
Is there a solution to this?
I'm not even sure if you've noticed this before?
I hoped I've explained the situation clearly and I'd really appreciate it if you could assist.
=================
Now back to you. What's causing this?
There are 3 files needed for the form to work / process etc (I'm not including the CSS file in this post not the html for the form as I don't think it's necessary).
1) process.php
2) image.php (this is for the captcha)
3) ajax.js
PROCESS.PHP
<?php if (!isset($_SESSION)) session_start();
if(!$_POST) exit;
if (!defined("PHP_EOL")) define("PHP_EOL", "\r\n");
$address = "email#example.com";
$bcc = "email#example.com";
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$comments = $_POST['comments'];
if (isset($_POST['verify'])) :
$posted_verify = $_POST['verify'];
$posted_verify = md5($posted_verify);
else :
$posted_verify = '';
endif;
$session_verify = $_SESSION['verify'];
if (empty($session_verify)) $session_verify = $_COOKIE['verify'];
$error = '';
if(trim($name) == '') {
$error .= '<li>Your name is required.</li>';
}
if(trim($email) == '') {
$error .= '<li>Your e-mail address is required.</li>';
} elseif(!isEmail($email)) {
$error .= '<li>You have entered an invalid e-mail
address.</li>';
}
if(trim($phone) == '') {
$error .= '<li>Your phone number is required.</li>';
} elseif(!is_numeric($phone)) {
$error .= '<li>Your phone number can only contain digits
(numbers and no spaces).</li>';
}
if(trim($comments) == '') {
$error .= '<li>You must enter a message to send.</li>';
}
if($session_verify != $posted_verify) {
$error .= '<li>The verification code you entered is
incorrect.</li>';
}
if($error != '') {
echo '<div class="error_title"><h6><span>Attention!
</span> Please correct the errors below and try again</h6>';
echo '<ul class="error_messages">' . $error . '</ul>';
echo '<div class="close"></div>';
echo '</div>';
} else {
if(get_magic_quotes_gpc()) { $comments = stripslashes($comments); }
$e_subject = 'Booking / Enquiry';
$msg = '<html>
<body style="margin:0; padding:0;">
Name: '.$_POST['name'].'
Email: '.$_POST['email'].'
Contact Number: '.$_POST['phone'].'
Notes: '.$_POST['comments'].'
</body>
</html>';
$msg = wordwrap( $msg, 70 );
$headers = "From: $email\r\nBCC:{$bcc}\r\n" . PHP_EOL;
$headers .= "Reply-To: $email" . PHP_EOL;
$headers .= "MIME-Version: 1.0" . PHP_EOL;
$headers .= "Content-type: text/html; charset=utf-8" . PHP_EOL;
$headers .= 'Content-Transfer-Encoding: 8bit'. "\n\r\n" . PHP_EOL;
if(mail($address, $e_subject, $msg, $headers)) {
echo "<div class='success'>";
echo "<h6>Your Enquiry has been Successfully submitted. </h6>";
echo '<div class="close"></div>';
echo "</div>";
} else {
echo 'ERROR!';
}
}
?>
*Please note that in the process.php code above, I removed a function that seems to validate the email address field - reason why I didn't include it in the code above is because it was heavy with code (would take up a lot of space) and I don't think it's necessary to include
IMAGE.PHP
<?php if (!isset($_SESSION)) session_start(); header("(anti-spam-
content-
type:) image/png");
$enc_num = rand(0, 9999);
$key_num = rand(0, 24);
$hash_string = substr(md5($enc_num), $key_num, 5); // Length of
String
$hash_md5 = md5($hash_string);
$_SESSION['verify'] = $hash_md5;
setcookie("verify", $hash_md5, time()+3600, "/");
session_write_close();
$bgs = array("../../img/1.png","../../img/2.png","../../img/3.png");
$background = array_rand($bgs, 1);
$img_handle = imagecreatefrompng($bgs[$background]);
$text_colour = imagecolorallocate($img_handle, 108, 127, 6);
$font_size = 5;
$size_array = getimagesize($bgs[$background]);
$img_w = $size_array[0];
$img_h = $size_array[1];
$horiz = round(($img_w/2)-
((strlen($hash_string)*imagefontwidth(5))/2),
1);
$vert = round(($img_h/2)-(imagefontheight($font_size)/2));
imagestring($img_handle, $font_size, $horiz, $vert, $hash_string,
$text_colour);
imagepng($img_handle);
imagedestroy($img_handle);
?>
AJAX.JS
jQuery(document).ready(function() {
$('.advertform').submit(function() {
var action = $(this).attr('action');
var form = this;
$('.submit', this).attr('disabled', 'disabled').after(
'<div class="loader"></div>').addClass("active");
$('.message', this).slideUp(750, function() {
$(this).hide();
$.post(action, {
name: $('.name', form).val(),
email: $('.email', form).val(),
phone: $('.phone', form).val(),
comments: $('.comments', form).val(),
verify: $('.verify', form).val()
},
function(data) {
$('.message', form).html(data);
$('.message', form).slideDown('slow');
$('.loader', form).fadeOut('fast', function() {
$(this).remove();
});
$('.submit',
form).removeAttr('disabled').removeClass("active");
});
});
return false;
});
$('.message').on('click', function(){
$('.message').slideUp();
});
});
Looking at the code above, can anyone spot what could be causing this problem? I'm assuming this can has to do with the javascript?
The comments are correct, the validation is failing on some forms because the session only holds the value of the last captcha generated therefore making captchas open in other tabs invalid because their value in the session was overwritten. Because of this, anyone using the same or similar code has this problem.
You can solve it fairly simply by changing the session to store an array of codes instead of just one.
In image.php, change:
$_SESSION['verify'] = $hash_md5;
to:
if (!isset($_SESSION['verify'])) $_SESSION['verify'] = array();
$_SESSION['verify'][$hash_md5] = $hash_md5; // *explantion for this array key later
You can also get rid of the cookie that gets set for the captcha, session storage should be fine.
Then in your form processor, change:
if($session_verify != $posted_verify) {
$error .= '<li>The verification code you entered is incorrect.</li>';
}
to:
if(!array_key_exists($posted_verify, $session_verify)) {
$error .= '<li>The verification code you entered is incorrect.</li>';
}
This should allow you to have multiple forms open in multiple tabs and still be able to submit each one without getting the incorrect captcha error.
Also, another issue with this code is that it doesn't unset the session verify value after a successful post. This means a person could solve one captcha and submit your form an unlimited number of times re-using the old code as long as they don't access image.php again between submissions.
To fix this with the array version, you'll need to unset the session key after the captcha and form is processed.
unset($_SESSION['verify'][$posted_verify]); // remove code from session so it can't be reused
Hope that helps.
I have an idea. Store the captcha values in an array, and keep a counter; both stored in SESSION variables.
So in the form you put a hidden input, and set it to the index.
When we check for captcha, we compare $_SESSION['captcha'][$index] to $_POST['captcha'].
Any time you (the client) open a new window; $index is increased.
We pass that index to image.php through the url; example src="img.php?index=2"
Here is a concept; minimal code to accomplish this.
Open a couple of windows with this page. See what happens
img.php
<?php
session_start();
header("(anti-spam-content-type:) image/png");
$captcha_text = rand(0, 99999);
// we read a "index" from the URL, example: <img src="img.php?index=2">
$index = isset($_GET['index']) ? (int) $_GET['index'] : 0;
if( empty($_SESSION['captcha'])) {
$_SESSION['captcha'] = array();
}
$_SESSION['captcha'][$index] = $captcha_text;
// #see http://php.net/manual/en/function.imagestring.php , first example
$im = imagecreate(100, 30);
$bg = imagecolorallocate($im, 55, 255, 255);
$textcolor = imagecolorallocate($im, 0, 0, 255);
imagestring($im, 5, 0, 0, $captcha_text, $textcolor);
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
?>
index.php
<?php
session_start();
// we handle the POST
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_SESSION['captcha'])) {
if ($_SESSION['captcha'][ $_POST['index'] ] == $_POST['captcha']) {
echo '<h2>correct</h2>';
}
else {
echo '<h2>not correct</h2>';
}
echo '<a href="index.php">Back to form</form>';
// header('location: index.php');
exit;
}
// normal page, with form
if(isset($_SESSION['captcha_index'])) {// index
// set a new index
$_SESSION['captcha_index']++;
}
else {
$_SESSION['captcha_index'] = 0;
}
$captcha_index = $_SESSION['captcha_index'];
echo '
<img src="img.php?index=' . $captcha_index . '">
<form action="" method="post">
<input name="captcha">
<input name="index" type="hidden" value="' . $captcha_index . '">
<input type="submit" value="GO">
</form>
';
// we show what's happening. Obviously you don't want to print this after test phase
$captcha = isset($_SESSION['captcha']) ? $_SESSION['captcha'] : array();
echo '
<br>print_r of $_SESSION[captcha]
<pre>' . print_r($captcha, true) . '<pre>
';
?>

Ajax not working on IE

Got this website --> http://www.secureshop.gr/POOL/acrosshotels/website/
If you check on the left sidebar there is the "find a hotel" sidebar where when you choose location from the drop down menu, the Hotel menu changes the options. This works with ajax. The problem is that it's not working with all versions of IE. When you choose a destination, the hotel drop down menu is empty/blank.
The javascript code is this. Pretty simple and works onclick of the destinations options
<script type="text/javascript">
function selecthotel(str) {
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("hotelselection").innerHTML=xmlhttp.responseText;
}
}
if(str == 0) {
str = 0;
}
xmlhttp.open("GET","includes/ajaxlocationsearch.php?location="+str+"&language=<?php echo $language; ?>",true);
xmlhttp.send();
}
</script>
The ajax file is this
$language = $_GET["language"];
$location = $_GET['location'];
if($location == "0") {
$result = mysql_query("Select * from eshop_articles where
category='/WEBSITE/SEARCHENGINE/HOTELS' order by
appearance",$link_id);
}else {
$result = mysql_query("Select * from eshop_articles where
category='/WEBSITE/SEARCHENGINE/HOTELS' and
short_description='$location' order by appearance",$link_id);
} ?>
<option value="0"><?php $a = $language."_choose_hotel"; echo ${$a};
?></option>
<?php while($row = mysql_fetch_assoc($result)) { ?>
<option value="<?php echo $row['appearance']; ?>"><?php echo
$row['title']; ?></option>
<?php } ?>
Thank you in advance :)
I made some testing and I found out that your code had some issues with the structure. You should always have the code properly formatted in order to find errors and problems faster. I formatted your code and found some problems with nesting and your query.
I would also like to warn you that you had a pretty serious SQL injection problem, which I fixed in this code by using prepared statements and a small extra preg_replace to strip all unwanted characters from the query and table in general. You should totally go and learn a little bit more about preventing SQL injections. There are great topics here that are dedicated to the subject and I made a list of these articles to you:
stackoverflow.com - How can I prevent SQL injection in PHP
php.net - SQL Injection
Here is the code I formatted and fixed. I have tested it by using no parameter, an empty parameter, a value that does not exist in the database, and a value that does exist in the database. Each one returned the value accordingly: three first ones return null, while the real query returns true; in this case it returns "No hotels available" if none found, or a list of these hotels if found. If the database query fails, it will by default return null, and then return "No hotels found".
I am sorry for changing the code layout a little bit, feel free to edit it back as you like, that's up to you. I highly recommend proper formatting however (might have been because of your code editor as well).
index.php
<?php
$language = "en";
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Hotel Selection</title>
</head>
<body>
<select id="hotelselection">
<option value="null">No hotels available</option>
</select>
<script>
function selecthotel(str) {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("hotelselection").innerHTML = xmlhttp.responseText;
}
}
if (typeof(str) == "undefined" || str == null) {
str = "";
}
xmlhttp.open("GET", "run.php?location=" + str + "&language=<?php echo($language); ?>", true);
xmlhttp.send();
}
selecthotel();
</script>
</body>
</html>
run.php
<?php
$phrases = array(
"en_error_db" => "No hotels available...",
"en_choose_hotel" => "Choose a hotel..."
);
$link_id = mysqli_connect("localhost", "", "", "");
if (mysqli_connect_errno($link_id)) {
die("Error occurred when attempting to connect to database (" . mysqli_connect_errno() . ": " . mysqli_connect_error() . ").");
error_log("Error occurred when attempting to connect to database (" . mysqli_connect_errno() . ": " . mysqli_connect_error() . ").");
exit(1);
}
$language_raw = isset($_GET["language"]) ? $_GET["language"] : "en";
$location_raw = isset($_GET['location']) ? $_GET["location"] : "";
$language = preg_replace("/[^\w.-]/", "", $language_raw);
$location = preg_replace("/[^\w.-]/", "", $location_raw);
if (empty($location)) {
$query = "SELECT * FROM `eshop_articles` WHERE `category` = '/WEBSITE/SEARCHENGINE/HOTELS' ORDER BY `appearance` ASC";
}else{
$query = "SELECT * FROM `eshop_articles` WHERE `category` = '/WEBSITE/SEARCHENGINE/HOTELS' AND `short_description` = ? ORDER BY `appearance` ASC";
}
if ($stmt = mysqli_prepare($link_id, $query)) {
if (!empty($location)) {
mysqli_stmt_bind_param($stmt, "s", $location);
}
mysqli_stmt_execute($stmt);
// Thanks to Bruce Martin on php.net for the SELECT * via _fetch (http://www.php.net/manual/en/mysqli-stmt.fetch.php#107034)
$metaResults = mysqli_stmt_result_metadata($stmt);
$fields = mysqli_fetch_fields($metaResults);
$statementParams = "";
foreach ($fields as $field) {
$statementParams .= (empty($statementParams) ? "\$column['" . $field->name . "']" : ", \$column['" . $field->name . "']");
}
$statment = "\$stmt->bind_result($statementParams);";
eval($statment);
print('<option value="0">' . $phrases[(isset($phrases[$language . "_choose_hotel"]) ? $language : "en") . "_choose_hotel"] . '</option>');
while (mysqli_stmt_fetch($stmt)) {
print('<option value="' . $column['appearance'] . '">' . $column['title'] . '</option>');
}
exit(1);
}else{
print('<option value="0">' . $phrases[(isset($phrases[$language . "_choose_hotel"]) ? $language : "en") . "_error_db"] . '</option>');
error_log("The script was unable to prepare a MySQLi statement (" . $query . ").");
exit(1);
}
?>
I switched over to MySQLi database extension instead of your deprecated MySQL extension. It should no longer return PHP errors over PHP error logs. I highly recommend switching to MySQL PDO if just possible. It's very simple, easy and works a lot better in my opinion!
Also, a note on your XMLHttpRequest/ActiveXObject usage: if you want to be able to support IE 5, create a class for that and load the script if the client is using that browser, otherwise use jQuery Ajax, which is very easy to use and you will not need to worry about query strings or so. The reason for having the ActiveXObject script out there, is because jQuery is not supported on IE 5, which is a common browser despite the known security issues. IE 5 is used by old computers, some banks, offices and other businesses that have not looked into the security details.
Hopefully this helped you.
Ajax-requests are cached in Internet Explorer. Try to delete the cache and then add a random parameter to the request-URL:
var url = "http://example.com/ajax.php?random="+new Date().getTime();
You shouldn't reinvent the wheel, there are some mature cross-browsers solutions out there already.
You should try using jQuery library and it's ajax method.
https://api.jquery.com/jQuery.ajax/
If you don't want to use a library you can find some solutions to your problem already, it involves creating different types of objects for IE:
http://www.quirksmode.org/js/xmlhttp.html
Internet Explorer caches content a lot, so you might need to force it to grab new data instead of taking it from the cache. You can add a GET parameter with a timestamp which is generated client side to the URL to which you're pointing.
In jQuery you can simply do it like this:
jQuery.ajax({
type: "GET",
url: "http://example.com/",
cache: false,
success: function (data) {
// do something here
}
});
Without jQuery you would need to add it manually to the url:
var url = "http://example.com" + "?_=" + (newDate()).getTime();

PHP / Ajax : How to show/hide DIV on $_SESSION variable value?

I have searched many, many topics on the Net discussing about session variables and how to get them from Javacript through Ajax. However, though I have been able to do so, this doesn't completely solve my problem.
Objective
To provide online inventory management online.
Constraints
Only authenticated users can manage the online inventory
Inventory management controls are hidden from an unauthenticated user
Each sections must be independently informed of the authentication in order to show/hide their controls accordingly
Code Samples
authenticate.php
project.js
index.php
atv.php
atv-inventory-list.php
sectionhandler.php
index.php
<?php session_start(); ?>
<html>
...
<div id="newAtvDialog" title="Input information on the new ATV">
<form id="newAtvAjaxForm" action="addNewAtv.php" method="post">
...
</form>
</div>
<div id="section">
<$php echo file_get_contents("inventory-sections.html"); ?>
</div>
...
</html>
authenticate.php
<?php
require_once "data/data_access.php";
$userName = "";
$password = "";
if (isset($_REQUEST["userName"])) $userName = $_REQUEST["userName"];
if (isset($_REQUEST["password"])) $password = $_REQUEST["password"];
$isAuthentic = isAuthenticUser($userName, $password);
$_SESSION["isAuthentic"] = $isAuthentic;
echo $isAuthentic;
// I try to use the below-written function where ever I need to show/hide elements.
function isCurrentUserAuthenticated() {
return isset($_SESSION["isAuthentic"]) && $_SESSION["isAuthentic"];
}
?>
project.js
$(document).ready(function() {
$("#newAtvDialog").dialog({
autoOpen: false,
closeOnEscape: true,
modal: true,
width: 1000
});
$("#newAtvAjaxForm").ajaxForm(function(data) {
$("#newAtvDialog").dialog("close");
$("#section").load("sectionhandler.php?section=atv&type=-1&make=0&year=0&category=0", function(event) { $("button").button(); });
});
});
atv.php
<div id="newAtvButton"> <!-- This DIV is to be hidden when not authenticated -->
<button id="addNewAtvButton">Add New ATV</div>
</div>
<div id="criterion">
...
</div>
<div id="atv-inventory">
<?php include ('atv-inventory-list.php'); ?>
</div>
atv-inventory-list.php
<?php
$type = -1;
$make = 0;
$year = 0;
$category = 0;
if (isset($_REQUEST["type"])) $type = $_REQUEST["type"];
...
$atvs = getAllAtvs($type, $make, $year, $category);
foreach ($atvs as $value=>$atv):
?>
<div class="inventory-item">
<img src="<?php echo utf8_decode($atv->getPathToImage())">
<div class="item-title">
...
</div>
<div id="commands">
<!-- This is the way I have tried so far, and it doesn't seem to work properly. -->
<button id="removeAtvButton"
class="<?php echo isCurrentUserAuthenticated() ? 'show' : 'hide'; ?>">
Remove ATV
</button>
</div>
</div>
sectionhandler.php
$section = "";
if (isset($_REQUEST["section"])) $section = $_REQUEST["section"];
$type = -1;
$make = 0;
$year = 0;
$category = 0;
// getting values from $_REQUEST[]
$activatedSection = "";
switch($section) {
case "atv": $activatedSection = "atv.php";
...
}
$file = $url.raw_url_encore($activatedSection);
include $file;
Supplementary thoughts
I thought of setting a boolean session variable which would expire after about 20 minutes of inactivity from the user, forcing him to log in again.
I know I shan't use passwords stored in the database. This is the first step of the authentication within this site which I shall put online pretty soon, as the client is going to ask for delivery any time soon. Encrypted passwords will be the next step. But first, I need the show/hide feature to work properly.
I have also thought about cookies, and being quite new to web development, I ain't quite sure what would be the best approach. As far as I'm concerned, the simplest the best, as long as it implies a minimum of security. This is not the NASA site after all! ;-)
Thanks everyone for your inputs! =)
It's an idea, but you can work on/from it;
actionURL is a php file where you can check if the user is logged in with a valid session.
ajaxSession function returns true or false if the user is logged.
Then you can call this function every X seconds/minutes to control if the session still going.
window.setInterval(function(){
// call your function here
if(ajaxSession(actionUrl)){
//return true, user logged, append/show protected divs.
}else{
//return false, remove/hide protected divs and ask user to log.
}
}, 5000); //every 5 seconds.
ajaxSession function:
function ajaxSession(actionUrl) {
var sessionOK= false;
$.ajax({
async: false,
url: actionUrl,
success: function(msg) {
// check the return call from the php file.
if(msg== 'OK'){
sessionOK = true;
}else{
sessionOk = false;
}
}});
return sessionOK;
}
EDIT
I will add an example code for the actionUrl, that will return if the session is isset or not to the ajaxSession function:
<?php
session_start();
// $_SESSION['reg'] is true when the user is logged in.
if($_SESSION['reg'] == true){
echo 'OK';
}else{
echo 'NO';
}
?>
Remember to check in the ajaxSession function the result of the Ajax call. If it's Ok, then sessionOk = true, if not, sessionOk = false.

AJAX to call PHP file which removes a row from database?

Alright, so I asked a question yesterday regarding how to save the blog posts that a user makes. I figured out the database side of it, and that works fine. Now, I want to REMOVE a blog post based after clicking an onclick button. Through my hours of digging through the web, I've found calling an jQuery AJAX function is the best way to go about it. I've been tooling around with it, but I can't get this working.
Blog code retrieved from database in blog.php:
$connection = mysql_connect("...", "...", "...") or die(mysql_error());
$database = mysql_select_db("...") or die(mysql_error());
$query = mysql_query("SELECT * FROM template") or die(mysql_error());
$template = mysql_fetch_array($query);
$loop = mysql_query("SELECT * FROM content ORDER BY content_id DESC") or die (mysql_error());
while ($row = mysql_fetch_array($loop))
{
print $template['Title_Open'];
print $row['title'];
print '<button class="deletePost" onClick="deleteRow(' . $row['content_id'] . ')">Remove Post</button>';
print $template['Title_Close'];
print $template['Body_Open'];
print $row['body'];
print $template['Body_Close'];
}
mysqli_close($connection);
This creates the following HTML on home.php:
<div class="blogtitle" class="post3">Title
<button class="deletePost" onClick="deleteRow(3)">Remove Post</button></div>
<div class="blogbody" class="post3">Content</div>
Which should call my remove.js when button is clicked (This is where I start to lose what I'm doing):
$function deleteRow(id){
$.ajax({
url: "remove.php",
type: "POST",
data: {action: id}
});
return false;
};
Calling remove.php (No idea what I'm doing):
$con=mysqli_connect("...","...","...","...");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$id = $_POST['action'];
$query = mysql_query("DELETE FROM content WHERE content_id=$id") or die(mysql_error());
My goal here is to REMOVE the row with the ID from the table which would in turn remove the blog post entirely since it won't see the row when it loops through the database table.
Any ideas?
Thanks for your help,
Kyle
couple of issues in your original code: the functions in Jquery shouldn't use a $ sign at the beginning and since you need to pass a single value I would use the query string rather than the POst, and instead of calling the "die" in php I would use the affected rows to return the callback of whether or not the value was deleted. But this is just my approach, there other ways I'm sure.
Here are little improvements in you code:
//HTML
<div class="blogtitle" class="post3">Title
<button class="deletePost" data-item="3" >Remove Post</button></div>
<div class="blogbody" class="post3">Content</div>
//JQUERY
jQuery(document).ready(function($) {
$('button.deletePost').each(function(){
var $this = $(this);
$this.click(function(){
var deleteItem = $this.attr('data-item');
$.ajax({url:'remove.php?action='+deleteItem}).done(function(data){
//colect data from response or custom code when success
});
return false;
});
});
});
//PHP
<?php
$id = $_REQUEST['action'];
$query = mysql_query('DELETE FROM content WHERE content_id="'.$id.'"');
$confirm = mysql_affected_rows() > 0 ? echo 'deleted' : echo 'not found or error';
?>
Hope this sample helps :) happy coding !
i hope this should help you i used this to remove items from my shopping cart project.
$(".deleteitem").each(function(e) {
$(this).click(function(e) {
$.post("library/deletefromcart.php",{pid:$(this).attr('prodid'), ajax:true},function(){
window.location.reload()
})
return false;
});
});

Categories

Resources