How to delete row with jquery, ajax and PDO - php

I have two tables in mysql DB, 'cars' and 'address' which they have relation with primary key and 'on delete restrict' in DB so I can't delete some address which have car and that's good. Addresss in DB have columns 'street', 'number' and 'city'. I want to delete every location which has no cars but I don't know where I'm wrong in code, it doesn't work.I checked all paths and all is ok. Any suggestion appreciate.
This is my modal delete button:
<a href="#" data-toggle="modal" data-target="#delete_loc<?php echo $value['id']?>" role="button" class="btn btn-danger btn-sm">
<i class="fa fa-trash-o"></i> Delete
</a>
<div class="modal fade" id="delete_loc<?php echo $value['id']?>" tabindex="-1" role="dialog" aria-labelledby="mydelModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content" style="text-align:center;">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h2 class="modal-title" id="mydelModalLabel" style="color:#a80b27;text-transform:uppercase;font-size:1.6rem;">Warning !</h2>
</div>
<div class="modal-body">
<h5>Are you shure you want delete address ID <b><?php echo $value['id']?></b>?</h5>
</div>
<div class="modal-footer">
<input type="hidden" name="loc_id" id="loc_id" value="<?php echo $value['id']?>">
<a href="" role="button" class="btn btn-danger" id="del_loc">
Yes, I'm shure!
</a>
<button type="button" class="btn btn-default" data-dismiss="modal">No</button>
</div>
</div>
</div>
</div>
This is jquery and ajax:
$(document).ready(function() {
$('#del_loc').bind('click',function(e){
e.preventDefault();
var id = $('#loc_id').val();
var data = 'loc_id='+id;
$.ajax({
type: "POST",
url: "include/locations/delete.php",
data: data,
success: function(result){
if(result == 1){
window.location.replace("address.php?id=");
}
else{
err_msg = JSON.parse(result);
if(err_msg.nAddress){
$('.panel-footer').append('<span class="help-block" style="float:right;"><strong>'+err_msg.nAddress+'</strong></span>');
}
}
}
});
});
});
This is delete.php:
<?php
require '../../config/init.php';
require '../functions/locations.php';
require '../services/xss.php';
$loc_id = _e($_POST['loc_id']);
$data = deleteLoc($loc_id);
if(is_array($data)){
print_r(1);
}
else{
echo $data;
}
?>
And this is function named locations.php:
function deleteLoc($loc_id){
global $conn;
try{
$stmt = $conn->prepare('DELETE FROM address WHERE id=:id');
$stmt->bindParam(':id',$loc_id);
$stmt->execute();
$row[] = 'deleted';
return $row;
}
catch(PDOException $e){
if(DEBUG === true){
header('Location:../../error/db_error.php?err_msg='.$e->getMessage());
}
else{
header('Location:../../error/db_error.php?err_msg');
}
}
}

If you are getting the value loc_id value properly.I think following code will help you a lot. Let's try..
JavaScript
<script type="text/javascript">
$(document).ready(function() {
$('#del_loc').bind('click',function(e){
e.preventDefault();
var id = $('#loc_id').val();
var data = 'loc_id='+id;
//try here alert(id); For checking whether you are getting value or not
$.ajax({
type: "POST",
url: "include/locations/delete.php",
dataType:'JSON',
data: data,
success: function(result){
var res=eval(result);
if(res.success){
window.location.replace("address.php?id=");
}
else
{
if(res.nAddress){
$('.panel-footer').append('<span class="help-block" style="float:right;"><strong>'+err_msg.nAddress+'</strong></span>');
}
}
}
});
});
});
</script>
PHP delete.php
<?php
require '../../config/init.php';
require '../functions/locations.php';
require '../services/xss.php';
$loc_id = _e($_POST['loc_id']);
$data = deleteLoc($loc_id);
if(is_array($data)){
echo json_encode(array('success'=>true));
}
else{
echo json_encode($data);
}
?>

Related

display data dynamically in bootstrap modal in laravel

I was watching tutorial on how to display MySQL data in dynamic window then I realized its not for laravel i hope there is a why to use it on laravel.
jQuery / AJAX :
<script>
$(document).ready(function(){
$('.view_data').click(function(){
var student_id = $($this).attr("id");
$.ajax({
url:select.php,
method:"post",
data:{student_id:student_id},
success:function(data){
$('student_detail').html(data);
$('#dataModal').modal("show");
}
});
});
});
</script>
the window shows up when the script has only this line: $('#dataModal').modal("show"); so script works when its like this but does not show any data.
<script>
$(document).ready(function(){
$('.view_data').click(function(){
var student_id = $($this).attr("id");
$('#dataModal').modal("show");
});
});
</script>
url:select.php
<?php
if(isset($_POST["student_id"]))
{
$output = '';
$connect = mysqli_connect("localhost", "root", "", "sms");
$query = "SELECT * FROM students WHERE id = '".$_POST["student_id"]."'";
$result = mysqli_query($connect, $query);
$output .= '
<div class="table-responsive">
<table class="table table-bordered">';
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td width="30%"><label>first name</label></td>
<td width="70%">'.$row["firstName"].'</td>
</tr>
';
}
$output .= "</table></div>";
echo $output;
}
?>
I have more data columns but im using firstName for now
and this is the window model that shows up :-
<div id="dataModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Employee Details</h4>
</div>
<div class="modal-body" id="student_detail">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
Try this
<script>
$(document).ready(function(){
$('.view_data').click(function(){
var student_id = $(this).attr("id");// also here $this will be not defined
$.ajax({
url:select.php,
method:"post",
data:{student_id:student_id},
success:function(data){
$('#student_detail').html(data);//selector are not valid you are missing to add # at the beginning
$('#dataModal').modal("show");
}
});
});
});
</script>
You should do a test first, check (I don't know if you did this already or not) if the PHP script actually returns some data. You can do an ajax call and display the response in the console.

How to get new session value after some time using PHP

I need to get the new session value after some second using PHP. My code is below.
<button class="btn nextbtnbgdiv open2" type="button">Next <span class="fa fa-arrow-right"></span></button>
<div class="fyndspacecategory fyndsheightsubc nano">
<div class="nano-content">
<?php
$cat_id= $_SESSION['cid'];
?>
</div>
</div>
Here when user is clicking on next button the div section is opening and the the value is fetching from session. Here i need after some second always the updated $_SESSION['cid'] will fetch at each time click on next button.
In order to fetch the updated $_SESSION['cid'] you will need to make a call to the server to return this value, you can do so by embedding the value into an element i.e.
Back-end (i.e. get_session.php):
<html>
<body>
<div id="session"><?= $_SESSION['cid'] ?></div>
</body>
</html>
Front-end:
<button class="btn nextbtnbgdiv open2" type="button">Next <span class="fa fa-arrow-right"></span></button>
<div class="fyndspacecategory fyndsheightsubc nano">
<div class="nano-content"><?php $cat_id= $_SESSION['cid']; ?></div>
</div>
<script>
jQuery(function($) {
$(document).on( 'click', '.nextbtnbgdiv', function() {
$('.fyndspacecategory .nano-content').load('/get_session.php', '#session');
});
});
</script>
Or you could use a header within a page to access $_SESSION['cid'].
<?php
if ( isset( $_GET['get_session'] ) && $_GET['get_session'] ) {
header( 'X-Session: ' . $_SESSION['cid'] );
exit;
}
?>
<button class="btn nextbtnbgdiv open2" onclick="javascript:getSession();" type="button">Next <span class="fa fa-arrow-right"></span></button>
<div class="fyndspacecategory fyndsheightsubc nano">
<div class="nano-content" id="sessionId"><?php $cat_id= $_SESSION['cid']; ?></div>
</div>
<script>
function getSession() {
var request = new XMLHttpRequest();
request.onerror = function() { console.warn('An error occurred while checking session.'); };
request.open('HEAD', '?get_session=true', true);
request.onload = function() {
if ( request.getResponseHeader('X-Session') ) {
document.getElementById("sessionId").innerHTML = request.getResponseHeader('X-Session');
}
};
request.send();
}
</script>
This is not tested but should be enough to give you a start to complete your goal.

User view count in yii

I created a button to generate a popup which shows some events.And past few days I was trying to show the count of users which visted the events.
I tried some of the extensions too...Like
Counter
pcviewcounter
etc,
But I need to store the ip address ,eventid and time in my database.
Can anyone please help me with this???
View for button
<div class="modal fade" id="detailsOffeEve" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
</div>
<script>
function showdetails(id)
{ // alert(id);
$('#detailsOffeEve').load('<?php echo Yii::app()->baseUrl; ?>/offerEvents/popup/'+id);
}
</script>
And action popup
public function actionPopup($id)
{
//$this->render('/offerEvents/Details',array(
//'model'=>OfferEvents::model()->findByAttributes(array('id'=>$id)), ));
$OfferEventsList = OfferEvents::model()->findAllByAttributes(array('id' => $id));
foreach($OfferEventsList as $Listdata)
{ $titnw=$Listdata['title']; $details=$Listdata['description'];
$discountper=$Listdata['discountper']; $discountperamt=$Listdata['discountperamt'];
$strdaate=$Listdata['startdate']; $enddaate=$Listdata['enddate']; $evoftype=$Listdata['type']; }
$cmuserid=$Listdata['createdby'];
if($Listdata['createdby']==0){ $createdbyname="Admin"; } else { $createdbyname=$Listdata->company->companyname; }
$locationnw=$Listdata->location;
$offrimage=$Listdata->image;
if($offrimage!=""){ $imgUrls=$offrimage; } else { $imgUrls='image-not-available.png'; }
$infowinimgpaths='theme/images/OfferEvents/orginal/'.$imgUrls;
if (file_exists($infowinimgpaths)) { $infowinimgpathSrcs=Yii::app()->baseUrl.'/'.$infowinimgpaths; } else
{ $infowinimgpathSrcs=Yii::app()->baseUrl.'/theme/images/OfferEvents/image-not-available.png'; }
if (Yii::app()->user->id!='' && Yii::app()->user->id!=1){
$subcribeemailid=Yii::app()->user->email; $logsts=1;
$countsubscribe = Newsfeeds::model()->countByAttributes(array('emailid' => $subcribeemailid,'cuserid' => $cmuserid));
} else { $subcribeemailid=''; $countsubscribe=0; $logsts=0; }
$PopupdetailText='<div class="modal-dialog-1">
<div class="modal-content">
<div class="modal-header login_modal_header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h2 class="modal-title" id="myModalLabel">'.$titnw.' </h2>
</div>
<div class="container-1">
<div class="row">
<div class="col-sm-7 detail-text">
<h2 class="title"> ';
if($evoftype==0){ $PopupdetailText.='Offer Price: '.$discountperamt.'
<font style="font-size: 15px;">[ Up To '.$discountper.'% Discount ]</font>'; }
$PopupdetailText.='</h2><p>Details: </p>
<p>'.$details.'</p>
<p>Location: '.$locationnw.'</p>
<p>Expires in: '.$enddaate.'</p>';
if($countsubscribe==0){
$PopupdetailText.='<p>Shared by: '.$createdbyname.'
<button type="button" class="btn btn-success btn-xs" Onclick="subcribefeed('.$logsts.','.$cmuserid.')" >Subscribe NewsFeed</button></p>';
} else {
$PopupdetailText.='<p>Shared by: '.$createdbyname.'
<button type="button" class="btn btn-success disabled btn-xs" >Already Subscribed NewsFeed</button></p>';
}
$PopupdetailText.='<div class="form-group" id="subcribefrm" style="display:none;background-color: #eee; padding: 12px; width: 82%;">
<input type="text" id="subemailid" placeholder="Enter EmailID here" value="'.$subcribeemailid.'" style="width: 100%;" class="form-control login-field">
<br/>
Subscribe Feeds </div> ';
// if($evoftype==0){ $PopupdetailText.='<p>Offer Price:<b> $'.$discountperamt.'</b></p>'; }
$PopupdetailText.='<p>';
$PopupdetailText .= $this->renderPartial('/comments/share', array('postid' => $id),TRUE);
$PopupdetailText.='<img src="'.Yii::app()->baseUrl.'/theme/site/images/comments.png"/>Comments
<img src="'.Yii::app()->baseUrl.'/theme/site/images/share.png"/>Share</p>
<br/>';
$userComment = new Comments;
$PopupdetailText .= $this->renderPartial('//comments/_form', array('model' => $userComment,'id'=>$id),TRUE,TRUE);
// $PopupdetailText .= $this->renderPartial('//comments/view', array('model' => $userComment,'id'=>$id),TRUE);
$PopupdetailText.='</div>
<div class="col-sm-5">
<img src="'.$infowinimgpathSrcs.'" width="100%"/>
</div>
</div>
</div>
<div class="clearfix"></div>
<div class="modal-footer login_modal_footer">
</div>
</div>
</div>
<script>
function subcribefeed(staus,cid)
{
if(staus==0){
$("#subcribefrm").toggle(); }
else { subcribefeedAdd(cid); }
}
function subcribefeedAdd(cid)
{
subusremail=$("#subemailid").val();
var re = /[A-Z0-9._%+-]+#[A-Z0-9.-]+.[A-Z]{2,4}/igm;
if (subusremail == "" || !re.test(subusremail))
{ alert("Invalid EmailID ."); }
else {
postData ={
"email" :subusremail,
"cid" :cid
}
$.ajax({
type: "POST",
data: postData ,
url: "'.Yii::app()->baseUrl.'/newsfeeds/create",
success: function(msg){
if(msg=="Success"){ showdetails('.$id.'); alert("news feed subscribe successfully."); }
else if(msg=="available"){ alert("Already subscribe News Feed for this Commercial user."); }
else { alert("Error ."); }
}
});
}
}
</script> ';
echo $PopupdetailText;
}
I just got the answer.I dont know whether the answer is in right method.
I just added the foolwiong code after my action.
**
$view = new Viewcount;
$viewip = Yii::app()->request->getUserHostAddress();
$viewdate = date('Y-m-d');
$view->ipadd = $viewip;
$view->ofrevntid = $id;
$view->visitdate = $viewdate;
$viewlist = Viewcount::model()->findByAttributes(array('ipadd'=>$viewip,'ofrevntid'=>$id,'visitdate'=>$viewdate));
$viewcount = count($viewlist);
if ($viewcount == 0){
$view->save();
}
**

How can I return multiple data using ajax and json

I'm trying to return a multiple data from database, then I'll pass it to jquery using ajax & json but the problem is its not working. Can anyone help me to fix it? Here is my code.
Jquery
$('.highlight').click(function() {
var y = $(this).find("td").eq(0).find('input[type="hidden"]').val();
var x = $(this).find("td").eq(1).text();
var z = $(this).find("td").eq(2).text();
//$('#ClassModal').modal('show');
$("#spanclass").text(x);
$("#spanclass2").text(z);
$('#ClassModal').modal('show');
$.ajax({
type:"GET",
url: 'db_loadStud.php',
data: 'year='+x+'&subject='+z,
dataType: 'json',
success: function(data){
for(var x=0;x<data.length; x++){
$(".studname").find("span").text(data[0]+", "+data[1]);
}
}
});
return false;
});
PHP
<?php
session_start();
include("db_conf.php");
$fid = $_SESSION['fid'];
$year = $_GET['year'];
$sub = $_GET['subject'];
$sql = "SELECT si_lname, si_fname, si_mname,si_studentno FROM `student_info` a";
$sql .= " INNER JOIN (SELECT * FROM student_enrolled WHERE se_active='True') b ON a.si_studentno=b.se_id";
$sql .= " INNER JOIN tblcourses c ON b.se_level=c.c_level WHERE c_level='$year' AND c_subject='$sub' AND c_teacher = '$fid'";
$result = mysql_query($sql);
$arr;
while($array = mysql_fetch_row($result)){
echo json_encode($array);
}
?>
HTML
<div class="modal fade" id="ClassModal" style="margin-left:-400px;margin-right:auto;" tabindex="-1" role="dialog" aria-labelledby="ClassModal" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content" style="width:1000px;">
<div class="modal-header" style="background-color:#0a4595;color:#fff">
<h4 class="modal-title" id="myModalLabel"><center>Landstand of Knowledge Learning School, Inc. [ <span id="spanclass"></span> - <span id="spanclass2"></span> ]</center></h4>
</div>
<div class="modal-body" style="height:470px;">
<div style="float:left;border:1px solid #0a4595;width:200px;height:435px;">
<div style="width:100%;height:30px;border-bottom:1px solid #0a4595;background-color:#0a4595;padding:5px;font-size:12;color:#fff">
<center>STUDENTS</center>
</div>
<div class="studname" style="width:100%;height:30px;border-bottom:1px solid #0a4595;padding:5px;font-size:12;">
<span id="studname"></span>
</div>
</div>
</div>
<div class="modal-footer" >
<button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
thank you in advance
In the for loop, you are always overriding the contents of the span instead of adding contents to the existing one so only the last item in the array will be visible
$(".studname").empty();
for (var x = 0; x < data.length; x++) {
$(".studname").find("span").append(data[x][0] + ", " + data[x][1]+'<br />');
}

Bootstrap modal confirmation delete

Hello guys I'm trying to delete a record/row from my table using a modal delete confirmation. This is what I've tried so far:
<script type="text/javascript">
$(function(){
$(".btn-show-modal").click(function(e){
e.preventDefault();
$("#dialog-example").modal('show');
});
$("#btn-delete").click(function(e) {
$("#dialog-example").modal('hide');
});
});
</script>
<table class="table table-bordered">
<?php
$stmt2 = $conn->prepare( "SELECT project_code, description
FROM tblprojects" );
$stmt2->execute();
for($i=0; $row2 = $stmt2->fetch(); $i++){
$project = $row2['project_code'];
$desc = $row2['description'];
?>
<tr>
<td><a href="project-detail.php?code=<?php echo $project; ?>">
<?php echo $project; ?></a></td>
<td><?php echo $desc; ?></td>
<td><a href="update-project.php?code=<?php echo $project; ?>" title="Update record">
<i class="icon-edit icon-white">
</i>
</a></td>
<td><a href="#<?php echo $project; ?>"
id="<?php echo $project; ?>"
data-id="<?php echo $project; ?>"
class="btn-show-modal" data-toggle="modal" title="Delete record">
<i class="icon-trash icon-white"></i></a></td>
<div class="modal hide fade" id="dialog-example">
<div class="modal-header">
<h5>Confirm Delete</h5>
</div>
<div class="modal-body">
<p class="modaltext">Are you sure you want to delete this record?</p>
</div>
<div class="modal-footer">
<a href="#" data-dismiss="modal" class="btn btn-info">No<a>
<a href="delete-project.php?code=<?php echo $project; ?>"
class="btn btn-danger" id="btn-delete">Yes<a>
</div>
</div>
</tr>
<?php
}
?>
</table>
But the problem is, when I am about to delete the last row the one that gets deleted is the first row. Why is it like that? Any ideas? Help is much appreciated. Thanks.
The problem lies in the modal generation and passing the $project value.
You are using a loop as
for($i=0; $row2 = $stmt2->fetch(); $i++){
$project = $row2['project_code'];
$desc = $row2['description'];
?>
And inside the above loop you are generating the modals so basically you will have many modals which are equal to the num of rows in the query.
Now all of them are having the same "id" i.e. "dialog-example" and once you click on the delete it pop ups the first modal from the DOM and is deleting wrong data.
Solution
For each modal you give the id as
<div class="modal hide fade" id="dialog-example_<?php echo $project; ?>">
Then in the blow code
$(".btn-show-modal").click(function(e){
e.preventDefault();
$("#dialog-example").modal('show');
});
Get the id of the element using attr("id") and append this at the end of
"dialog-example_"+{id you received}
The same thing you need to do for the hide modal as well.
UPDATE ON HOW TO DO IT
Give the modal div id as
<div class="modal hide fade" id="dialog-example_<?php echo $project; ?>">
Then in the click function to as
$(".btn-show-modal").click(function(e){
e.preventDefault();
var id = $(this).attr('id');
var modal_id = "dialog-example_"+id;
$("#"+modal_id).modal('show');
});
Change
<a href="delete-project.php?code=<?php echo $project; ?>"
class="btn btn-danger" id="btn-delete">Yes<a>
to
<a href="delete-project.php?code=<?php echo $project; ?>"
class="btn btn-danger" id="<?php echo $project ;?>">Yes<a>
AND finally
$("#btn-delete").click(function(e) {
$("#dialog-example").modal('hide');
});
to
$(".btn btn-danger").click(function(e) {
var id = $(this).attr('id');
var modal_id = "dialog-example_"+id;
$("#"+modal_id).modal('hide');
});
because you generate modal for every row this is wrong !
and show modal(first modal show) this is wrong!(this delete first row)
create one modal and set parameter with jquery e.g
$(".btn-show-modal").click(function(e){
e.preventDefault();
$("#dialog-example").modal('show');
$("#dialog-example #btn-delete").attr('href','delete-project.php?code='+$(this).attr('data-id'));
});
good luck
On topic
Problem is you have multiple modals. But select it on 1 id. So jQuery will select the first value.
A solution would be to put the delete url in an hidden input field. Then when the user clicks the open delete modal you select the url and put it in the a tag.
Example time
JavaScript Part
$(function(){
$(".btn-show-modal").click(function(e){
// put the right url in the delete
$("#dialog-example .delete-url").attr('href', $(this).attr('data-delete-url');
$("#dialog-example").modal('show');
return e.preventDefault();
});
$("#btn-delete").click(function(e) {
$("#dialog-example").modal('hide');
});
});
PHP part
I assume $stmt is prepared etc
<ul>
<? foreach($stmt->fetchAll() as $record) : ?>
<li>
delete
</li>
<? endforeach; ?>
</ul>
<div class="modal hide fade" id="dialog-example">
<div class="modal-header">
<h5>Confirm Delete</h5>
</div>
<div class="modal-body">
<p class="modaltext">Are you sure you want to delete this record?</p>
</div>
<div class="modal-footer">
<a href="#" data-dismiss="modal" class="btn btn-info">No<a>
<a class="delete-url btn btn-danger">Yes<a>
</div>
</div>
Code explaind
It is not handy to put an bootstrap modal in an foreach/for/while unless you change the id. But then again lot of duplicate code.
What the code does it changes the delete-url on the fly depending on which a the user clicked
Off topic
I highly recommend using the foreach for your iteration of the data records instead of a for loop.
$stmt2 = $conn->prepare( "SELECT project_code, description
FROM tblprojects" );
$stmt2->execute();
for($i=0; $row2 = $stmt2->fetch(); $i++){ /** code **/}
would be
$stmt2 = $conn->prepare( "SELECT project_code, description
FROM tblprojects" );
$stmt2->execute();
foreach($stmt2->fetchAll() as $record){}
Because when you open the modal, it open the first #dialog-example div.
<script type="text/javascript">
$(function(){
$(".btn-show-modal").click(function(e){
e.preventDefault();
$(this).parent().find("#dialog-example").modal('show');
});

Categories