Code is not creating a file in server directory php - php

Im trying to write a new file to the server using the following code
error_reporting(E_ALL); ini_set('display_errors', 1);
if($_SERVER['REQUEST_METHOD'] == "POST") {
$html = $_POST['html'];
$filename = $_POST['fileName'];
$file = fopen('"$filename".php', 'w');
fwrite($file, $html);
// fwrite($file, $_POST["cssContent"]);
fclose($file);
The file being created is a new html page and the html content is being copied using jquery post, in the echo statements I can see the html is there as well as the filename I would like to call this new file, however after the script is run the file hasn't been created and the php error report is not reporting an error. The $file echo shows the file as Resource id #3
The html page code
<?php
include_once '../../../includes/db_connect.php';
include_once '../../../includes/functions.php';
sec_session_start();
error_reporting(E_ALL); ini_set('display_errors', 1);
$first_name = $_SESSION['memberInfo']['memberFirstName'];
$surname = $_SESSION['memberInfo']['memberLastName'];
$hash = $_SESSION['memberInfo']['hash'];
$newTemplateSrc = $_SESSION['memberInfo']['templateSrc'];
$sql = "SELECT * FROM members WHERE firstName = '$first_name' AND surName = '$surname' AND passWord = '$hash' AND templateFileSrc = '$newTemplateSrc'";
$result=mysqli_query($mysqli, $sql);
while($row = mysqli_fetch_array($result) ){
$dateofBirth = $row['dateofBirth'];
$deceasedName = $row['deceasedName'];
$dateofDeath = $row['dateofDeath'];
$aboutDeceased = $row['aboutDescription'];
$directoryId = $row['directoryid'];
$templateFileSrc = $row['templateFileSrc'];
$deceasedImage = $row['deceasedPhoto'];
};
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<!-- TemplateBeginEditable name="doctitle" -->
<title>RIDERS in the SKY CREATE MEMORIAL</title>
<!-- TemplateEndEditable -->
<link rel="stylesheet" type="text/css" href="../../../style/rits2.css">
<link rel="stylesheet" type="text/css" href="../../../Valums-File-Uploader-file-uploader-9991748/client/fileuploader.css">
<style type="text/css">
a:link {
text-decoration: none;
color: rgba(135,206,235,1);
}
a:visited {
text-decoration: none;
color: rgba(135,206,235,1);
}
a:hover {
text-decoration: none;
color: rgba(0,0,0,1);
}
a:active {
text-decoration: none;
color: rgba(135,206,235,1);
}
</style>
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- TemplateBeginEditable name="head" -->
<!-- TemplateEndEditable -->
</head>
<body>
<div class="container">
<header>
<table id="head_top">
<tbody>
<tr>
<td width="10%" rowspan="3" class="logo"><img src="../../../images/riders-in-the-sky.png" alt="RIDERS IN THE SKY LOGO - CLICKING HERE TAKES YOU TO THE HOME PAGE" title="RIDERS IN THE SKY LOGO - CLICKING HERE TAKES YOU TO THE HOME PAGE" class="logo_image"/></td>
<td width="80%" colspan="3" class="title">RIDERS IN THE SKY </td>
<td width="10%" rowspan="3" class="login_register"><table class="log_nav">
<tbody>
<tr>
<td><form action="../../../register.php"><input name="register" type="submit" class="register" title="REGISTER HERE" id="register" value="Register"></form></td>
</tr>
<tr>
<td><form action="../../../login.php"><input name="login" type="submit" class="login" title="LOGIN HERE" id="login" value="Login"></form>
</td>
</tr>
<tr> </tr>
</tbody>
</table></td>
</tr>
<tr>
<td colspan="3" class="title_tagline">MEMORIALS AND FUNERAL RESOURCES FOR BIKERS AND MOTORCYCLISTS</td>
</tr>
<tr>
<td><div class="3but_nav volunteer">VOLUNTEER</div></td>
<td><div class="3but_nav resource hover">FUNERAL RESOURCES</div></td>
<td><div class="3but_nav about">ABOUT US</div></td>
</tr>
</tbody>
</table>
<table class="top_nav">
<tbody>
<tr>
<td class="create"><form><input name="create" type="button" class="create_but" id="create" value="Create Memorial" title="CTREATE A MEMORIAL HERE" onClick="window.location.href='../../../create.php'"></form></td>
<td class="view"><form><input name="view" type="button" class="view_but" id="view" value="View Memorials" title="VIEW A MEMORIAL HERE" onClick="window.location.href='../../../view.php'"></form></td>
<td class="faq"><form><input name="faq" type="button" class="faq_but" id="faq" value="Faq's" title="GO TO OUR FAQ's and HELP PAGE" onClick="window.location.href='../../../faq.php'"></form></td>
<td class="contact"><form><input name="contact" type="button" class="contact_but" id="contact" value="Contact Us" title="NEED TO CONTACT US? CONTACT US HERE" onClick="window.location.href='../../../contact.php'"></form></td>
<td class="donate"><form><input name="donate" type="button" class="donate_but" id="donate" value="Make a Donation" title="WANT TO MAKE A DONATION TO RIDERSin the SKY? GO TO OUR DONATIONS PAGE" onClick="window.location.href='../../../donation.php'"></form></td>
</tr>
</tbody>
</table>
</header>
<!-- TemplateBeginEditable name="content_main" -->
<main class="content">
<div id="deceasedName" class="#" contenteditable="false"><?php echo $deceasedName ?></div>
<div id="DeceasedDetail" contenteditable="false">
<div id="dob" contenteditable="false"><?php echo $dateofBirth ?></div>
<div id="deceasedImage" contenteditable="false"><img class="deceasedImage" src="<?php echo $deceasedImage ?>"></div>
<div id="dod" contenteditable="false"><?php echo $dateofDeath ?></div>
<div id="deceasedProfile">
<h1 id="aboutTitle" contenteditable="false" >About <?php echo $deceasedName?></h1>
<h2 id="aboutDesciption" contenteditable="false" ><?php echo $aboutDeceased ?></h2>
</div>
<input name="button" type="button" class="editMemorial" value="Edit/Create Memorial">
</div>
<div class="editMenu" style="display:none">
<button id="editDOB" class="editMenuNav">Edit/Add D.O.B</button>
<button id="editPic" class="editMenuNav">Change/Add Deceased Photo</button>
<button id="editDOD" class="editMenuNav">Edit/Add Deceased D.O.D</button>
<button id="editDeceasedTitle" class="editMenuNav">Edit/Add About the Deceased Title</button>
<button id="editDeceasedDescription" class="editMenuNav">Edit/Add About the Deceased</button>
<button id="editName" class="editMenuNav">Edit/Add Deceased Name</button>
<button id="saveEdits" class="editMenuNav">Save Changes</button>
</div>
</main>
<!-- TemplateEndEditable -->
<footer class="footer">
<div class="breadcrumb">
<p class="breadcrumb">Funeral Resources | Terms of Use | Privacy | About Us | Contact Us | Faq's</p>
<p class="copyright"><span>©2015 RIDERS IN THE SKY</span></p>
</div>
</footer>
</div>
<div id="uploadDeceasedImage" style="display: none">
<div id="closeDeceasedUpload">Close Upload X</div>
<noscript>
<p>Please enable JavaScript to use file uploader.</p>
or put a simple form for upload here
</noscript>
<div id="preview">
<img src="../../../images/riders in the sky no text.png" alt="" width="100px" height="100px" class="deceasedThumb"/>
</div>
<!--<form id="deceasedImageUpload">
<label class="deceasupload">Upload a Picture of the Deceased</label>
<input type="file" size="20" id="imageUpload" class=" ">
<button type="submit" class="saveDeceasedImage">Save Photo</button>
</form>-->
<div id="uploadDeceasedImageWrapper">
</div>
<input id="file_upload" name="file_upload" type="file" multiple style="display:none">
<input type="button" id="upload_but" href="javascript:$('#file_upload').uploadifive('upload')" style="display: none" value="Upload Images">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="../../../Valums-File-Uploader-file-uploader-9991748/client/fileuploader.js"></script>
<script type="text/javascript">
$(".editMemorial").on('click', function() {
$('.editMenu').show();
$('.editMemorial').hide();
});
$("#saveEdits").on('click', function() {
var dateofBirth = ($('#dob').text());
var deceasedName = ($('#deceasedName').text());
var dateofDeath = ($('#dod').text());
var aboutTitle = ($('#aboutTitle').text());
var aboutDescription = ($('#aboutDesciption').text());
var firstName = ("<?php echo $first_name?>");
var surName = ("<?php echo $surname?>");
var hash = ("<?php echo $hash?>");
var templateSrc = ("<?php echo $newTemplateSrc?>");
// console.log(dateofBirth, deceasedName, dateofDeath, abouttheDeceased,firstName, surName, hash, templateSrc);
$.post('../../../includes/editContent.php', {dateofBirth:dateofBirth,deceasedName:deceasedName,dateofDeath:dateofDeath, aboutTitle:aboutTitle,aboutDescription:aboutDescription,firstName:firstName,surName:surName,hash:hash,templateSrc:templateSrc }, function(json) {
if(json.result === "success") {
$('.editMenu').hide();
$('.editMemorial').show();
$('#dob').attr('contenteditable', 'false');
$('#dod').attr('contenteditable', 'false');
$('#aboutDesciption').attr('contenteditable', 'false');
$('#aboutTitle').attr('contenteditable', 'false');
$('#deceasedName').attr('contenteditable', 'false');
$('#dob').attr('class','#')
$('#dod').attr('class','#')
$('#aboutDesciption').attr('class','#')
$('#aboutTitle').attr('class','#')
$('#deceasedName').attr('class','#')
$('#uploadDeceasedImage').hide();
}else{
};
});//json call
});//onclick
// editable clicks
$("#editDOB").on('click', function() {
$('#dob').attr('contenteditable', 'true');
$('#dod').attr('contenteditable', 'false');
$('#deceasedName').attr('contenteditable', 'false');
$('#aboutDesciption').attr('contenteditable', 'false');
$('#aboutTitle').attr('contenteditable', 'false');
$('#dob').attr('class','deceasedNameHighlight');
$('#dod').attr('class','#');
$('#deceasedName').attr('class','#');
$('#aboutDesciption').attr('class','#');
$('#aboutTitle').attr('class','#');
$('#uploadDeceasedImage').hide();
});
$("#editName").on('click', function() {
$('#dob').attr('contenteditable', 'false');
$('#dod').attr('contenteditable', 'false');
$('#deceasedName').attr('contenteditable', 'true');
$('#aboutDesciption').attr('contenteditable', 'false');
$('#aboutTitle').attr('contenteditable', 'false');
$('#dob').attr('class','#');
$('#dod').attr('class','#');
$('#deceasedName').attr('class','deceasedNameHighlight');
$('#aboutDesciption').attr('class','#');
$('#aboutTitle').attr('class','#');
$('#uploadDeceasedImage').hide();
});
$("#editDOD").on('click', function() {
$('#dob').attr('contenteditable', 'false');
$('#dod').attr('contenteditable', 'true');
$('#deceasedName').attr('contenteditable', 'false');
$('#aboutDesciption').attr('contenteditable', 'false');
$('#aboutTitle').attr('contenteditable', 'false');
$('#dob').attr('class','#');
$('#dod').attr('class','deceasedNameHighlight');
$('#deceasedName').attr('class','#');
$('#aboutDesciption').attr('class','#');
$('#aboutTitle').attr('class','#');
$('#uploadDeceasedImage').hide();
});
$("#editDeceasedDescription").on('click', function() {
$('#dob').attr('contenteditable', 'false');
$('#dod').attr('contenteditable', 'false');
$('#deceasedName').attr('contenteditable', 'false');
$('#aboutDesciption').attr('contenteditable', 'true');
$('#aboutTitle').attr('contenteditable', 'false');
$('#dob').attr('class','#');
$('#dod').attr('class','#');
$('#deceasedName').attr('class','#');
$('#aboutDesciption').attr('class','deceasedNameHighlight');
$('#aboutTitle').attr('class','#');
$('#uploadDeceasedImage').hide();
});
$("#editDeceasedTitle").on('click', function() {
$('#dob').attr('contenteditable', 'false');
$('#dod').attr('contenteditable', 'false');
$('#deceasedName').attr('contenteditable', 'false');
$('#aboutDesciption').attr('contenteditable', 'false');
$('#aboutTitle').attr('contenteditable', 'true');
$('#dob').attr('class','#');
$('#dod').attr('class','#');
$('#deceasedName').attr('class','#');
$('#aboutDesciption').attr('class','#');
$('#aboutTitle').attr('class','deceasedNameHighlight');
$('#uploadDeceasedImage').hide();
});
$('#editPic').on('click', function() {
$('#uploadDeceasedImage').show();
$('#dob').attr('contenteditable', 'false');
$('#dod').attr('contenteditable', 'false');
$('#deceasedName').attr('contenteditable', 'false');
$('#aboutDesciption').attr('contenteditable', 'false');
$('#aboutTitle').attr('contenteditable', 'false');
$('#dob').attr('class','#');
$('#dod').attr('class','#');
$('#deceasedName').attr('class','#');
$('#aboutDesciption').attr('class','#');
$('#aboutTitle').attr('class','#');
});
$('#closeDeceasedUpload').on('click', function() {
$('#uploadDeceasedImage').hide();
$('#dob').attr('contenteditable', 'false');
$('#dod').attr('contenteditable', 'false');
$('#deceasedName').attr('contenteditable', 'false');
$('#aboutDesciption').attr('contenteditable', 'false');
$('#aboutTitle').attr('contenteditable', 'false');
$('#dob').attr('class','#');
$('#dod').attr('class','#');
$('#deceasedName').attr('class','#');
$('#aboutDesciption').attr('class','#');
$('#aboutTitle').attr('class','#');
});
</script>
<script type="text/javascript">
// DOM-ready event is a much option here, just using onload in demo for simplicity
// jQuery users can use $(function()) { ...
window.onload = function() {
var uploader = new qq.FileUploader({
// pass the dom node (ex. $(selector)[0] for jQuery users)
element: document.getElementById('uploadDeceasedImageWrapper'),
// path to server-side upload script
// action: '/server/upload'
action: '../../../includes/uploadDeceased_image.php',
params: {
directoryId: '<?php echo $directoryId ?>',
templateSrc: '<?php echo $templateFileSrc ?>'
},
allowedExtensions: ['jpg', 'png'],
sizeLimit: 100000000, // 100mb
minSizeLimit: 500,
debug: true
});
};
</script>
<script type="text/javascript">
$('#saveEdits').on('click', function() {
var html = $("html").html();
var fileName = <?php echo $directoryId ?>;
console.log(html);
$.post('../../../includes/memorialSave.php', {html:html, fileName:fileName}, function(json) {
});
});
</script>
</body>
</html>
The html and filename are being sent to the php by the jquery code as shown below
<script type="text/javascript">
$('#saveEdits').on('click', function() {
var html = $("html").html();
var fileName = <?php echo $directoryId ?>;
console.log(html);
$.post('../../../includes/memorialSave.php', {html:html, fileName:fileName}, function(json) {
});
});
</script>
I'm aware that there is a lot of jquery that could be better scripted but I'm new to jquery and initially I'm just getting stuff to work

I see $filename = $_POST['fileName']; and that tells me we're dealing with files.
Sidenote: fileName and filename are not the same, should that be the case for the input.
This also tells me you're using a form and wanting to upload a file.
Since you have not provided the rest of the code, your form needs to have a POST method, including a valid enctype.
I.e. method="post" enctype="multipart/form-data". Make sure that's included.
This $filename = $_POST['fileName']; will need to be changed to
$filename = $_FILES['fileName']; while making sure the input for it also bears the fileName name attribute.
Make sure your form contains the POST method.
Forms default to GET if omitted <form action=""> and will fail silently.
While doing <form action="" method="post"> will specify it exactly.
Also $file = fopen('"$filename".php', 'w');
quotes are wrong which should be
$file = fopen($filename.".php", 'w');
or simply $file = fopen($filename, 'w'); - unsure what the file is to be.
Post the rest of your code in order to be sure.
If I'm wrong here, I'll just delete this.
Edit: Test.
Using the following test code, worked for me and created a file called filename1.php with "content" inside it.
$_POST['html'] = "content";
$_POST['fileName'] = "filename1";
$html = $_POST['html'];
$filename = $_POST['fileName'];
$file = fopen($filename.".php", 'w');
As did
$_POST['html'] = "<b>content</b>"; with <b>content</b> inside it.
2nd edit:
The $file echo shows the file as Resource id #3
You haven't shown us where you're trying to pull that content/file from.
Answer/example pulled from: https://stackoverflow.com/a/2408630/
The file did open just fine, you cannot echo it like that because it's a file pointer, not the contents of the file itself. You need to use fread() to read the actual contents, or better yet, use file_get_contents() the get the content straight away.
Doing it your way:
$handle = fopen("test.txt", "r");
$fileip = fread($handle, filesize($filename));
fclose($handle);
echo $fileip;
Or, using file_get_contents():
$fileip = file_get_contents("test.txt");
echo $fileip;
Path example:
$path = "/var/user/home/httpdocs/folder_to_write_in/";
$file = fopen($path.$filename.".php", 'w');

PHP will only parse variable within double quotes, so in your case you need to do this:
$file = fopen("\"$filename\".php", 'w');
or
$file = fopen($filename.'.php', 'w');
also you need to make sure PHP has enough permission to create file

Error in quotes it would be
$file = fopen($filename.".php", 'w');
Also read this single quotes vs double quotes
For examlpe
$filename = "text.php";
echo '$filename'; // $filename.
echo "$filename"; // text.php.

Related

How do i get the details of person who is selected in drop down?

I am building a CI application. here i show the Login and Logout of Employees. now i have a drop down where i fetch all the users from database and below that i have a table that shows the all users and their relevant login logout. Now i want to do something like when i select a user from drop down i can seen only his information and not all others.
The Controller:
public function index()
{
$this->data['attendances'] = $this->attendance_m->join_data();
$this->data['attendance_dropdown'] = $this->attendance_m->get_emp_list();
$this->data['subview'] = 'admin/attendance/index';
$this->load->view('admin/_layout_main', $this->data);
}
The Model:
function get_emp_list() {
$q = $this->db->select('name')
->from('users')
->get();
return $q->result_array();
}
Below is my code to fetch the users:
<script type="text/javascript" src="<?php echo site_url('js/bootstrap.min.js');?>"></script>
<h2>Upload CSV To Import Users</h2>
<!-- in the action you need to place /controller/function in our case #Attendance, #upload -->
<form method="post" action="<?php echo site_url('admin/attendance/upload');?>" enctype="multipart/form-data">
<input type="file" name="file" id="file">
<br>
<input type="submit" name="submit" value="UPLOAD" class="btn btn-primary">
</form>
<div class="row">
<div class="col-lg-12">
<div class="row">
<div class="col-md-3">
<div class="form-group">
<h1><label for="sel1">Select list:</label></h1>
<select name="attendance-list" id="attendance-list" class="form-control" >
<?php foreach($attendance_dropdown as $value) { ?>
<option value="<?php echo $value['name'];?>"><?php echo $value['name']; ?> </option>
<?php } ?>
</select>
</div>
<h1 class="page-header">Attendance Details</h1>
</div>
<!-- /.col-lg-12 -->
</div>
<!-- /.row -->
<div class="row">
<div class="col-lg-12">
<div class="panel panel-primary">
<div class="panel-heading">
All Calls Records
</div>
<!-- /.panel-heading -->
<div class="panel-body">
<div class="dataTable_wrapper">
<table class="table table-striped table-bordered table-hover" id="dataTables-example">
<thead>
<tr>
<th>Emp_ID</th>
<th>Name</th>
<th>Date</th>
<th>Entry</th>
</tr>
</thead>
<tbody>
<?php if(count($attendances)): foreach($attendances as $attendance): ?>
<tr class="odd gradeX">
<td><?php echo trim($attendance->emp_id,'">'); ?></td>
<td><?php echo trim($attendance->name.$attendance->last_name,'">'); ?></td>
<td><?php echo trim($attendance->date_data,'">'); ?></td>
<td><?php trim($attendance->entry,'">'); ?> <?php if($attendance->entry >100)
{
echo "Logged In";
}
else
{
echo"Logged Out";
}?>
</tr>
<?php endforeach; ?>
<?php else: ?>
<tr>
<td colspan="3">We could not find any Data.</td>
</tr>
<?php endif; ?>
</tbody>
</table>
</div>
<!-- /.table-responsive -->
</div>
<!-- /.panel-body -->
</div>
<!-- /.panel -->
</div>
<!-- /.col-lg-12 -->
</div>
<!-- /.row -->
<!-- /.row -->
<!-- jQuery -->
<script src="../bower_components/jquery/dist/jquery.min.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="../bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
<!-- Metis Menu Plugin JavaScript -->
<script src="../bower_components/metisMenu/dist/metisMenu.min.js"></script>
<!-- DataTables JavaScript -->
<script src="../bower_components/datatables/media/js/jquery.dataTables.min.js"></script>
<script src="../bower_components/datatables-plugins/integration/bootstrap/3/dataTables.bootstrap.min.js"></script>
<!-- Custom Theme JavaScript -->
<script src="../dist/js/sb-admin-2.js"></script>
<!-- Page-Level Demo Scripts - Tables - Use for reference -->
<script>
$(document).ready(function() {
$('#dataTables-example').DataTable({
responsive: true
});
});
</script>
You have to bind on change event for given dropdown if value is not empty the call ajax and get info of that particular user
in you js :
<script>
site_url="http://localhost/ci_root/index.php/";
$('#attendance-list').on('change', function () {
var select_emp_name=$(this).val();
if(select_emp_name!=""){
var params={};
params["name"]= select_emp_name;
$.ajax({type: 'POST', url: site_url + 'employee/getUserInfo', data: params,success: function (response) {
//write on response logic/set employee details
var user_data=JSON.parse(response);
}, async: true});
}
})
</script>
in Controller function
public function getUserInfo()
{
$name=$this->input->post("name",true);
$data = $this->attendance_m->get_emp_data($name);
echo json_encode( $data);
exit;
}
in Model Function:
function get_emp_data($name) {
$q = $this->db->select('*')//required fields
->from('users')
->where('name',$name) // considering name is unique field
->get();
return $q->result_array();
}
Suggestion : Its better practice to send user id or unique field for dropdown values instead of name like user_id=>1,name=>sanjay
and we can set user_id as value at dropdown and name as label for option
it will look like
<?php foreach($attendance_dropdown as $value) { ?>
<option value="<?php echo $value['user_id'];?>"><?php echo $value['name']; ?> </option>
<?php } ?>
according your where clause also change
let me know if you need more support
here is your display code for Scipt only
<script>
site_url = "http://127.0.01/project/admin/";
$('#attendance-list').on('change', function() {
var select_emp_id = $(this).val();
if (select_emp_id != "") {
var params = {};
params["id"] = select_emp_id;
$.ajax({type: 'POST', url: site_url + 'attendance/getUserInfo', data: params, success: function(response) {
//write on response logic/set employee details
var user_data = JSON.parse(response);
var row = '<tr class="odd gradeX"><td>' + user_data.emp_id + '</td><td>' + user_data.name + ' ' + user_data.last_name'</td><td>' + user_data.date_data + '</td><td>' + user_data.entry + ' ' + (user_data.entry > 100?"Logged In":"Logged Out") + '</td> </tr>';
$("#dataTables-example tbody").find('tr').remove();
$("#dataTables-example tbody").append(row);
}, async: true});
}
});
</script>
Here is how to grab data in codeigniter with a post:
Controller
function catchPost(){
$this->form_validation->set_rules("nametage", "something", "required");
if($this->form_validation->run() == TRUE){//Formvalidation worked
$this->load->model("model_name");
$data['userInfo'] = $this->model_name->function();
$this->load->view("view", $data);
}else{
redirect("prevUrl", "refresh");
}
}
Model:
function getData(){//No parameters because we work directly with the post. You should filter the post before you actually use it.
$query = $this->db-select("*")
->from("users")
->where("username", $this->input->post("username"))
->get()
->result_array();
return $query
}
This is a general way of grabbing specific data.

How to keep current page on ajax pagination after editting a row?

The header.php has a <div id="content"></div> and then will load the page user.php
Q1: Is javascript coding on the header.php can not interact with the loaded content?
Therefore I put the js code on the loaded page, but i found a little bit strange.
Q2:
The paging function is working, suppose it is on page 4.
After I editting one of the row, the page go back to first page. I want to keep it on page 4.
< 1 2 3 4 5 6>
I want to store the current link as a text within a after i click the paging, however the link is stored first and then page will refresh and clear the data.
The href of the paging links will look like
localhost://blog/index.php/admin/users/show/10
localhost://blog/index.php/admin/users/show/20
localhost://blog/index.php/admin/users/show/30
Please point out the solution or suggest another better solution
$("input[name=submit]").click(function() {
$(this).parents('.alert-box').hide();
$form = $(this).parent('form');
$.post(
$form.attr('action'),
$form.find(':input').serializeArray(),
function(data) {
$("#content").html(data);
}
);
});
View:header.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<link href="<?= $css; ?>bootstrap.css" rel="stylesheet" type="text/css">
<link href="<?= $css; ?>basic/basic.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="<?= $js; ?>jquery.js"></script>
<script type="text/javascript" src="<?= $js; ?>jquery_validate.js"></script>
<script type="text/javascript" src="<?= $js; ?>form_control.js"></script>
<script type="text/javascript" src="<?= $js; ?>additional-methods.min.js"></script>
</head>
<body>
<style>
#content{
background-color: #D0D0D0;
float:left;
width:80%;
}
#main-frame{
width:100%;
}
#list{
width:18%;
float:left;
}
#delete-alert-box{
background-color: #269abc;
position: absolute;
z-index: 99999;
display: none;
}
#edit-alert-box{
background-color: #269abc;
position: absolute;
z-index: 99999;
display: none;
}
body{
font-size:2em;
}
</style>
<script language="javascript">
$(document).ready(function() {
init();
$('.open').click(function(e) {
e.preventDefault();
$.post($(this).attr('href'), function(data) {
$('#content').html(data);
});
});
});
function init() {
$.post(
"<?php echo site_url("admin/users/show");?>", function(data) {
$("#content").html(data);
}
);
}
</script>
<div id="header">
<div id="logo">
</div>
<?php if ($this->AuthModel->check_admin_log()) { ?>
Logout
<?php }
?>
</div>
<ul id="list">
<li>
Users Manage
</li>
<li>
Group Manage
</li>
<li>
Post Mange
</li>
<li>
System Setting
</li>
<li>
<a href="<?php echo site_url('logout/admin') ?>" >Logout</a>
</li>
</ul>
<div id="content" class="box"></div>
view:users.php
<table border="1">
<tr><th>User Id</th><th>User Name</th><th>Email</th><th>Registeration Date</th><th>Group</th><th>State</th><th>Operation</th></tr>
<?php foreach ($users as $user): ?>
<tr>
<td><?= $user->id; ?></td>
<td><?= $user->username; ?></td>
<td><?= $user->email; ?></td>
<td><?= mdate('%Y-%m-%d', $user->registeration_time); ?></td>
<td><?= $user->user_type; ?></td>
<td><?= $user->account_status; ?></td>
<td>
<button type="button" value="<?php echo $user->id; ?>" name="delete">X</button>
<button type="button" value="<?php echo $user->id; ?>" name="edit">edit</button>
</td>
</tr>
<?php endforeach; ?>
</table>
<?php echo $links ?>
<div id="delete-alert-box" class="alert-box">
<div class="cancel">X</div>
<h3>Are you sure to delete the account?</h3>
<form action="<?php echo site_url('admin/users/delete') ?>" id="deleteForm">
<input type="hidden" value="" name="user_id">
<input type="button" value="Yes" name="submit">
<input type="button" value="No" name="cancel">
</form>
</div>
<div id="edit-alert-box" class="alert-box">
<div class="cancel">X</div>
<h3>Edit User:<span id="username"></span></h3>
<form action="<?php echo site_url('admin/users/edit') ?>" id="editForm">
<table>
<tr>
<td>Group</td>
<td>
<select name="group" id="group">
<option value="1">Nomal User</option>
<option value="2">Amin</option>
</select>
</td>
</tr>
<tr>
<td>State</td>
<td>
<select name="state" id="state">
<option value="1">Activated</option>
<option value="2">Non-Activated</option>
<option value="3">Blocked</option>
</select>
</td>
</tr>
</table>
<input type="hidden" value="" name="user_id">
<input type="button" value="Yes" name="submit">
<input type="button" value="No" name="cancel">
</form>
</div>
<script>
$(document).ready(function() {
$(".cancel").click(function() {
$(this).parent('.alert-box').hide();
});
$("input[name=cancel]").click(function() {
$(this).parents('.alert-box').hide();
});
$("button[name=delete]").click(function() {
var $user_id = $(this).attr('value');
if ($user_id !=<?php echo $this->session->userdata('user_id') ?>) {
$("#delete-alert-box").show();
$('#delete-alert-box').find('input[type=hidden]').attr('value', $user_id);
}
});
$("button[name=edit]").click(function() {
var $user_id = $(this).attr('value');
if ($user_id !=<?php echo $this->session->userdata('user_id') ?>) {
$("#edit-alert-box").show();
var $tr = $(this).parents('tr');
var $tds = $tr.find('td');
$('#edit-alert-box').find('input[type=hidden]').attr('value', $user_id);
$('#group').find('option').each(function(index) {
$(this).removeAttr('selected');
});
$('#group').find("option[value=" + get_group_code($($tds[4]).html()) + "]").attr('selected', 'selected');
$('#state').find("option[value=" + get_account_code($($tds[5]).html()) + "]").attr('selected', 'selected');
}
});
$("input[name=submit]").click(function() {
$(this).parents('.alert-box').hide();
$form = $(this).parent('form');
$.post(
$form.attr('action'),
$form.find(':input').serializeArray(),
function(data) {
$("#content").html(data);
}
);
});
$('.paging a').click(function(e) {
e.preventDefault();
$.post($(this).attr("href"), function(data) {
$("#content").html(data);
});
});
});
function get_group_code(name) {
switch (name) {
case "Normal User":
return 1;
case "Admin":
return 2;
}
}
function get_account_code(name) {
switch (name) {
case "Activated":
return 1;
case "Non-Activated":
return 2;
case "Blocked":
return 3;
}
}
</script>
Controller: admin/users.php
function pagination() {
$this->load->library('pagination');
$config['base_url'] = site_url('admin/users/show');
$config['total_rows'] = $this->UsersModel->get_num_rows();
$config['per_page'] = '10';
$config['uri_segment'] = 4;
$config['full_tag_open'] = '<p class="paging">';
$config['full_tag_close'] = '</p>';
$this->pagination->initialize($config);
return $this->pagination->create_links();
}
public function show() {
$data['users'] = $this->UsersModel->get_users(10, $this->uri->segment(4, 0));
$data['links'] = $this->pagination();
$this->load->view('admin/users', $data);
}
public function delete() {
$user_id = $this->input->post('user_id');
if (!$this->UsersModel->delete_user($user_id)) {
echo "Unknown error";
}
$this->show();
}
public function edit() {
$user_id = $this->input->post('user_id');
$state = $this->input->post('state');
$group = $this->input->post('group');
$data = array(
'id' => $user_id,
'account_status_code' => $state,
'group_status_code' => $group
);
if (!$this->UsersModel->edit_user($data)) {
echo "Unknown error";
}
$this->show();
}
The paging function is working, suppose it is on page 4. After I
editting one of the row, the page go back to first page. I want to
keep it on page 4.
When opening that 4-th page in a browser, you can save its number in session and then after editing you can read that value you stored in session i.e - 4.
#session_start();
function indexAction()
{
$_SESSION['curr_page'] = 4; // or take it from $_GET
}
function saveAction(){
// .... do stuff....
header('location: page.php?page=' . $_SESSION['curr_page']);
}
first the best way to do paging is via get, to get the url friendly and rotating the User in case it needs to pass it on.
you need set data in console.log(), for view if data this value,
if the expected values ​​are coming up to the date, try switching by append html:
example.
$ ("# content") html ('.');
$ ("# content") append (date).;

Trying to show jqmobile grid(trirand) in a jquery mobile windows

Using JQuery Mobile I want to pop a dialog box where the user can enter in search filters and then when they submit the query show the jqmobile grid(trirand) inside a modal window. Is this possible. Here is my code below:
qr.php
<?php require_once '../auth.php'; require_once '../jqSuitePHP/jq-config.php'; // include the PDO driver class require_once '../../jqSuitePHP/php/jqGridPdo.php'; // Connection to the server $conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD); // Tell the db that we use utf-8 $conn->query("SET NAMES utf8"); if(isset($_REQUEST['a'])) { //get asset information $conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD); $sql = "SELECT asset_no, dept_id as dept, short_desc, `LOTO #` as loto FROM mfg_eng_common.machine WHERE asset_no ='".$_REQUEST['a']."'"; $result = $conn->query($sql); $row = $result->fetch(PDO::FETCH_ASSOC); //check to see if active work order exists in MWO system for current asset //status_id of 50 mean Approved/Closed $sql = "SELECT count(*) woCnt FROM mfg_eng_mwo.mwo WHERE asset_id ='".$_REQUEST['a']."' AND status_id != 50"; $result = $conn->query($sql); $woCnt = $result->fetch(PDO::FETCH_ASSOC); } else { header("Location: http://rworley-laptop.dayton-phoenix.com/dpg/mwo/forms/MWO.php"); } ?> <!DOCTYPE HTML> <html lang="en-US"> <head> <link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.css" /> <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script> <script src="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.js"></script> <script type="text/javascript"> function getWOCnt() { var cntval = <?php echo $woCnt['woCnt'];?>; if(cntval > 0) { if (confirm(" There are already active work order(s) for asset <?php echo $_REQUEST['a']?>. \n To see active work orders:\n Click Cancel and then click 'Update Work Orders'. \n\n To enter a new work order for asset <?php echo $_REQUEST['a']?> \n Click OK .")) { window.open("../forms/MWO.php?a=<?php echo $_REQUEST['a']?>", "new"); /* $(function () { $("#newMWO").on('click', (function (event) { event.preventDefault(); var loadVars=(encodeURI("../forms/MWO.php?a=<?php echo $_REQUEST['a']?>")); var dialogName= $("#mwoForm").load(loadVars); $(dialogName).dialog({ autoOpen: false, resizable: true, modal: true, bigframe: true, height: 600, width: 1000, overflow: scroll, resizable: true, title: "MWO New Work Order" }); dialogName.dialog('open'); return false; })); }); */ } } else { window.open("../forms/MWO.php?a=<?php echo $_REQUEST['a']?>", "new"); /* $(function () { $("#newMWO").on('click', (function (event) { event.preventDefault(); var loadVars=(encodeURI("../forms/MWO.php?a=<?php echo $_REQUEST['a']?>")); var dialogName= $("#mwoForm").load(loadVars); $(dialogName).dialog({ autoOpen: false, resizable: true, modal: true, bigframe: true, height: 600, width: 1000, overflow: scroll, resizable: true, title: "MWO New Work Order" }); dialogName.dialog('open'); return false; })); }); */ } }; </script> </head> <body> <div data-role="page" data-theme="b" align="center"> <div data-theme="a" data-role="header"> <h1>Maintenance Work Orders</h1> <img alt="<?php echo $_REQUEST['a']?>" src="../../Machine Pictures/<?php echo $row['dept']?>/<?php echo $row['asset_no']?>.jpg" height="240" width="300"/> <b><br><?php echo $row['short_desc']?></b> </div><!-- /header --> <br> <div data-theme="c" data-content-theme="d" > <hr> <?php echo "PM Procedure" ?> <b>|</b> <?php echo "Loto Procedure" ?> </div> <div data-role="collapsible-set" data-theme="b" data-content-theme="d" > <ul data-role="listview" data-inset="true" align="center" data-filter="false" data-theme="b"> <li> <a id="newMWO" name="newMWO" data-role="button" data-inline="true" target="_blank" onclick=getWOCnt() > New Work Order </a> </li> </ul> <ul data-role="listview" data-inset="true" align="center" data-filter="false" data-theme="b"> <li> Update Work Order </li> </ul> <ul data-role="listview" data-inset="true" align="center" data-filter="false" data-theme="b"> <li> <a href="../../mwo/MWO_mobile.php?a=<?php echo $_REQUEST['a']?>" data-role="button" data-inline="true" data-rel="dialog" target="mwoSearch" data-transition="slidedown" > Search Work Orders </a> </li> </ul> </div> <?php if(!($_POST)) { echo " <a href='#popupBasic' data-rel='popup' data-role='button' data-inline='true'>Quick Search</a> <div data-role='popup' id='popupBasic' data-transition='flip' > <a href='#' data-rel='back' data-role='button' data-theme='a' data-icon='delete' data-iconpos='notext' class='ui-btn-right'>Close</a> <form action='#' method='POST'> <div data-theme='a' data-role='header'> <h2>Look Up MWO</h2> </div> <p> Problem<textarea name='search_prob' data-theme = 'a' data-content-theme = 'd' rows = '3' cols = '50' id = 'search_prob' /></textarea> </p> <p> Solution<textarea name='search_sol' data-theme = 'a' data-content-theme = 'd' rows = '3' cols = '50' id = 'search_sol' /></textarea> </p> <p id = 'submit-area'> <input type='submit' data-theme='b' value='Search' id = 'sub1'/> </p> </form> </div> "; } else { echo " <ul data-role='listview' data-inset='true' align='center' data-filter='false' data-theme='b'> <li> <a href=\"QS.php?a=".$_REQUEST['a']."\" data-role='button' data-inline='true' data-rel='dialog' data-transition='slidedown'> Qucick Search Results </a> </li> </ul>"; } ?> <div data-role="footer" data-theme="a"> <h4>Dayton-Phoenix Group, Inc.</h4> </div><!-- footer --> </div><!-- page --> </body> </html>
QS.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>MWO Quick Search</title>
<link rel="stylesheet" href="../../jquerymobile.jqGrid/css/themes/default/jquery.mobile.css" />
<link rel="stylesheet" href="../../jquerymobile.jqGrid/css/themes/ui.jqgridmobile.css" />
<link rel="stylesheet" href="../../jquerymobile.jqGrid/css/themes/shCoreEclipse.css" />
<link rel="stylesheet" href="../../jquerymobile.jqGrid/css/themes/shThemeEclipse.css" />
<script src="../../jquerymobile.jqGrid/js/jquery.js" type="text/javascript"></script>
<script src="../../jquerymobile.jqGrid/js/jquerymobile.jqGrid.min.js" type="text/javascript"></script>
<script src="../../jquerymobile.jqGrid/js/jquery.mobile.js" type="text/javascript"></script>
<script src="../../jquerymobile.jqGrid/js/grid.locale-en.js" type="text/javascript"></script>
</head>
<body>
Paging, sorting and searching
</body>
</html>
quickSearch2.php
<!DOCTYPE html>
<html>
<body>
<div id="page" data-role="page" data-theme="b">
<div data-role="header" data-theme="b" style="margin-bottom: 10px">
<h1> MWO Quick Search Results</h1>
Home
</div>
<!-- HTML table Definition -->
<table id='grid'></table>
<div id='pager'></div>
<!-- Java Scruipt Code -->
<script type='text/javascript'>
var a = <?php echo json_encode($_REQUEST['a']); ?>;
var prob = <?php echo json_encode($_REQUEST['search_prob']); ?>;
jQuery('#grid').jqGrid({
"hoverrows":false,
"viewrecords":true,
//"jsonReader":{"repeatitems":false,"subgrid":{"repeatitems":false}},
"gridview":true,
"url":"../../mwo/mobile/quicksearch.php?a=" + a + "&search_prob=" + prob,
"loadonce": true,
"rowNum":10,
"height":200,
"autowidth":true,
"sortname":"mwo_id",
"rowList":[10,30,40],
"datatype":"json",
"colModel":[
{"name":"e", "index":"empty", "sorttype":"int", "hidden":true,"width":50,"editable":true},
{"name":"MWO #", "index":"mwo_id", "sorttype":"int", "key":true,"width":80,"editable":true},
{"name":"DPG #", "index":"asset_id", "sorttype":"string", "width":80, "editable":true},
{"name":"Assigned to", "index":"assigned_id", "sorttype":"string", "width":80, "editable":true},
{"name":"Entered", "index":"entered_time", "sorttype":"datetime", "width":80, "editable":true,"datefmt":"m/d/Y", "searchoptions":{sopt:['eq']}, "formatter":"date","formatoptions":{"srcformat":"Y-m-d H:i:s","newformat":"m/d/Y"}},
{"name":"Problem", "index":"long_desc", "sorttype":"string", "width":80, "editable":true},
{"name":"Solution", "index":"solution", "sorttype":"string", "width":80, "editable":true}
],
"pager":"#pager"
});
</script>
</div>
</body>
</html>
json data being used:
{"page":1,"total":2,"records":13,"rows":[{"mwo_id":"1302271211","cell":["","1302271211","38315","-1","2013-07-08 11:13:19","approved test",""]},{"mwo_id":"1302271213","cell":["","1302271213","38315","-1","2013-07-11 09:26:26","yo momma is so fattest","how fat is she? she's so fat she left the house in heels and came back in flip-flops"]},{"mwo_id":"1302271214","cell":["","1302271214","38315","-1","2013-07-12 12:13:55","july test",""]},{"mwo_id":"1302271215","cell":["","1302271215","38315","-1","2013-07-08 08:59:56","test","update2"]},{"mwo_id":"1302271216","cell":["","1302271216","38315","-1","2013-07-09 06:14:02","test",""]},{"mwo_id":"1302271217","cell":["","1302271217","38315","-1","2013-07-08 09:01:30","yep testing","no answer yet"]},{"mwo_id":"1302271218","cell":["","1302271218","38315","-1","2013-07-09 09:59:46","new test of email system",""]},{"mwo_id":"1302271219","cell":["","1302271219","38315","","2013-07-08 12:33:09","email new test",""]},{"mwo_id":"1302271221","cell":["","1302271221","38315","12","2013-07-11 13:20:55","ANOTHER TEST OF NEW ...WITH EMAIL","AND THE ANSWER IS ....."]},{"mwo_id":"1302271222","cell":["","1302271222","38315","","2013-07-11 09:29:58","test...add issue",""]},{"mwo_id":"1302271223","cell":["","1302271223","38315","","2013-07-11 13:11:15","testing",""]},{"mwo_id":"1302271224","cell":["","1302271224","38315","7","2013-07-11 13:27:32","test with auto assign","no solution its all good"]},{"mwo_id":"1302271226","cell":["","1302271226","38315","7","2013-07-12 12:05:02","Meeting test",""]}]}

Not able to load mysql query data in JEasyUI Grid

I am new to PHP and JEasy UI.
I am actually running the demo application of JEasy UI Grid.
Whereas I am not getting the data from Php file to Grid.
Any Idea or suggestion please...!!
Below is My Code:
index.php
<html>
<head>
<meta charset="UTF-8">
<title>Basic CRUD Application - jQuery EasyUI CRUD Demo</title>
<link rel="stylesheet" type="text/css" href="http://www.jeasyui.com/easyui/themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="http://www.jeasyui.com/easyui/themes/icon.css">
<link rel="stylesheet" type="text/css" href="http://www.jeasyui.com/easyui/demo/demo.css">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.min.js"></script>
<script type="text/javascript" src="http://www.jeasyui.com/easyui/jquery.easyui.min.js"></script>
</head>
<body>
<div class="demo-info" style="margin-bottom:10px">
<div class="demo-tip icon-tip"> </div>
</div>
<table id="dg" title="My Users" class="easyui-datagrid" style="width:700px;height:250px"
url="http://www.jeasyui.com/tutorial/app/crud/get_users.php"
toolbar="#toolbar" pagination="true"
rownumbers="true" fitColumns="true" singleSelect="true">
<thead>
<tr>
<th field="firstname" width="50">First Name</th>
<th field="lastname" width="50">Last Name</th>
<th field="phone" width="50">Phone</th>
<th field="email" width="50">Email</th>
</tr>
</thead>
</table>
<div id="toolbar">
New User
Edit User
Remove User
</div>
<div id="dlg" class="easyui-dialog" style="width:400px;height:280px;padding:10px 20px"
closed="true" buttons="#dlg-buttons">
<div class="ftitle">User Information</div>
<form id="fm" method="post" novalidate>
<div class="fitem">
<label>First Name:</label>
<input name="firstname" class="easyui-validatebox" required="true">
</div>
<div class="fitem">
<label>Last Name:</label>
<input name="lastname" class="easyui-validatebox" required="true">
</div>
<div class="fitem">
<label>Phone:</label>
<input name="phone">
</div>
<div class="fitem">
<label>Email:</label>
<input name="email" class="easyui-validatebox" validType="email">
</div>
</form>
</div>
<div id="dlg-buttons">
Save
Cancel
</div>
<script type="text/javascript">
var url;
function newUser(){
$('#dlg').dialog('open').dialog('setTitle','New User');
$('#fm').form('clear');
url = 'save_user.php';
}
function editUser(){
var row = $('#dg').datagrid('getSelected');
if (row){
$('#dlg').dialog('open').dialog('setTitle','Edit User');
$('#fm').form('load',row);
url = 'update_user.php?id='+row.id;
}
}
function saveUser(){
$('#fm').form('submit',{
url: url,
onSubmit: function(){
return $(this).form('validate');
},
success: function(result){
var result = eval('('+result+')');
if (result.errorMsg){
$.messager.show({
title: 'Error',
msg: result.errorMsg
});
} else {
$('#dlg').dialog('close'); // close the dialog
$('#dg').datagrid('reload'); // reload the user data
}
}
});
}
function destroyUser(){
var row = $('#dg').datagrid('getSelected');
if (row){
$.messager.confirm('Confirm','Are you sure you want to destroy this user?',function(r){
if (r){
$.post('destroy_user.php',{id:row.id},function(result){
if (result.success){
$('#dg').datagrid('reload'); // reload the user data
} else {
$.messager.show({ // show error message
title: 'Error',
msg: result.errorMsg
});
}
},'json');
}
});
}
}
</script>
<style type="text/css">
#fm{
margin:0;
padding:10px 30px;
}
.ftitle{
font-size:14px;
font-weight:bold;
padding:5px 0;
margin-bottom:10px;
border-bottom:1px solid #ccc;
}
.fitem{
margin-bottom:5px;
}
.fitem label{
display:inline-block;
width:80px;
}
</style>
</body>
</html>
PHP Code URL
http://www.jeasyui.com/tutorial/app/crud/get_users.php
to get the data from datagrid you need to code like this
public function get_user(){
/*Default request pager params from jeasyUI*/
$offset = isset($_POST['page']) ? intval($_POST['page']) : 1;
$limit = isset($_POST['rows']) ? intval($_POST['rows']) : 10;
$search = isset($_POST['search']) ? $_POST['itemid'] : '';
$offset = ($offset-1)*$limit;
//change this line to yours
$data = $this->user_model->get_user($offset,$limit,$search);
$i = 0;
$rows = array();
foreach ($data ['data'] as $r) {
$rows[$i]['first_name'] = $r->first_name;
$rows[$i]['last_name'] = $r->last_name;
$rows[$i]['phone'] = $r->phone;
$rows[$i]['email'] = $r->email;
$i++;
}
//keys total & rows is required on jEasyUI
$result = array('total'=>$data['count'],'rows'=>$rows);
echo json_encode($result);
}
more complete example here

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