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

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.

Related

ajax request makes page lag

I have this ajax request code
function hehe2(){
var a = $(".film2numb").val();
return $.ajax({
type : "GET",
url : "php/controller1.php?page=semuafilm",
data : "data="+a,
cache: false,
success: function(data){
$('.semuafilm').load('php/film.php');
},
});
}
and it requests this php code, basically it prints out HTML data from SQL
<?php
$indicator = $_SESSION['p'];
if ($indicator == 'filmbaru') {
# code...
$batas = $_SESSION['a'];
if (!$batas) {
$batas = 1;
}
if ($batas>1) {
$batas = $batas * 8;
}
include('connect.php');
$queryfilm = "select * from tb_film order by film_year desc, film_id desc limit $batas ,8";
$exec = $conn->query($queryfilm);
while ( $f = $exec->fetch_assoc()) {
$tn = str_replace(" ","-",$f['film_name']) ;
?>
<div class='col l3 m3 s6 itemovie'><div><img src="images/dum.jpg" class="lazy" data-original='http://www.bolehnonton.com/images/logo/<?php echo $f["film_logo"]; ?>' width="214" height="317"><div><div><div><p><b><?php echo $f['film_name']; ?></b></p><p>IMDB Rating</p><p><?php echo $f['film_genre']; ?></p><p class='center-align linkmov'><a class='dpinblock browntex' href='?page=movie&filmname=<?php echo $tn; ?>'>PLAY MOVIE</a></p><p class='center-align linkmov'><a class='dpinblock' href=''>SEE TRAILER</a></p></div></div></div></div></div>
<?php
}
?>
and here is the controller
<?php
session_start();
$a = $_GET['data'];
$p = $_GET['page'];
$g = $_GET['genre'];
$_SESSION['a'] = $a;
$_SESSION['p'] = $p;
$_SESSION['g'] = $g;
?>
My question is why every time I click button that binded to the hehe2() function (4-5 times, which requested a lot of images) the page get heavier as I click incrementally(laggy, slow to scroll), is there a way to make it lighter, or is there a way to not store image cache on page or clear every time I click the button that binded to hehe2() function?
I am not sure that my advice will be helpful, I will just share my experience.
First of all you should check your binding. Do you bind click trigger only once?
Sometimes function binds multiple times and it can slow down the page.
You can put code below inside function and check the console
console.log("Function called");
If everything is fine from that point and function fires only once - I would recommend you to change flow a little bit. Is it possible to avoid many clicks in a row? If it is not big deal - you can disable button on click, show loader and enable button when AJAX request is completed. This approach will prevent from making multiple requests at once at page will be faster.

Trying to load a response sheet from php in the same page

I'm trying to load a response from the php onto the same page. My Client side html looks like this.
<p>
<script type="text/javascript">// <![CDATA[
function sendForm() {
var dataSend = "?ClientName=" + $("#ClientName").val();
$.post("AddClient.php", dataSend, function(data) {
$("#responseDiv").html(data);
});
// ]]></script>
</p>
<div id="responseDiv"> </div>
<form action="AddClient.php" onsubmit="sendForm()">
<h1>Client Wizard <span>Please fill all the texts in the fields.</span></h1>
<label> <span>Client Name :</span> <input id="ClientName" type="text" name="ClientName" /> </label> <span> </span> <input class="button" type="Submit" value="Send" />
</form>
My Server side php looks like this:
<?php
$dbhost='127.0.0.1';
$dbuser='name';
$dbpass='password';
$dbname='dbname';
$conn=mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
if(!$conn)
{
die('Could not connect:'.mysqli_connect_error());
}
$client=$_REQUEST["ClientName"];
$retval=mysqli_query($conn,"INSERT into client (clientid,clientname) VALUES (NULL,'$client')");
if(!$retval)
{
die('Could not add client:'.mysql_error());
}
$display_string="<h1>Client Added Successfully</h1>";
echo $display_string;
mysqli_close($conn);
?>
Unfortunately not only is the response being shown in anew html page, Its not accepting any name typed in the form. When I check the sql table the Column has a blank entry under it. I have not been able to figure out where I'm going wrong. Any help would be really appreciated.
All right. Your code have some room for improvement, but it's not an endless thing.
I saw somebody mention sanitization and validation. Alright, we got that. We can go in details here
This is how I will restructure your code using some improvements made by Samuel Cook (thank you!) and added a lot more.
index.html
<p>
<script type="text/javascript">// <![CDATA[
function sendForm() {
var dataSend = {clientName: $('#clientName').val()}
$.post("AddClient.php", dataSend, function(data) {
$('#responseDiv').html(data);
});
return false;
}
//]]>
</script>
</p>
<div id="responseDiv"></div>
<form action="AddClient.php" onsubmit="sendForm(); return false;">
<h1>Client Wizard <span>Please fill all the texts in the fields.</span></h1>
<label><span>Client Name :</span><input id="clientName" type="text" name="clientName"/><span></span><input type="submit" class="button" value="Send"></label>
</form>
Notice change in an input id and input name - it's now start with a lower case and now clientName instead of ClientName. It's look a little bit polished to my aesthetic eye.
You should take note on onsubmit attribute, especially return false. Because you don't prevent default form behavior you get a redirect, and in my case and probably your too, I've got two entries in my table with a empty field for one.
Nice. Let's go to server-side.
addClient.php
<?php
$dbhost = '127.0.0.1';
$dbuser = 'root';
$dbpass = '123';
$dbname = 'dbname';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if (!$conn) {
die('Could not connect: ' . mysqli_connect_error());
}
$client=$_REQUEST["clientName"];
$client = filter_var($client, FILTER_SANITIZE_STRING);
if (isset($client)) {
$stmt = $conn->prepare("INSERT into client(clientid, clientname) VALUES (NULL, ?)");
$stmt->bind_param('s', $client);
$stmt->execute();
}
if (!$stmt) {
die('Could not add client:' . $conn->error);
}
$display_string = "<h1>Client $client Added Successfully</h1>";
echo $display_string;
mysqli_close($conn);
?>
That is going on here. We are using PHP filters to sanitize our incoming from somewhere string.
Next, we check if that variable $client even exist (you remember that twice sended form xhr? Double security check!)
Here comes a fun part - to protect our selves even more, we start using prepared mySQL statements. There is no way someone could SQL inject you somehow.
And just check for any errors and display it. Here you go. I've tested it on my machine, so it works.
Forms default behavior is to redirect to the page given in the action attribute (and if it's empty, it refreshes the current page). If you want it to make a request without redirecting to another page, you need to use Javascript to intercept the request.
Here's an example in jQuery:
$('form').on('submit', function(e) {
e.preventDefault(); // This stops the form from doing it's normal behavior
var formData = $(this).serializeArray(); // https://api.jquery.com/serializeArray/
// http://api.jquery.com/jquery.ajax/
$.ajax($(this).attr('action'), {
data: formData,
success: function() {
// Show something on success response (200)
}, error: function() {
// Show something on error response
}, complete: function() {
// success or error is done
}
});
}
Would recommend having a beforeSend state where the user can't hit the submit button more than once (spinner, disabled button, etc.).
First off, you have a syntax error on your sendForm function. It's missing the closing bracket:
function sendForm() {
//...
}
Next, You need to stop the form from submitting to a new page. Using your onsubmit function you can stop this. In order to do so, return false in your function:
function sendForm() {
//...
return false;
}
Next, you aren't actually sending any POST data to your PHP page. Your second argument of your .post method shouldn't be a query string, but rather an object (I've commented out your line of code):
function sendForm() {
var dataSend = {ClientName:$("#ClientName").val()}
//var dataSend = "?ClientName=" + $("#ClientName").val();
$.post("AddClient.php", dataSend, function(data) {
$("#responseDiv").html(data);
});
return false;
}
Lastly, you have got to sanitize your data before you insert it into a database. You're leaving yourself open to a lot of vulnerabilities by not properly escaping your data.
You're almost there, your code just need a few tweaks!

POST session variables to a relational database with ajax

I am trying to add some data to a relational database, and would like the session_user_id to be the foreign key for that database. When a user clicks a button, I want to make a database entry with the session_user_id and some other information I have POSTed to the page. My ajax posts to the php webpage page which it is run on (meaning all my scripts are on the same page)
I am currently getting a Uncaught ReferenceError: $sess_user_id1 is not defined. The jquery is firing. While I would love to get the undefined variable fixed, overall this does not seem like a very direct way to to this, and has added a bunch of confusing variables, when all the variables I need were already in my PHP statement. Is there any way to trigger the PHP entry without going through ajax and having to define the variables again?
Here is my php, which is at the header which is on the same page as my JS and HTML:
<?php
$markerid = $_POST["id"];
$name = $_POST["name"];
$type = $_POST["type"];
$point = $_POST["point"];
$lat2 = $_POST["lat"];
$lng2 = $_POST["lng"];
$locationdescription = $_POST["locationdescription"];
$locationsdirections = $_POST["locationdirections"];
session_start();
if (!isset($_SESSION['sess_user_id']) || empty($_SESSION['sess_user_id'])) {
// redirect to your login page
exit();
}
$sess_user_id1 = $_SESSION['sess_user_id'];
if ((isset($_POST['usid'])) && (isset($_POST['usid']))) {
$user_id_follow = strip_tags($_POST['usid']);
echo $user_id_follow;
$query = "INSERT INTO markerfollowing ( userID, markerID, type )
VALUES ('$user_id_follow', '$markerid', '$type');";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
mysql_close();
}
?>
Here is the HTML button:
<div class="btn pull-right">
<button class="btn btn-large btn-followmarker" type="submit"id="followmarker">Add me to the list</button>
</div>
Here is the jquery/ajax post:
<script/javascript>
$(document).ready(function () {
$("#followmarker").click(function(){
$.ajax({
type: "POST",
url: "", //
data: { usid: <?php echo '$sess_user_id1'; ?>},
success: function(msg){
alert("success");
$("#thanks").html(msg);
},
error: function(){
alert("failure");
}
});
});
});
</script
A sincere thanks for any and all help. I haven't worked with relational databases before.
<?php echo '$sess_user_id1'; ?>
is wrong. If you wont to get
data: { usid: 123} at $sess_user_id1 is 123, you should write
data: { usid: <?php echo "$sess_user_id1"; ?>}
See your html source code in your brawser. I think there is data: { usid: $sess_user_id1}, and javascript is not understand what is the $sess_user_id1
This is the only one problem that I can see now, but I don't understand your current task whole to say more.

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

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)."'";

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