ajax response message unique identifier - php

<?php
session_start();
if(!$_SESSION['Admin']) {
header('Location: login.php'); exit();
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title> ticketExpress | Admin </title>
<link rel='stylesheet' href='../assets/css/style.css'>
</head>
<body>
<div id='containerAdmin'>
<h1> <img class='logo' src='../assets/images/logo.png' width='200' height='43'> </h1> <a href='?logout' class='logout'> Logout </a>
<h3> Open Tickets </h3>
<hr />
<?php
require("../configuration/config.php");
$GetTickets = $con->query("SELECT * FROM tickets WHERE open='true'");
while($TicketInfo = $GetTickets->fetch_object()) {
$Subject = $TicketInfo->Subject;
echo "<div id='ticket'>".$Subject ."<a href='?delete=$TicketInfo->ID'><img style='float:right'src='../assets/images/delete.png' width='15px' height='15px'></a><a style='float:right; color:red; text-decoration:none; margin-right:10px;' href='?close=$TicketInfo->ID'> Close </a><font style='float:right; margin-right:10px; color:green;' id='responseMsg'> </font></div>";
}
if(isset($_GET['delete'])) {
$ID = $_GET['delete'];
echo "
<script type='text/javascript'>
var ajax = new XMLHttpRequest();
ajax.open('POST','delete.php', true);
ajax.setRequestHeader('Content-type','application/x-www-form-urlencoded');
ajax.onreadystatechange = function () {
if(ajax.readyState == 4 && ajax.status == 200) {
document.getElementById('responseMsg').innerHTML = ajax.responseText;
}
}
ajax.send('delete=$ID');
</script>
";
}
if(isset($_GET['logout'])) {
session_destroy();
header('Location: login.php');
}
if(isset($_GET['close'])) {
$ID = $_GET['close'];
echo "
<script type='text/javascript'>
var ajax = new XMLHttpRequest();
ajax.open('POST','close.php', true);
ajax.setRequestHeader('Content-type','application/x-www-form-urlencoded');
ajax.onreadystatechange = function () {
if(ajax.readyState == 4 && ajax.status == 200) {
document.getElementById('responseMsg').innerHTML = ajax.responseText;
}
}
ajax.send('close=$ID');
</script>
";
}
?>
<br />
</div>
</body>
</html>
My problem is that whenever I click delete, the ajax response always appears next to the first ticket on the page (the top one)
If I for example click "Close" next to ticket 21, the AJAX response "Ticket Succesfully Closed" will always appear next to the first ticket on the page (for example ticket 1)
Here is close.php
<?php
require('../configuration/config.php');
if(isset($_POST['close'])) {
echo "Ticket Successfully Closed";
$TID = $_POST['close'];
$con->query("UPDATE tickets SET open='false' WHERE ID='$TID'");
}
And delete.php
<?php
require('../configuration/config.php');
if(isset($_POST['delete'])) {
echo "Ticket Deleted";
$TID = $_POST['delete'];
$con->query("DELETE FROM tickets WHERE ID='$TID'");
}
All answers are much appreciated as always! thanks in advance

You have multiple DOM elements with same ID. Check your while loop.
Code document.getElementById('responseMsg') will always get the first element that exists in DOM.
You are displaying multiple tickets with the same DOM id.
You need to append some unique identifier to element where you want to display server response.
Look at this line:
echo "<div id='ticket'>".$Subject ."<a href='?delete=$TicketInfo->ID'><img style='float:right'src='../assets/images/delete.png' width='15px' height='15px'></a><a style='float:right; color:red; text-decoration:none; margin-right:10px;' href='?close=$TicketInfo->ID'> Close </a><font style='float:right; margin-right:10px; color:green;' id='responseMsg'> </font></div>";
You could change id='responseMsg' to id='responseMsg{$TicketInfo->ID}' and then send this ticket ID as a parameter in JavaScript function to target the right one "responseMsg" element.
E.g.
echo "<div id='ticket{$TicketInfo->ID}'>". $Subject ." <a style='float:right; color:red; text-decoration:none; margin-right:10px;' href='#' onclick='closeTicket({$TicketInfo->ID});'> Close </a><span style='float:right; margin-right:10px; color:green;' id='responseMsg{$TicketInfo->ID}'> </span></div>";
<script type='text/javascript'>
function deleteTicket(ticketID) {
var ajax = new XMLHttpRequest();
ajax.open('POST','delete.php', true);
ajax.setRequestHeader('Content-type','application/x-www-form-urlencoded');
ajax.onreadystatechange = function () {
if(ajax.readyState == 4 && ajax.status == 200) {
document.getElementById('responseMsg'+ticketID).innerHTML = ajax.responseText;
}
}
ajax.send('delete='+ticketID);
}
</script>

Related

Uncaught SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse (<anonymous>) at XMLHttpRequest.<anonymous>

I had look to the similar question and its doesn't solve my problem
I want to create file multiple upload system with progressbar using php
and i have this error
Uncaught SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse (<anonymous>)
at XMLHttpRequest.<anonymous>
my code is
<?php
error_reporting(0);
$state="white";
$count=0;
if(isset($_GET["state"])){
$state=$_GET["state"];
$count=$_GET["count"];
}
?>
<html >
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="keywords" content="كتابك القريب,أدهم شرقاوي,روايات, كتب pdf,تحميل كتب,كتب دراسية,pdf,books">
<meta name="google-site-verification" content="ieyWI-BKgki1_LGBMFqdFYkGyEeHlMSEAodDuxKcN7A" />
<link rel="stylesheet" href="controls.css">
<!--
-->
<style>
.bar
{
position: absolute;
height: 15px;
background-color: rgb(27, 26, 26);
box-shadow:inset 1px 1px 1px 1px #fff5;
width: 80%;
bottom: 45px;
border-radius:15px ;
}
.pbar
{
position: absolute;
height: 15px;
background-color:#941ab4;
width: 0;
border-radius:15px ;
}
</style>
<title>كتابك القريب</title>
<script src="jquery.js"></script>
<script>
var state= <?php echo '"' .$state.'"' ; ?>;
var Vcount= <?php echo $count; ?>;
if (state=="succsses") {$(document).ready(function() { $(".succsses").css("display","block");}); }
</script>
<script>
var state= <?php echo '"' .$state.'"' ; ?>;
if (state=="error") { $(document).ready(function() { $(".error").css("display","block"); }); }
</script>
<script>
$(document).ready(function() {
$(".x").click(function() {
$(".succsses").css("display","none");
});
});
$(document).ready(function() {
$(".x").click(function() {
$(".error").css("display","none");
});
});
</script>
</head>
<body>
<div class="succsses" id="succsses" >
<p><?php if ($state=="succsses") { echo"تم تحميل ($count) ملفات بنجاح" ;}?></p>
<span class="x">x</span>
</div>
<div class="error" id="error" >
<p><?php if ($state=="error") { echo"فشل التحميل " ;}?></p>
<span class="x">x</span>
</div>
<div class="login-form">
<img src="https://yourclosebook.com/res/logos/ryhan.png" alt="" class="ava">
<form action="upload.php" method="post" enctype="multipart/form-data" id="frm">
<input type="email" name="email" id="" placeholder="email (اختياري)">
<input type="file" name="file[]" id="costum-file" accept="application/pdf,application/msword,.docx" multiple >
<input type="submit" value="تحميل" id="upload">
</form>
<div class="bar">
<span class="pbar" id="pb"></span> <span class="ptext " id="pt"></span>
</div>
<P> (*.pdf,*.docx,*.doc,*.ppt,*pptx)يمكنكم تحميل ملفات من الصيغ المدرجة جانبا</P>
<h3 id="friend"> <a href="https://www.yourclosebook.com" target="_blank" > كتابك القريب !</a> صديقك المقرب</h3>
</div>
<style>
</style>
<script src="upload.js"></script>
<script>
document.getElementById('upload').addEventListener('click',function(e){
e.preventDefault();
var f = document.getElementById('costum-file');
var pb = document.getElementById('pb');
var pt = document.getElementById('pt');
app.uploader({
files:f,
porgressBar:pb,
porgressText:pt,
processor:'upload.php',
finished:function(data){
},
error:function(){
}
});
});
</script>
</body>
</html>
uploade.php
<?php
require_once("conn.php");
header("Content-Type:application/json");
$err="";
$UPLOADED=NULL;
$count=0;
$i=0;
$succeded=[];
$faild=[];
for ($i; $i <count($_FILES['file']['name']) ; $i++) {
$target_path="uploads/";
$file=$_FILES['file']['name'][$i];
$file_temp=$_FILES['file']['tmp_name'][$i];
$fileSize =$_FILES['file']['size'][$i];
$fileError =$_FILES['file']['error'][$i];
$fileType =$_FILES['file']['type'][$i];
$fileEXT =explode('.',$file);
$fileRealExt=strtolower(end($fileEXT));
$target_path= $target_path.$file;
$allowed =array('pdf','doc','docx');
if (!empty($file)) {
if (in_array($fileRealExt,$allowed)) {
if ($fileError===0) {
$helpTimes=1;
$email=$_POST['email'];
$email= $db->real_escape_string($email);
$file= $db->real_escape_string($file);
$UPLOADED=move_uploaded_file($file_temp,$target_path);
if ($UPLOADED) {
$insert = $db->query("INSERT INTO user_uploads(email,filepath,upload_time,help_times) VALUES('".$email."','".$file."',NOW(),'".$helpTimes."')");
$count=$i+1;
$succeded=array(
'name'=>$name,
'file'=>$file
);
}else{
$faild= array('name' => $name);
echo header("Location:index.php?state=error&error=failedUpload");
}
}else{
$err= "حدث خطأ غير متوقع";
echo header("Location:index.php?state=error&error=failedUpload");
}
}else{
echo header("Location:index.php?state=error&error=notAcceptedFileFormat");
}
}else{
$err=" يجب اختيار ملف واحد على الاقل";
echo header("Location:index.php?state=error&error=empty");
}
// --------------------
if (!empty($_POST['ajax'])) {
echo json_encode(array(
'succeded'=> $succeded,
'faild'=>$faild
));
}
}
echo $err;
if ($count>0) {
//index.php
echo header("Location:index.php?state=succsses&count=$count");
if (!empty($_POST['email'])) {
$email=$_POST['email'];
$from = "MIME-Version: 1.0" . "\r\n";
$from .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$from .= 'From: YOUR CLOSE BOOK TEAM <contact#yourclosebook.com>' . "\r\n";
$s=" رسالة شكر";
$messagge="<H1>باسمنا نحن فريق موقع كتابك القريب نقد لكم فائق الشكر لاجل مساعدتنا بتقديم كتبكم الثمينة</H1>";
$mail= mail($email,$s,$messagge,$from);
if (!$mail) {
echo"email sending error";
}
else{
echo"check your email";
}
}
}else{
echo header("Location:index.php?state=error");
}
upload.js
var app=app ||{};
(function(o){
"use strict";
var ajax,getFormData,setProgress;
ajax =function (data)
{
var xhr= new XMLHttpRequest(),uploaded;
xhr.addEventListener('readystatechange',function()
{
//readyState===4 => done
if (this.readyState===4)
{
/*
status===200=> ok*/
if (this.status===200)
{
uploaded= JSON.parse(this.response);
if (typeof o.options.finished==='function')
{
o.options.finished(uploaded);
}
}
else
{
if (typeof o.options.error==='function')
{
o.options.error();
}
}
}
});
xhr.upload.addEventListener('progress',function(event)
{
var percent;//%
if (event.lengthComputable===true)
{
percent= Math.round((event.loaded/event.total)/100);
setProgress(percent);
}
});
xhr.open('post',o.options.processor);
xhr.send(data);
};
getFormData =function (source) {
var data = new FormData(),i;
for ( i = 0; i < source.length; i++) {
data.append('costum-file[]',source[i]);
}
data.append('ajax',true);
return data;
};
setProgress =function (value) {
if (o.options.porgressBar !== undefined) {
o.options.porgressBar.style.width=value?value+'%':0;
}
};
o.uploader=function (options) {
o.options=options;
if (o.options.files!==undefined) {
ajax(getFormData(o.options.files.files));
}
}
}(app));
There are some issues with your code:
In your main file you have an email element but in your upload.js file you are not adding it to your FormDara object. So in your uploade.php file you don't have access to it and $email=$_POST['email']; will throw an error
In your upload.js you are naming your file objects costum-file fun in your upload.php you are looking for file objects with the name of file. These two should have same name.
echo header("Location:index.php"); is incorrect and you should only use header("Location:index.php");
If you are calling upload.php file via ajax request then you can not do php redirect(header("Location:index.php");). What you should do is to return some json response and then pars it in your main file JavaScript and show relevant messages(Error or success)
So to sum them up what you need to change to fix the error you are getting is(I'm just highlighting the changes and not the whole code):
main(index.php?) file
You need to provide an id for the email element:
<input type="email" name="email" id="email" placeholder="email (اختياري)">
You need to add this email element to your JavaScript call
<script type="text/javascript">
document.getElementById('upload').addEventListener('click',function(e){
e.preventDefault();
var f = document.getElementById('costum-file');
var pb = document.getElementById('pb');
var pt = document.getElementById('pt');
var eml = document.getElementById('email');
app.uploader({
files:f,
porgressBar:pb,
porgressText:pt,
email:eml,
processor:'upload.php',
finished:function(data){
},
error:function(){
}
});
});
</script>
upload.js
You need to change the file element to file and also add the email element in the FormData object
getFormData =function (source) {
var data = new FormData(), i;
for ( i = 0; i < source.length; i++) {
data.append('file[]',source[i]);
}
data.append('email', o.options.email.value);
data.append('ajax', true);
return data;
};
And finally in your upload.php file change all the echo header("Location:index.php") instances with a json encoded string like what you have here:
echo json_encode(array(
'succeded'=> $succeded,
'faild'=>$faild
));
With proper response which then you can parse in your index.php file.
Please give it a try and see if it fixes your issue.

ask for the re-authentication in api when logout from dropbox

I am using php sdk provided by dropbox to fetch user's images.
All is working fine. When user comes to my website and clicks on the dropbox button, it is asking for the authentication first and then imports the user's images. Because of this process user automatically logs in the dropbox.com as well. It is expected behavior.
But after all this process, if user logs out from dropbox.com, and then again clicks on the dropbox button in my website, I believe my app shall ask for authentication but it does not ask for the authentication but provides the images from the user dropbox account.
Please ask for more details If I was not clear.
Thank you in advance.
Edit:
index.php
<?php
/***********************************************************************
* Plugin Name: Dropbox Plugin
* Plugin URI: http://www.picpixa.com/
* Version: 1.0
* Author: Ashish Shah
* Description: Plugin To Import Images From User's Dropbox Account
**********************************************************************/
session_start();
include_once '/home/picpixa/wp-config.php';
//ini_set("display_errors",1);
?>
<!-- Bootstrap -->
<link href='https://www.picpixa.com/wp-content/plugins/create-own-object/plugin-dropbox/css/bootstrap.css' rel='stylesheet'>
<link href='https://www.picpixa.com/wp-content/plugins/create-own-object/plugin-dropbox/css/style.css' rel='stylesheet'>
<style>
.loader {
position: fixed;
left: 0px;
top: 0px;
width: 100%;
height: 100%;
z-index: 9999;
background: url('https://www.picpixa.com/wp-content/plugins/create-own-object/plugin-dropbox/Images/page-loader.gif') 50% 50% no-repeat rgb(249,249,249);
}
</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(window).load(function() {
$(".loader").fadeOut("slow");
});
//creating dynamic back button
//var docRef = document.referrer;
//$('#backBtn').html('Go Back');
//alert('Go Back');
/* Not in use
//This function will call on the click event of <div class='row'>
function loadBackBtn()
{
$('#backBtn').html('<a class="btn btn-primary" href="' + document.referrer + '">Back</a>');
}
//document.write('<a class='btn btn-primary' href="' + document.referrer + '">Back</a>');*/
</script>
<script>
function loader(){
$('#load').show();
}
/*function loadExistingImages(){
window.opener.$('#loader_img').show();
result=null;
window.opener.$('#fileupload').each(function () {
var that = this;
window.opener.$.getJSON(this.action, function (result) {
if (result && result.length) {
window.opener.$(that).fileupload('option', 'done')
.call(that, null, {result: result});
//console.log('ss='+$('.table-striped tbody').find('.btn-danger').length);
if(window.opener.$('.table-striped .files').find('.btn-danger').length>0){
window.opener.$('.coo-images-other-buttons').show();
}else{
window.opener.$('.coo-images-other-buttons').hide();
}
}
window.opener.$('#loader_img').hide();
if (window.opener.$('.table-striped.files').children().length > 0)
{
window.opener.$('.table_tagline').show();
}
});
});
}*/
</script>
<!-- Adding this block to allow to see the login page like other social media -->
<!-- Login Block Start -->
<?php /*
if(isset($_SESSION['comingFirstTime']) && $_SESSION['comingFirstTime']==true)
{
?>
<div id="load" class="loader"></div>
<div id="wrap">
<div class="header">
<h4>Dropbox</h4>
</div>
<div class="cl"></div>
<div id="middal_part">
<div class="left_side">
<img src="Images/dropbox.jpg"/>
</div>
<div class="right_side">
<a class='btn btn-primary' href="<?php echo $loginUrl ?>" onclick="loader()">Login</a><br><br>
<button class="btn btn-primary close_window" type="button" onClick="window.close();">Close</button>
</div>
<div class="cl"></div>
</div>
</div>
<?php
$_SESSION['comingFirstTime'] = false;
die;
}*/
?>
<!-- Login Block End -->
<script type="text/javascript">$('#load').hide();</script>
<?php
if(isset($_POST['copy']) && $_POST['dropbox'])
{
$imgArray = $_POST['dropbox'];
$current_user = wp_get_current_user();
if(isset($current_user->ID) && trim($current_user->ID)!='' && trim($current_user->ID)!=0){
$extraSessionStr = 'usr-'.md5($current_user->ID).'/';
$user = $current_user->ID;
}else{
$sesstionId = session_id();
$user = $sesstionId;
$extraSessionStr = $sesstionId.'/';
}
foreach ($imgArray as $img)
{
//Getting a file name
$imgInfo = pathinfo($img); //This will become an array with keys ('dirname','basename','extension','filename')
$oriFileName=$imgInfo['filename'];//Getting a file name without extension
$fileName = (string) $oriFileName.".".$imgInfo['extension'];//Creating a file name with extension
//Check weather the file is exists or not rename the file if exists
$i=1;
if(file_exists('/home/picpixa/server/php/files/'.$extraSessionStr.$fileName)){
while(file_exists('/home/picpixa/server/php/files/'.$extraSessionStr.$fileName)){
$fileName = (string) $oriFileName."(".$i.").".$imgInfo['extension'];
$i++;
}
}
// Read file content
$file_content = file_get_contents($img);
file_put_contents('/home/picpixa/server/php/files/'.$extraSessionStr.$fileName, $file_content);
//file_put_contents('/home/picpixa/server/php/thumbnails/'.$extraSessionStr.$fileName, $file_content);
/* To create thumbnail */
// Max vert or horiz resolution
$maxsize=80;
// create new Imagick object
$image = new Imagick($img); //"input_image_filename_and_location"
// Resizes to whichever is larger, width or height
if($image->getImageHeight() <= $image->getImageWidth())
{
// Resize image using the lanczos resampling algorithm based on width
$image->resizeImage($maxsize,0,Imagick::FILTER_LANCZOS,1);
}
else
{
// Resize image using the lanczos resampling algorithm based on height
$image->resizeImage(0,$maxsize,Imagick::FILTER_LANCZOS,1);
}
// Set to use jpeg compression
$image->setImageCompression(Imagick::COMPRESSION_JPEG);
// Set compression level (1 lowest quality, 100 highest quality)
$image->setImageCompressionQuality(75);
// Strip out unneeded meta data
$image->stripImage();
// Writes resultant image to output directory
$image->writeImage('/home/picpixa/server/php/thumbnails/'.$extraSessionStr.$fileName); //"output_image_filename_and_location"
// Destroys Imagick object, freeing allocated resources in the process
$image->destroy();
}
?>
<script type="text/javascript">
window.opener.$('tbody.files').find('tr').remove();
//loadExistingImages();
var myVar;
if (/(MSIE\ [0-9]{1})/i.test(navigator.userAgent)) {
window.opener.$(window.opener.loadExistingFiles());
myVar = setTimeout(function(){
window.opener.$('tbody.files').find('tr .preview a[title="<?php echo $fileName;?>"]').click();
},1000);
}
else{
window.opener.$.when(window.opener.loadExistingFiles()).done(function(){
myVar = setTimeout(function(){
window.opener.$('tbody.files').find('tr .preview a[title="<?php echo $fileName;?>"]').click();
},1000);
});
}
</script>
<?php
echo "<h2>The selected images have been uploaded successfully.</h2>";
//echo "<h3>Please click on \"Proceed With Uploaded Images\" button to Proceed OR ";
//echo "Click on the \"Upload More Images\" Button to upload more images.</h3>";
?>
<div class="modal-footer">
<input type='button' name='continue' value='Upload More Images' class='btn btn-primary' onclick='loader();window.location.href="https://www.picpixa.com/wp-content/plugins/create-own-object/plugin-dropbox/index.php/";'>
<!-- <input type='button' name='closeWindow' value='Close' class='btn btn-primary pading' onClick="window.close();"> -->
</div>
<?php
die();
}
elseif (isset($_POST['copy']))
{
echo "<h2>You have not selected any image(s) to move.</h2><br><br>";
//echo "<h3>Please click on \"Close\" button to Close the window OR ";
//echo "Click on the \"Upload Images\" Button to upload images.</h3>";
?>
<div class="modal-footer">
<input type='button' name='continue' value='Upload Images' class='btn btn-primary' onclick='loader();window.location.href="https://www.picpixa.com/wp-content/plugins/create-own-object/plugin-dropbox/index.php/";'>
<!-- <input type='button' name='closeWindow' value='Close' class='btn btn-primary pading' onClick="window.close();"> -->
</div>
<?php
die();
}
require_once __DIR__.'/dropbox-sdk/Dropbox/strict.php';
$appInfoFile = __DIR__."/AppInfo.json";
// NOTE: You should be using Composer's global autoloader. But just so these examples
// work for people who don't have Composer, we'll use the library's "autoload.php".
require_once __DIR__.'/dropbox-sdk/Dropbox/autoload.php';
use \Dropbox as dbx;
$requestPath = init();
if ($requestPath === "/") {
$dbxClient = getClient();
if ($dbxClient === false) {
$loginUrl = getPath("dropbox-auth-start");
/*$loginPage = <<<login
<div id="load" class="loader"></div>
<div id="wrap">
<div class="header">
<h4>Dropbox</h4>
<p>Display Your Photo Stream</p>
</div>
<div class="cl"></div>
<div id="middal_part">
<div class="left_side">
<img src="https://www.picpixa.com/wp-content/plugins/create-own-object/plugin-dropbox/Images/dropbox.jpg"/>
</div>
<div class="right_side">
<a class='btn btn-primary' href="$loginUrl" onclick="loader()">Login</a>
<button class="btn btn-primary close_window" type="button" onClick="window.close();">Close</button>
</div>
<div class="cl"></div>
</div>
</div>
login;*/
$loginPage = <<<login
<div id="load" class="loader"></div>
<div id="wrap">
<div class="header">
<h4>Dropbox</h4>
<p>Display Your Photo Stream</p>
</div>
<div class="cl"></div>
<div id="middal_part">
<div class="left_side">
<img src="https://www.picpixa.com/wp-content/plugins/create-own-object/plugin-dropbox/Images/dropbox.jpg"/>
</div>
<div class="right_side">
<a class='btn btn-primary' href="$loginUrl" onclick="loader()">Login</a>
</div>
<div class="cl"></div>
</div>
</div>
login;
echo $loginPage;
//header("Location: ".getPath("dropbox-auth-start"));
exit;
}
$path = "/";
if (isset($_GET['path'])) $path = $_GET['path'];
$entry = $dbxClient->getMetadataWithChildren($path);
if ($entry['is_dir']) {
echo renderFolder($entry);
}
else {
echo renderFile($entry);
}
}
else if ($requestPath == "/download") {
$dbxClient = getClient();
if ($dbxClient === false) {
header("Location: ".getPath("dropbox-auth-start"));
exit;
}
if (!isset($_GET['path'])) {
header("Location: ".getPath(""));
exit;
}
$path = $_GET['path'];
$fd = tmpfile();
$metadata = $dbxClient->getFile($path, $fd);
header("Content-Type: $metadata[mime_type]");
fseek($fd, 0);
fpassthru($fd);
fclose($fd);
}
else if ($requestPath === "/upload") {
if (empty($_FILES['file']['name'])) {
echo renderHtmlPage("Error", "Please choose a file to upload");
exit;
}
if (!empty($_FILES['file']['error'])) {
echo renderHtmlPage("Error", "Error ".$_FILES['file']['error']." uploading file. See <a href='http://php.net/manual/en/features.file-upload.errors.php'>the docs</a> for details");
exit;
}
$dbxClient = getClient();
$remoteDir = "/";
if (isset($_POST['folder'])) $remoteDir = $_POST['folder'];
$remotePath = rtrim($remoteDir, "/")."/".$_FILES['file']['name'];
$fp = fopen($_FILES['file']['tmp_name'], "rb");
$result = $dbxClient->uploadFile($remotePath, dbx\WriteMode::add(), $fp);
fclose($fp);
$str = print_r($result, TRUE);
echo renderHtmlPage("Uploading File", "Result: <pre>$str</pre>");
}
else if ($requestPath === "/dropbox-auth-start") {
$authorizeUrl = getWebAuth()->start();
header("Location: $authorizeUrl");
}
else if ($requestPath === "/dropbox-auth-finish") {
try {
list($accessToken, $userId, $urlState) = getWebAuth()->finish($_GET);
// We didn't pass in $urlState to finish, and we're assuming the session can't be
// tampered with, so this should be null.
assert($urlState === null);
}
catch (dbx\WebAuthException_BadRequest $ex) {
respondWithError(400, "Bad Request");
// Write full details to server error log.
// IMPORTANT: Never show the $ex->getMessage() string to the user -- it could contain
// sensitive information.
error_log("/dropbox-auth-finish: bad request: " . $ex->getMessage());
exit;
}
catch (dbx\WebAuthException_BadState $ex) {
// Auth session expired. Restart the auth process.
header("Location: ".getPath("dropbox-auth-start"));
exit;
}
catch (dbx\WebAuthException_Csrf $ex) {
respondWithError(403, "Unauthorized", "CSRF mismatch");
// Write full details to server error log.
// IMPORTANT: Never show the $ex->getMessage() string to the user -- it contains
// sensitive information that could be used to bypass the CSRF check.
error_log("/dropbox-auth-finish: CSRF mismatch: " . $ex->getMessage());
exit;
}
catch (dbx\WebAuthException_NotApproved $ex) {
echo renderHtmlPage("Not Authorized?", "Why not?");
exit;
}
catch (dbx\WebAuthException_Provider $ex) {
error_log("/dropbox-auth-finish: unknown error: " . $ex->getMessage());
respondWithError(500, "Internal Server Error");
exit;
}
catch (dbx\Exception $ex) {
error_log("/dropbox-auth-finish: error communicating with Dropbox API: " . $ex->getMessage());
respondWithError(500, "Internal Server Error");
exit;
}
// NOTE: A real web app would store the access token in a database.
$_SESSION['access-token'] = $accessToken;
echo renderHtmlPage("Authorized!",
"Authorization complete, <a href='".htmlspecialchars(getPath(""))."' onclick='loader()'>click here</a> to browse.");
}
else if ($requestPath === "/dropbox-auth-unlink") {
// "Forget" the access token.
unset($_SESSION['access-token']);
//$_SESSION = array();
/*echo renderHtmlPage("Logged Out",
"<div class='modal-footer'>
You have been logged out.<br>
<input type='button' name='login' value='Login Again' class='btn btn-primary' onClick='location.href = \"https://www.picpixa.com/wp-content/plugins/create-own-object/plugin-dropbox/index.php/\";'>
<input type='button' name='closeWindow' value='Close' class='btn btn-primary pading' onClick='window.close();'>
</div>"
);*/
echo renderHtmlPage("Logged Out",
"<div class='modal-footer'>
You have been logged out.<br>
<input type='button' name='login' value='Login Again' class='btn btn-primary' onClick='location.href = \"https://www.picpixa.com/wp-content/plugins/create-own-object/plugin-dropbox/index.php/\";'>
</div>"
);
}
else {
echo renderHtmlPage("Bad URL", "No handler for $requestPath");
exit;
}
function renderFolder($entry)
{
/*echo "entry:<pre>";
print_r($entry);
echo "</pre>entry end.<br>Session:<pre>";
print_r($_SESSION);
echo "</pre>Session end.";
die;*/
$dbxClient = getClient();//Using to use the createTemporaryDirectLink() function
// TODO: Add a token to counter CSRF attacks.
// $upload_path = htmlspecialchars(getPath('upload'));
//$path = htmlspecialchars($entry['path']);
//$form = <<<HTML <form action='$upload_path' method='post' enctype='multipart/form-data'> <label for='file'>Upload file:</label> <input name='file' type='file'/> <input type='submit' value='Upload'/> <input name='folder' type='hidden' value='$path'/> </form> HTML;
//$form = <<<HTML HTML;
$listing_folder = '';
$listing_folder .= "<div class='container'>
<div class='row'>
<div class='col-lg-12 col-md-12 col-sm-12 col-xs-12'>
<div style='clear: both;'></div>
<div class='modal-body'>";
$listing = "<div id='load' class='loader'></div>
<div class='container'>
<div class='row'>
<div class='col-lg-12 col-md-12 col-sm-12 col-xs-12'>
<div style='clear: both;'></div>";
/*//This section is to display logout button
if(isset($entry['contents']) && $entry['contents']){
$listing .= "<div class='modal-footer'>
<script>
function goDirect(){
window.location.href='dropbox-auth-unlink';
}
</script>
<input type='button' name='logout' value='Logout' class='btn btn-primary' onclick='goDirect()'>
</div>";
}*/
$listing .= "<form method='POST' action=''>
<div class='modal-body imgAlignment'>";
$i=0;
$showBtn=False;
foreach($entry['contents'] as $child) {
$type='Folder';
$cp = $child['path'];
$cn = basename($cp);
if (!$child['is_dir']){
$type=$child['mime_type'];
}
$cp = htmlspecialchars($cp);
$link = getPath("?path=".htmlspecialchars($cp));
if ($child['is_dir']){
$listing_folder .= "<div class='baby_img'>
<a style='text-decoration: none' href='$link'>
<img src='https://www.picpixa.com/wp-content/plugins/create-own-object/plugin-dropbox/Images/folder.jpeg' style='margin: 0px 5px 0 10px !important; width:100px !important; height:100px !important; padding: 0 5px 10px 10px !important;display: block !important;clear: left !important;float: left !important;'>
<div style='clear: both;'></div>
<p style='margin: 0px 5px 0 10px !important; padding: 0 0 0 0 !important;'>$cn</p>
</a>
</div>";
$cn .= '/';
}
else{
if(strcmp($type,'image/*')==1){
$img = $dbxClient->createTemporaryDirectLink($cp);
$listing .= "<div class='baby_img'>
<input type='checkbox' id='dropbox_".$i."' name='dropbox[]' value='".$img[0]."' class='styled' />";
$listing .= "<img src='".$img[0]."' class='img-responsive' style='width:100px !important; height:100px !important;'/>";
$listing .= '</div>';
$i++;
$showBtn=true;
}
}
}
$listing .= '<div class="clearfix"></div>
<div class="modal-footer btnAlignment">';
if($showBtn){
$listing .= "<input type='submit' name='copy' value='Copy Selected Files' class='btn btn-primary' onclick='loader();'>";
}
//$listing .= "<input type='button' name='closeWindow' value='Close This Window' class='btn btn-primary pading' onClick='window.close();'>";
$listing .= '</div>
</div>';
$listing .= "</form>
</div>
</div>
</div>";
$listing_folder .= "</div>
</div>
</div>
</div>";
return renderHtmlPage("App/picpixa$entry[path]", $listing_folder.$listing);
}
function getAppConfig()
{
global $appInfoFile;
try {
$appInfo = dbx\AppInfo::loadFromJsonFile($appInfoFile);
}
catch (dbx\AppInfoLoadException $ex) {
throw new Exception("Unable to load \"$appInfoFile\": " . $ex->getMessage());
}
$clientIdentifier = "examples-web-file-browser";
$userLocale = null;
return array($appInfo, $clientIdentifier, $userLocale);
}
function getClient()
{
if(!isset($_SESSION['access-token'])) {
return false;
}
list($appInfo, $clientIdentifier, $userLocale) = getAppConfig();
$accessToken = $_SESSION['access-token'];
return new dbx\Client($accessToken, $clientIdentifier, $userLocale, $appInfo->getHost());
}
function getWebAuth()
{
list($appInfo, $clientIdentifier, $userLocale) = getAppConfig();
$redirectUri = getUrl("dropbox-auth-finish");
$csrfTokenStore = new dbx\ArrayEntryStore($_SESSION, 'dropbox-auth-csrf-token');
return new dbx\WebAuth($appInfo, $clientIdentifier, $redirectUri, $csrfTokenStore, $userLocale);
}
function renderFile($entry)
{
$metadataStr = htmlspecialchars(print_r($entry, true));
$downloadPath = getPath("download?path=".htmlspecialchars($entry['path']));
$body = <<<HTML
<pre>$metadataStr</pre>
Download this file
HTML;
return renderHtmlPage("File: ".$entry['path'], $body);
}
function renderHtmlPage($title, $body)
{
$output = <<<HTML
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<title>$title</title>
<!-- Bootstrap -->
<link href='https://www.picpixa.com/wp-content/plugins/create-own-object/plugin-dropbox/css/bootstrap.css' rel='stylesheet'>
<link href='https://www.picpixa.com/wp-content/plugins/create-own-object/plugin-dropbox/css/style.css' rel='stylesheet'>
</head>
<body>
HTML;
$permLink = "https://www.picpixa.com/wp-content/plugins/create-own-object/plugin-dropbox/index.php/";
if(isset($_GET) && $_GET['path'] && $_GET != "/")
{
$path = $_GET['path'];
$filename = substr(strrchr($path, "/"), 1);
$newPath = $permLink."?path=".str_replace('/'.$filename,'',$path);
if($newPath == $permLink."?path="){
//Setting the newPath to the root path if there there is first folder
$newPath = $permLink;
}
$output .= "<br><div class='container'>
<div class='row'>
<div class='col-lg-12 col-md-12 col-sm-12 col-xs-12'>
<a href = '".$newPath."' class='btn btn-primary pading'>Back</a>
</div>
</div>
</div>";
}
$output .= <<<HTML
$body
</body>
</html>
HTML;
return $output;
}
function respondWithError($code, $title, $body = "")
{
$proto = $_SERVER['SERVER_PROTOCOL'];
header("$proto $code $title", true, $code);
echo renderHtmlPage($title, $body);
}
function getUrl($relative_path)
{
if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') {
$scheme = "https";
} else {
$scheme = "http";
}
$host = $_SERVER['HTTP_HOST'];
$path = getPath($relative_path);
return $scheme."://".$host.$path;
}
function getPath($relative_path)
{
if (PHP_SAPI === 'cli-server') {
return "/".$relative_path;
} else {
return $_SERVER["SCRIPT_NAME"]."/".$relative_path;
}
}
function init()
{
global $argv;
// If we were run as a command-line script, launch the PHP built-in web server.
if (PHP_SAPI === 'cli') {
launchBuiltInWebServer($argv);
assert(false);
}
if (PHP_SAPI === 'cli-server') {
// For when we're running under PHP's built-in web server, do the routing here.
return $_SERVER['SCRIPT_NAME'];
}
else {
// For when we're running under CGI or mod_php.
if (isset($_SERVER['PATH_INFO'])) {
return $_SERVER['PATH_INFO'];
} else {
return "/";
}
}
}
function launchBuiltInWebServer($argv)
{
// The built-in web server is only available in PHP 5.4+.
if (version_compare(PHP_VERSION, '5.4.0', '<')) {
fprintf(STDERR,
"Unable to run example. The version of PHP you used to run this script (".PHP_VERSION.")<br>".
"doesn't have a built-in web server. You need PHP 5.4 or newer.<br>".
"<br>".
"You can still run this example if you have a web server that supports PHP 5.3.<br>".
"Copy the Dropbox PHP SDK into your web server's document path and access it there.<br>");
exit(2);
}
$php_file = $argv[0];
if (count($argv) === 1) {
$port = 5000;
} else if (count($argv) === 2) {
$port = intval($argv[1]);
} else {
fprintf(STDERR,
"Too many arguments.<br>".
"Usage: php $argv[0] [server-port]<br>");
exit(1);
}
$host = "localhost:$port";
$cmd = escapeshellarg(PHP_BINARY)." -S ".$host." ".escapeshellarg($php_file);
$descriptors = array(
0 => array("pipe", "r"), // Process' stdin. We'll just close this right away.
1 => STDOUT, // Relay process' stdout to ours.
2 => STDERR, // Relay process' stderr to ours.
);
$proc = proc_open($cmd, $descriptors, $pipes);
if ($proc === false) {
fprintf(STDERR,
"Unable to launch PHP's built-in web server. Used command:<br>".
" $cmd<br>");
exit(2);
}
fclose($pipes[0]); // Close the process' stdin.
$exitCode = proc_close($proc); // Wait for process to exit.
exit($exitCode);
}
?>
"But after all this process, if user logs out from dropbox.com, and then again clicks on the dropbox button in my website, I believe my app shall ask for authentication".
Your website is remembering the user because you're using a session to do so. If you don't want to remember the user, stop doing it. :-)
In general, a user logging out of one website has no impact on their sessions at other websites. So a user logging out of dropbox.com has no effect on their logged in status on your website. Perhaps you want to set an expiration time on the session so the user is forced to reauthenticate after a while? Or you could not use a session at all (i.e. not store the access token), in which case the user would have to reauthenticate on every page load?
EDIT
Here's the code you shared that remembers the user:
if ($requestPath === "/") {
$dbxClient = getClient();
if ($dbxClient === false) {
$loginUrl = getPath("dropbox-auth-start");
...
function getClient()
{
if(!isset($_SESSION['access-token'])) {
return false;
}
list($appInfo, $clientIdentifier, $userLocale) = getAppConfig();
$accessToken = $_SESSION['access-token'];
return new dbx\Client($accessToken, $clientIdentifier, $userLocale, $appInfo->getHost());
}

Loading a query with AJAX

function showUser(str) {
if (str=="") {
document.getElementById("content").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("content").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","paginas.php?q="+str,true);
xmlhttp.send();
}
I got this script from a website, it goes with this
<?php
$q = htmlspecialchars($_GET['q']);
$con = mysqli_connect('localhost','root',NULL,'ttrpg');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
$sql="SELECT * FROM content WHERE Pagina = '".$q."' ORDER BY ID ASC";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
echo '<div class="container">';
echo $row['Text'];
echo "</div>";
}
echo "</table>";
mysqli_close($con);
?>
I also used this:
<body onload="showUser('Home')">
I didn't change the function's name because there's no need for that
The problem I'm having is that when I load the page, there's nothing showing up inside the div.
When I press a link with for example onclick="showUser('Apple')" the text inside the div DOES change, but to the text from Home, this text doesn't ever go away, except when I reload the page
If you want to load a script on page load you can use
<script>
showUser('Home');
</script>
just before
</body> or </html> /* it will also work at the end of all html codes.*/
If you want to just print the query you executed in ajax file then you can simply use
echo $sql="SELECT * FROM content WHERE Pagina = '".$q."' ORDER BY ID ASC";
you can also see the whole ajax headers, parameters sent and response using firefox's firebug or chrome 's developer tools using inspect element then going to nework it will show ajax request and response.
Additionally you can use print_r($_REQUEST) in your ajax php file.
EDITS: I have written code to work for your needs using ajax. This will call home pages content once the page loads from fetching record from table content. If you click on about button then it will fetch content of about page from content table.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title></title>
<meta name="" content="">
<style>.msg{ color:#ff0000;}
#contentloader{ background-color:#fff; border:1px solid #333; padding:10px; }
</style>
</head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
function ajaxContentLoad(page){
q = {
'page':page,
}
$.ajax({
type:'post',
data:q,
url:'ajaxData.php',
beforeSend: function(){
$("#msg").text("sending request to server...");
},
complete:function (){
$("#msg").text("request received and loaded");
},
success:function(result, textStatus, jqXHR) {
$("#contentloader").html(result);
},
error: function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
}
})
}
$().ready(function(e){
ajaxContentLoad('Home');
})
</script>
<body>
<div style="padding: 20px; margin:20px auto; width:80%; background: #eee">
<button id="btn1" value="Home" onclick="ajaxContentLoad('Home');">Home</button>
<button id="btn1" value="About" onclick="ajaxContentLoad('About');">About</button>
<p id="msg" class="msg"></p>
<div id="contentloader">
Content on page load
</div>
</div>
</body>
</html>
and here is ajaxData.php file
<?php
$q = htmlspecialchars($_REQUEST['page']);
$con = mysqli_connect('localhost','root',admin,'demo');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"demo");
$sql="SELECT * FROM tbl_content WHERE page = '".$q."' ORDER BY ID ASC";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
echo '<div class="container">';
echo $row['content'];
echo "</div>";
}
mysqli_close($con);

How to send GET value and php available to another page using ajax?

First i access to
www.mysite.com/index.php?order_by=id asc
i want to sent $name AND $_GET[order_by] to autoload_process.php , How can i do ?
.
.
.
index.php
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Auto Loading Records</title>
<script type="text/javascript" src="js/jquery-1.9.0.min.js"></script>
<?php
include("connect.php");
$items_per_group = 5;
$mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASSWORD, $DB_NAME);
$results = $mysqli->query("SELECT COUNT(*) as t_records FROM product_details");
$total_records = $results->fetch_object();
$total_groups = ceil($total_records->t_records/$items_per_group);
$results->close();
?>
<script type="text/javascript">
$(document).ready(function() {
var track_load = 0; //total loaded record group(s)
var loading = false; //to prevents multipal ajax loads
var total_groups = <?php echo $total_groups; ?>; //total record group(s)
$('#results').load("autoload_process.php", {'group_no':track_load}, function() {track_load++;}); //load first group
$(window).scroll(function() { //detect page scroll
if($(window).scrollTop() + $(window).height() == $(document).height()) //user scrolled to bottom of the page?
{
if(track_load <= total_groups && loading==false) //there's more data to load
{
loading = true; //prevent further ajax loading
$('.animation_image').show(); //show loading image
//load data from the server using a HTTP POST request
$.post('autoload_process.php',{'group_no': track_load}, function(data){
$("#results").append(data); //append received data into the element
//hide loading image
$('.animation_image').hide(); //hide loading image once data is received
track_load++; //loaded group increment
loading = false;
}).fail(function(xhr, ajaxOptions, thrownError) { //any errors?
alert(thrownError); //alert with HTTP error
$('.animation_image').hide(); //hide loading image
loading = false;
});
}
}
});
});
</script>
<style>
body,td,th {font-family: Georgia, Times New Roman, Times, serif;font-size: 15px;}
.animation_image {background: #F9FFFF;border: 1px solid #E1FFFF;padding: 10px;width: 500px;margin-right: auto;margin-left: auto;}
#results{width: 500px;margin-right: auto;margin-left: auto;}
#resultst ol{margin: 0px;padding: 0px;}
#results li{margin-top: 20px;border-top: 1px dotted #E1FFFF;padding-top: 20px;}
</style>
</head>
<body>
<ol id="results">
</ol>
<div class="animation_image" style="display:none" align="center"><img src="ajax-loader2.gif"></div>
</body>
</html>
autoload_process.php
<?php
include("connect.php");
$items_per_group = 5;
$mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASSWORD, $DB_NAME);
if($_POST)
{
//sanitize post value
$group_number = filter_var($_POST["group_no"], FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_STRIP_HIGH);
//throw HTTP error if group number is not valid
if(!is_numeric($group_number)){
header('HTTP/1.1 500 Invalid number!');
exit();
}
//get current starting point of records
$position = ($group_number * $items_per_group);
//Limit our results within a specified range.
$results = $mysqli->query("SELECT * FROM product_details WHERE seller = '$name' ORDER BY $_GET[order_by] LIMIT $position, $items_per_group");
if ($results) {
//output results from database
while($obj = $results->fetch_object())
{
echo '<li id="item_'.$obj->id.'">'.$obj->id.' - <strong>'.$obj->seller.'</strong></span> — <span class="page_message">'.$obj->description.'</span></li>';
}
}
unset($obj);
$mysqli->close();
}
?>
First save the url parameter value to a hidden input box like this
<input type="hidden" id="orderby" value="<?php echo $_GET['orderby']; ?>"/>
and session varaible like
<input type="hidden" id="name" value="<?php echo $_SESSION['Username']; ?>"/>
then pass the value in $.POST like this
var orderby = $("#orderby").val();
var name = $("#name").val();
$.post('autoload_process.php',{'group_no': track_load, 'order_by':orderby, 'name':name} , function(data){
The second parameter of $.post is "data". You can send your variables as an object.
For example: { 'group_no': track_load, name: 'John Smith', order_by: 'id asc' }

Create Input-box with validation in JavaScript popup box

I'm confuse in this topic what should I do and How.?
I would like to have popup box which ask for the password before delete the user from the list. If Password(as some value eg. ex12345) is correct then delete the user If no then say Password is incorrect.
I have my PHP page with simple popup. I would like to have popup with the inputbox
Any help will be appreciate.
here is my code. as view.php
<html>
<head>
<meta charset="utf-8">
<title>LogIn Information System</title>
<link rel="stylesheet" media="screen" href="stylesS.css" >
<script>
function confirmDelete(delUrl)
{
if (confirm("Are you sure you want to delete"))
{
document.location = delUrl;
}
}
</script>
</head>
<body>
<div class="header-top">
<a href="//home" class="utopia-logo">
<img src="//images/logo.png" alt="asd" />
</a>
</div><!-- End header -->
<table class = "button_table">
<tr>
<td><button class="submit" type="submit">Home</button></td>
<td><button class="submit" type="submit">Search</button></td>
<td><button class="submit" type="submit">Customer List</button></td>
<?php
if($_SESSION['valid']=='admin'){
echo "<td><button class='submit' type='submit'><a href='add.php'>Add User</a></button></td>";
echo "<td><button class='submit' type='submit'><a href='users.php'>View User</a></button></td>";
}
?>
<td><button class="submit" type="submit">Logout</button></td>
</tr>
</table>
<form class="contact_form" action="search.php" method="post" name="contact_form">
<ul>
<li>
<h2>Search Results</h2>
<span class="required_notification">Following search matches our database</span>
</li>
</li>
<?php
echo "<table border='0' width='100%'>";
echo "<tr class='head'>";
echo "<th>Name</th>";
echo "<th>Last Name</th>";
echo "<th>Phone</th>";
echo "<th>Action</th>";
echo "</tr>";
while($row = mysql_fetch_array($find)){
echo "<tr class='t1'>";
echo "<td>".$row['fname']."</td>";
echo "<td>".$row['lname']."</td>";
echo "<td>".$row['phone']."</td>";
?>
<td>
<a href="edit.php?id=<?php echo $row['id'];?>" class='action'>Edit</a> |
Serve
</td>
<?php
echo "</tr>";
}
echo "</table>";
?>
</li>
</ul>
</form>
</body>
</html>
Delete.php
if (isset($_GET['id']) && is_numeric($_GET['id']))
{
// get id value
$id = $_GET['id'];;
}
$rec = "delete from data where id='$id'";
if(mysql_query($rec)){
echo "<center></h1>Selected Customer serve by DC</h1></center>"."<br />";
echo "<center></h6>Please wait while you are redirected Home in 3 seconds..</h6> </center>"."<br />";
header('Refresh: 3; url=home.php');
}
else{
die("Data failed to delete in the database");
}
?>
Okay here is an example of what I think you are asking for:
I separated the js in the header so you could better understand. first one does the pop up box and second script does the ajax call. Remember this is a very basic example
Test.html
<!DOCTYPE html>
<html lang="en">
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
//select all the a tag with name equal to modal
$('a[name=modal]').click(function(e) {
//Cancel the link behavior
e.preventDefault();
//Get the A tag
var id = $(this).attr('href');
//Get the screen height and width
var maskHeight = $(document).height();
var maskWidth = $(window).width();
//Set heigth and width to mask to fill up the whole screen
$('#mask').css({'width':maskWidth,'height':maskHeight});
//transition effect
$('#mask').fadeIn(1000);
$('#mask').fadeTo("slow",0.9);
//Get the window height and width
var winH = $(window).height();
var winW = $(window).width();
//Set the popup window to center
$(id).css('top', winH/3-$(id).height()/3);
$(id).css('left', winW/2-$(id).width()/2);
//transition effect
$(id).fadeIn(2000);
});
//if close button is clicked
$('.window .close').click(function (e) {
//Cancel the link behavior
e.preventDefault();
$('#mask').hide();
$('.window').hide();
});
//if mask is clicked
$('#mask').click(function () {
$(this).hide();
$('.window').hide();
});
$(window).resize(function () {
var box = $('#boxes .window');
//Get the screen height and width
var maskHeight = $(document).height();
var maskWidth = $(window).width();
//Set height and width to mask to fill up the whole screen
$('#mask').css({'width':maskWidth,'height':maskHeight});
//Get the window height and width
var winH = $(window).height();
var winW = $(window).width();
//Set the popup window to center
box.css('top', winH/2 - box.height()/2);
box.css('left', winW/2 - box.width()/2);
});
});
</script>
<script type="text/javascript">
function ConfirmDelete()
{
var confirm = document.getElementById('confirm').value;
var dataString = 'password='+ confirm;
if(confirm.length>0)
{
$.ajax({
type: "GET",
url: "delete.php",
data: dataString,
success: function(server_response)
{
document.getElementById("results").style.display = "block";
$('#results').html(server_response).show();
$('#mask').hide();
$('.window').hide();
}
});
}
return false;
}
</script>
<style type="text/css">
#mask{position:absolute;left:0;top:0;z-index:9000;background-color:#222;display:none}
.window{position:fixed;left:0;top:0;width:450px;height:200px;display:none;z-index:9999;padding:20px}
#dialog1{padding:10px 10px 8px 25px;border:2px solid #a1a1a1;width:450px;height:200px; background-image:url('imgs/bg.jpg');
</style>
</head>
<body>
Delete this Entry
<!-- Start of MODAL BOX -->
<div id="dialog1" class="window" align="center">
<font color="#FFFFFF">If you are sure you wish to delete this please enter your admin password</font><br>
<font color="#FFFFFF"><b>test password ( Admin )</b></font>
<input type="password" id="confirm"/><br><br>
<input type="submit" name="confirm_delete" onclick="ConfirmDelete()" value="Confirm Delete">
</div><!-- End of MODAL BOX -->
<div id="mask"></div><!-- Mask to cover the whole screen -->
<div id="results" class="results" style="display:none;"> </div>
</body>
</html>
the call page this is where you will have your php
delete.php
<?PHP
if($_GET['password'] === "Admin")
{
//sucess do your delete here
echo " this was the correct password ";
}
else
{
//failure
echo " Password incorrect!! ";
}
?>
do JS check on client side and use CRSF on server side - http://en.wikipedia.org/wiki/Cross-site_request_forgery
Here is a good example: CSRF (Cross-site request forgery) attack example and prevention in PHP

Categories