i am trying to delete values with check box using ajax call can any one help me out.
unable to find the error and one nore thing this is a template and i hav a feature of check all inbuilt so do need to change anyinbuilt code for check box
This is my listing form:
<form id="stafflistForm">
<input type="hidden" name="checkedids" value="<?php echo $staffResults['id_staff']; ?>">
<button id="deleteChecked"><i class="fa fa-trash-o"></i></button>
</form>
This my Ajax Script:
<script language="JavaScript">
$("#deleteChecked").click(function()
{
$("#delshowMessageDiv").hide();
$("#delshowMessage").html('');
$.ajax({
url: "staffcontroller.php",
method: "POST",
data: { delData : $("#stafflistForm").serialize(), 'action':'delete'},
dataType: "json",
success: function (response) {
if(response["success"]==true)
{
$("#delshowMessageDiv").hide();
$("#delshowSuccessMessageDiv").show();
$("#delshowSuccessMessage").html(response["message"]);
}else{
$("#delshowMessageDiv").show();
$("#delshowMessage").html(response["message"]);
}
},
error: function (request, status, error) {
$("#hshowMessageDiv").show();
$("#hshowMessage").html("OOPS! Something Went Wrong Please Try After Sometime!");
}
});
return false;
});
</script>
And this is my controller page:
else if($_REQUEST['action']=='delete'){
$delids=explode(",",$_REQUEST["checkedids"]);
$count=count($delids);
for($i=0;$i<$count;$i++)
{
$delQuery= $conn->query("DELETE FROM os_staff WHERE id_staff=".$delids[$i]);
}
if($delQuery){
$response['message'] = "<strong>Success!</strong>Staff Deleted Successfully.";
$response['success'] = true;
}else{
$response['message'] = "<strong>Warning!</strong> Staff Not Deleted.Please Check Carefully..";
$response['success'] = false;
}
echo json_encode($response);
exit;
}
First of all: Dont use html attribute id if you using it multipli id="deleteChecked". Use class selector or data attribute instead.
Here is a small script which show you how you can improve your code.
That should be help you to solve your issue.
$(document).ready(function() {
$('.delete-user').on('click', function(e) {
// do here your ajax
// this is just example
$(this).parents('tr').remove();
});
});
.fa-trash-o {
padding: 3px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>
<form class="stafflistForm">
<input type="hidden" name="checkedids" value="<?php echo $staffResults['id_staff']; ?>">
<button class="delete-user"><i class="fa fa-trash-o"></i></button>
</form>
</td>
<td>Tom</td>
</tr>
<tr>
<td>
<form class="stafflistForm">
<input type="hidden" name="checkedids" value="<?php echo $staffResults['id_staff']; ?>">
<button class="delete-user"><i class="fa fa-trash-o"></i></button>
</form>
</td>
<td>Peter</td>
</tr>
<tr>
<td>
<form class="stafflistForm">
<input type="hidden" name="checkedids" value="<?php echo $staffResults['id_staff']; ?>">
<button class="delete-user"><i class="fa fa-trash-o"></i></button>
</form>
</td>
<td>Son Goku</td>
</tr>
<tr>
<td>
<form class="stafflistForm">
<input type="hidden" name="checkedids" value="<?php echo $staffResults['id_staff']; ?>">
<button class="delete-user"><i class="fa fa-trash-o"></i></button>
</form>
</td>
<td>Gozilla</td>
</tr>
</table>
The PHP script should set the correct mime type via:
header('Content-type: application/json');
Besides that: Why do you have separate DIV containers for the error and success messages? Why not have one "feedback" div, which gets a CSS class which does the formating (based on error or success).
Related
Hello I am just learning codeigniter, here I am displaying a database and there are several rows. I made a delete function with ajax, it worked, but it had to be reloaded, how so that when I click delete, the data is deleted and it doesn't have to be refreshed.
<tbody id="tbody">
<?php
$no = 1;
foreach ($temporary as $m) { ?>
<tr>
<input type="hidden" class="form-control" name="id_service" value="<?php echo $m->id_service ?>">
<input type="hidden" class="form-control" name="id_cs" value="<?php echo $m->id_cs ?>">
<input type="hidden" class="form-control" name="jenis" value="<?php echo $m->jenis ?>">
<td>
<input type="hidden" class="form-control" name="id_tmp" value="<?php echo $m->id_tmp ?>">
<input type="text" class="form-control" name="" value="<?php echo $m->tracking_number ?>">
</td>
<td>
<button type="button" class="btn btn-danger" onclick="deletes(<?php echo $m->id_tmp;?>)">Delete</button>
</td>
</tr>
<?php } ?>
</tbody>
ajax
function deletes(id){
if (confirm("Are you sure?")) {
$.ajax({
url: '<?php echo base_url();?>backend/inbound/del',
type: 'post',
data: {id_tmp:id},
success: function () {
alert('ok');
},
error: function () {
alert('gagal');
}
});
} else {
alert(id + " not deleted");
}
}
Another way you can use .closest() for more details Click here
Php Code
<tbody id="tbody">
<?php
$no = 1;
foreach ($temporary as $m) { ?>
<tr class="jsRowDelete">
<input type="hidden" class="form-control" name="id_service" value="<?php echo $m->id_service ?>">
<input type="hidden" class="form-control" name="id_cs" value="<?php echo $m->id_cs ?>">
<input type="hidden" class="form-control" name="jenis" value="<?php echo $m->jenis ?>">
<td>
<input type="hidden" class="form-control" name="id_tmp" value="<?php echo $m->id_tmp ?>">
<input type="text" class="form-control" name="" value="<?php echo $m->tracking_number ?>">
</td>
<td>
<button type="button" class="btn btn-danger" onclick="deletes(<?php echo $m->id_tmp;?>,this)">Delete</button>
</td>
</tr>
<?php } ?>
</tbody>
Jquery Code
function deletes(id,oElem) {
if (confirm("Are you sure?")) {
$.ajax({
url: '<?php echo base_url();?>backend/inbound/del',
type: 'post',
data: {
id_tmp: id
},
success: function() {
//alert('ok');
console.log($(oElem).closest(".jsRowDelete"));
$(oElem).closest(".jsRowDelete").remove();
//or
//$(oElem).closest("tr").remove();
},
error: function() {
alert('gagal');
}
});
} else {
alert(id + " not deleted");
}
}
You can check the working example click here
Since you've mentioned it's deleting on the backend or your database, you could just use jquery to delete that row on the UI. Here's one way without modifying your markup.
First is you add a class to the input field that contains the ID. I used id-input
<input type="hidden" class="form-control id-input" name="id_tmp" value="<?php echo $m->id_tmp ?>">
Then use this ajax to navigate through the input fields with that class and value to delete the row. See my code on success function;
function deletes(id){
if (confirm("Are you sure?")) {
$.ajax({
url: '<?php echo base_url();?>backend/inbound/del',
type: 'post',
data: {id_tmp:id},
success: function () {
// loop through all input with class id-input
$(".id-input").each(function(){
// if it matches the value delete parent row
if($(this).val() == id){
// delete parent row
$(this).parent().parent().remove();
}
});
},
error: function () {
alert('gagal');
}
});
} else {
alert(id + " not deleted");
}
}
EDIT: use .parent().parent() as we need to refer to tr, not td
A part on my page is responsible for multiple picture uploads, it worked for a while but it is not working anymore.
I'm using a WampServer Version 3.1.7 64bit and testing on localhost.
I have tried accepting and sending datas via ajax instead of html submit, but i didn't get datas on php side either, but on client side i had all datas before sending ( FormData() ).
HTML part:
<div class="div_shadow_here">
<form id="gallery_data" method="post" enctype="multipart/form-data">
<input type="hidden" name="formid" value="<?php echo $_SESSION[" formid "]; ?>" />
<table class="news_table">
<tr>
<td>
<p class="name_col">Gallery name:</p>
</td>
<td>
<input class="input_news" id="gallery_title" type="text" name="gallery_title" />
</td>
</tr>
<tr>
<td>
<p class="name_col">Picture(s):</p>
</td>
<td>
<input class="input_news" id="news_picture_path" type="file" name="picture_path[]" multiple />
<label id="label_for_input" for="picture_path">Select picture(s)</label><span id="uploadState"></span>
</td>
</tr>
<tr>
<td></td>
<td>
<div id="img_container"></div>
</td>
</tr>
</table>
<button class="print_button hidden_a" type="submit" name="login" id="save_news" form="gallery_data">Save</button>
</form>
</div>
PHP part for testing:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
echo '<script>console.log("Not empty")</script>';
if (isset($_POST['formid'])) {
echo '<script>console.log("'.$_POST['formid'].
'")</script>';
}
if (isset($_POST['gallery_title'])) {
echo '<script>console.log("'.$_POST['gallery_title'].
'")</script>';
}
if (isset($_FILES['picture_path']['name'])) {
echo '<script>console.log("'.count($_FILES['picture_path']['name']).
'")</script>';
}
} else {
echo '<script>console.log("Empty")</script>';
}
I get Notice: Undefined index: gallery_title.. errors without isset($_POST['gallery_title']) testing (same for all other input fields).
Ajax for testing:
$('body').on('click', '#save_news', function(e) {
e.preventDefault();
var formData = new FormData($(this).parents('form')[0]);
for (var key of formData.keys()) {
console.log(key);
}
for (var value of formData.values()) {
console.log(value);
}
$.ajax({
url: 'galleryupload.php',
type: 'POST',
success: function(data) {
alert("Data Uploaded: " + data);
},
data: formData,
cache: false,
contentType: false,
processData: false
});
return false;
});
I have multiple form and each form is getting submitted but not the first one.
I tried everything like event.preventDefault();
MY CODE :
<?php for($i=0;$i<=5;$i++){ ?>
<form id="form<?php echo $i; ?>>
<td><?php echo $i++ ?><td>
<td><input type="text" name="detention_unloading_charges" value="<?php echo $history[$i]->name; ?>"></td>
<td><input type="text" name="dtn_chrg_per_day" value="<?php echo $history[$i]->dtn_chrg_per_day; ?>"></td>
<td><input type="text" name="dtn_chrg" value="<?php echo $history[$i]->dtn_chrg; ?>"></td>
<td>
<button class="btn btn-secondary" type="button" onclick="save_changes(<?php echo $i ?>);">Save Changes</button></td>
</form>
}
and jquery function:
function save_changes(id)
{
$.ajax({
url: "History/update",
type: "POST",
data: $('#form'+id).serialize(),
success: function(data) {
// Success message
console.log(data);
if(data==1){
$('.success_pop_up').addClass('show').removeClass('d-none');
} else{
$('.failure_pop_up').addClass('show').removeClass('d-none');;
}
}
});
}
You are incrementing $i twice in the beginning itself by echo $i++, which also increments $i apart from for loop , so loop runs only thrice and form id is form0 but corresponding function is save_changes(1) , where that form id does not exist at all , try below code.
<?php for($i=0;$i<=5;$i++){ ?>
<form id="form<?php echo $i; ?>>
<td><?php echo $i?><td>
<td><input type="text" name="detention_unloading_charges" value="<?php echo $history[$i]->name; ?>"></td>
<td><input type="text" name="dtn_chrg_per_day" value="<?php echo $history[$i]->dtn_chrg_per_day; ?>"></td>
<td><input type="text" name="dtn_chrg" value="<?php echo $history[$i]->dtn_chrg; ?>"></td>
<td>
<button class="btn btn-secondary" type="button" onclick="save_changes(<?php echo $i ?>);">Save Changes</button></td>
</form>
<?php } ;?>
Try this code and let me know if it works.
You'll probably want to solve this the following way:
Let the button do a default submit like so:
<button type="submit">Send</button>
Catch the submit event for your form in jQuery:
$('form').on('submit', function(e) {
// Prevent default so the browser doesnt automatically submit it.
e.preventDefault();
var data = $(this).serialize();
// ... send it
});
This way it is much easier to do AJAX form requests.
I have a simple ajax (jquery version) script and very short php function and they works fine without problem.
When I submit the value from the form input are, the ajax will work to send and get result from
the php script, in this case to get a total amount of the book order.
The Ajax script and html section are as follows:
<script language="JavaScript">
$(document).ready(function() {
$("form").mouseout( function() {
// get field value
var qtyVal = $('#qty').val();
// use HTTP GET get ajax
$.ajax({
type: 'GET',
url: 'getSunBody.php',
data: { qty : qtyVal,
},
success: function(data) {
//get xml value
$('#result').html($(data).find('qty').text());
$('#result1').html($(data).find('caution').text());
}
});
return false;
});
});
</script>
<body>
Total price:<div id="result" class="box" style="height=350px;"></div><div id="result1" class="box" style="height=350px;"></div>
<form>
<p>
<label>quantity: </label>
<input type="text" id="qty" name="qty"/>
<br/>
<input type="submit" value="submit">
total price:</p>
<p> </p>
</form>
And the following php script serving as xml also works fine with above ajax request:
<?php
// XML document
header("Content-Type: text/xml");
header("Content-Type:text/html; charset=utf-8");
// get field values
$qty = (isset($_POST["qty"]) ) ? $_POST["qty"] : $_GET["qty"];
echo "<?xml version=\"1.0\" ?>";
echo "<datetime>";
echo "<qty>" . $qty*100 . "</qty>";
$total=$qty*100;
if ($total==0)
echo "<caution>"."please input number!"."</caution>";
else if ($total<=500)
echo "<caution>"."you shoud buy more!"."</caution>";
echo "";
echo "</datetime>";
?>
However when I combine the above scripts with my shopping cart foreach loops, it doesn't work and the ajax script failed to get variables from the form input area. I don't know if it is a variable scope issue (globals or local)? or anything else?
The following is the total script I would like to fixed with:
<script language="JavaScript">
$(document).ready(function() {
$("form").mouseout( function() {
// get value from the form
var qtyVal = $('#qty').val();
// get
$.ajax({
type: 'GET',
url: 'getSunBody.php',
data: { qty : qtyVal,
},
success: function(data) {
// get XML value
$('#result').html($(data).find('qty').text());
$('#result1').html($(data).find('caution').text());
}
});
return false;
});
});
</script>
</head>
<body>
<table border="1" align="center">
<tr>
<th>no</th>
<th>name</th>
<th>price</th>
<th>qty</th>
<th>update</th>
</tr>
<?php
foreach( $_SESSION["psn"] as $i => $data ){
?>
<form action="sessionCartUpdate.php">
<input type="hidden" name="psn" value="<?php echo $_SESSION["psn"][$i];?>">
<tr>
<td><?php echo $_SESSION["psn"][$i];?></td>
<td><?php echo $_SESSION["pname"][$i];?></td>
<td><?php echo $_SESSION["price"][$i];?></td>
<td><input type="text" id="qty" name="qty" value="<?php echo $_SESSION["qty"][$i];?>"></td>
<input type="submit" name="qty"
<td><input type="submit" name="btnUpdate" value="update" />
<input type="submit" name="btnDelete" value="delete" />
</td>
</tr>
</form>
<?php
}
?>
<tr><td colsan="5">total amount:<div id="result" class="box" style="height=350px;"></div><div id="result1" class="box" style="height=350px;"></div></td></td>
</table>
<p>continue to shop
<p>Put your order
</body>
</html>
I would be very grateful if anyone can offer kind or possible suggestion or advice?
My goal is to put different number (variables) in the "input area" (name or id as "qty") throught the using of ajax to get a total amount of price and show the result in the div box (id="result" or "result1").
You should replace the id attribute with class because id is supposed to be unique in the dom and using class you can do a loop to get all quantities of the items in the cart
Another thing i have noticed that you have made the an individual form foreach item in the cart there should be one form having the multiple fields,also remove this line <input type="submit" name="qty" it doesent makes sense
<form action="sessionCartUpdate.php">
<?php
foreach( $_SESSION["psn"] as $i => $data ){
?>
<input type="hidden" name="psn" value="<?php echo $_SESSION["psn"][$i];?>">
<tr>
<td><?php echo $_SESSION["psn"][$i];?></td>
<td><?php echo $_SESSION["pname"][$i];?></td>
<td><?php echo $_SESSION["price"][$i];?></td>
<td><input type="text" class="qty" name="qty[]" value="<?php echo $_SESSION["qty"][$i];?>"></td>
<td><input type="submit" name="btnUpdate" value="update" />
<input type="submit" name="btnDelete" value="delete" />
</td>
</tr>
<?php
}
?>
</form>
<script language="JavaScript">
$(document).ready(function() {
$("form").mouseout( function() {
var qtyVal =0;
$( ".qty" ).each(function() {
qtyVal =qtyVal + parseInt($(this).val());
});
// get
$.ajax({
type: 'GET',
url: 'getSunBody.php',
data: { qty : qtyVal,
},
success: function(data) {
// get XML value
$('#result').html($(data).find('qty').text());
$('#result1').html($(data).find('caution').text());
}
});
return false;
});
});
</script>
// get field values
$qty = (isset($_POST["qty"]) ) ? $_POST["qty"] : $_GET["qty"];
Instead of using both $_GET and $_POST, you can use $_REQUEST which will give data from either POST or GET.
I have a View which calculates entries to be edited,deleted using javascript. The id's are calculated according to ticked checkboxes and are stored in an array which need to be sent to controller-method to either edit or delete...I read somewhere that ideally variables should not be sent from View to Controller in Codeigniter. How can i do it differently?
View
function checkedAll() {
var rowlength=document.getElementById("check").rows.length;
z=document.getElementById("check").getElementsByTagName("input")[0].checked;
for(var i=1;i<rowlength-1;i++)
{
document.getElementById("check").getElementsByTagName("input")[i].checked = z;
}
}
function del(){
var rowlength=document.getElementById("check").rows.length;
var id = new Array();
for(var i=1;i<rowlength-1;i++)
{
var t = document.getElementById("check").getElementsByTagName("input")[i].checked;
var y = document.getElementById("check").rows[i].cells;
id[i]=y[0].innerHTML;
}
}
</script>
</head>
<body>
<table id="check" >
<tr>
<th>S.No</th>
<th>Name</th>
<th>Age</th>
<th>Qualification</th>
<th> <input type="checkbox" onclick='checkedAll()'/> </th>
</tr>
<?php
$check=0;
$flag=0;
$my_checkbox=array();
foreach($forms as $ft): ?>
<tr id="<?php echo $check;?>" class="<?php echo $d ?>">
<td > <?php echo $ft['serial']; ?> </td>
<td> <?php echo $ft['name'] ;?></td>
<td> <?php echo $ft['age'] ;?></td>
<td> <?php echo $ft['qualification'] ;?></td>
<td> <input type="checkbox" /></td>
</tr>
<?php $check++ ?>
<?php endforeach ?>
<tr>
<td colspan="5" align="center">
<button type="button" name="create" id='but' value="Create"
onclick = "Redirect();" >Create </button>
<button type="button" name="edit" onclick="edit();" id='but' >Edit </button>
<button type="button" name="delete" id='but' onclick="del(); " >Delete </button>
</td>
</tr>
</table>
<form action="<?php $this->load->helper('url');echo site_url('form/edit');?>" method="POST" id="myForm" >
<input type="hidden" name="snap" id="snap">
</form>
</body>
Create method in the controller that accepts this array and processes it, use jquery ajax to send this data to a controller... no need for a reload, no problems with direct call.
On the other hand, you can create controller method which is called directly, and after processing array redirects back to the view to emulate staying there. I do not recommend this because it is 5-6 years old approach.
Drop me a comment if you need more detailed directions on this.
Here is example code:
var data = //your variable to be sent
$.ajax({
type: "POST",
url: "/controller/method",
data: data,
success: function(result) {
// data is returned by controller
},
error: function(){
console.log('ERROR');
//for errors thrown by PHP exceptions and other backend features
//or you can return result also and fetch an exception if you go for try - catch, which I highly recommend
}
});