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
}
});
Related
good evening, I have dynamically filled my table from the database. at the end of each row I have a button.
my idea is : when i clicked the button the row is hidden. I succes to recuperate the id of each row but jquery code does not work and my console doesn't return any error. i don't know where the problem is? or even if the process is correct.
also,at the latest i hope to replace the button with a checkbox but i don't know how to apply my idea with a checkbox
<table name="table" class="table" border="1">
<tbody>
<?php
include 'controller.php';
$controller1 = new Controller();
$res = $controller1->array();
while ($donne = $res->fetch()) {
?>
<tr id="<?php $donne['id'] ?>">
<td> <?php echo $donne['operateur'] ?></td>
<td> <?php echo $donne['machine'] ?></td>
<td> <?php echo $donne['declaration'] ?></td>
<td>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method='post' style="display: inline;">
<input type='hidden' id='id' name='id' value="<?php echo $donne['id']; ?>" />
<input type='submit' name='validate' id='validate' value='validate' />
</form>
</td>
</tr>
<?php
}
?>
</table>
and this is my jQuery code
if (isset($_POST['id']) && !empty($_POST['id'])) {
?>
<script>
$(document).ready(function () {
$("#validate").click(function () {
var i = $("#id").val();
var i = i.toString()
$("#" + i).hide();
});
});
</script>
<?php
}
use JQuery to hide the preferred row bi either id or class after loading dynamically.
this is an example:
// Denotes total number of rows.
var rowIdx = 0;
// jQuery button click event to add a row.
$('#addBtn').on('click', function () {
// Adding a row inside the tbody.
$('#tbody').append(`<tr id="R${++rowIdx}">
<td class="row-index text-center">
<p>Row ${rowIdx}</p></td>
<td class="text-center">
<button class="btn btn-danger remove"
type="button">Remove</button>
</td>
</tr>`);
});
Consider the following.
$(function() {
$(".validate").click(function() {
var i = $(this).closest("tr").attr("id");
$("#" + i).hide();
var url = "<?php echo $_SERVER['PHP_SELF']; ?>";
$.post(url, {
id: i,
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table name="table" class="table" border="1">
<tbody>
<tr id="row-1">
<td>
operateur 1
</td>
<td>
machine 1
</td>
<td>
declaration 1
</td>
<td>
<button class="validate">Validate</button>
</td>
</tr>
<tr id="row-2">
<td>
operateur 2
</td>
<td>
machine 2
</td>
<td>
declaration 2
</td>
<td>
<button class="validate">Validate</button>
</td>
</tr>
<tr id="row-3">
<td>
operateur 3
</td>
<td>
machine 3
</td>
<td>
declaration 3
</td>
<td>
<button class="validate">Validate</button>
</td>
</tr>
</table>
This will apply the callback to each Button. When the button is clicked,the Row is hidden and the ID is posted to your PHP Script.
i find my mistake .i have set the same id for each button,that's wrong,so i use class instead of id also in this way i could recuperate the id simply and apply .hide()
<script type="text/javascript">
$(".validate").click(function () {
var num = $(this).parents("tr").find("td:eq(0)").text();
alert(num);
});
</script>
i delete the form also because there is no need anmore
At the folloing code,I try to delete a row using ajax .serialize() but it only deletes the first row.Using jQuery(this).closest('form').find('input[name="id"]').val(); also returns "Undefined" for ID.
Ajax Code
function AjaxDelete() {
var rowId = $("#sil").serialize();
var confirmation = confirm("Are you sure of deleting the following user:"+rowId);
if (confirmation) {
$.ajax({
type:'POST',
url:'sil.php', //deleting file
data: rowId,
success:function(cevap){
alert("User has been successfully removed.ID="+rowId);
}
});
}
return confirmation;
};
Table Structure
echo '<table id="kullanicilar" align=center>
<thead>
<tr>
<td></td>
<td>ID</td>
<td>Kullanıcı Adı</td>
<td>Yönetici</td>
<td colspan=4>İşlemler</td>
</tr>
</thead>
';
while($results->fetch()){ //fetch values
echo '<tr>
<td><input type="checkbox" name="select[]" value="'.$id.'"></td>
<td>'.$id.'</td>
<td>'.$kullanici_adi.'</td>
<td>'.$yonetici.'</td>
<td><form method="post" id="sil"><input type="hidden" name="id" value="'.$id.'" class="id"></form><img src="img/delete.png" title="Sil"></td>
<td><img src="img/edit.png" title="Düzenle"></img></td>
<td>Gönderilerini Gör</td>
<td><a target="_blank" href="#" class="gor">Profilini Gör</a></td>
</tr>
'
;
}
echo '</table><br/>';
In your while loop, you are giving same id to inputs which is wrong. you can try:
<a href="#" onclick="return AjaxDelete("'.$id.'");" class="link"><form method="post" id="sil">
and then in your ajax:
function AjaxDelete(x) {
var rowId = x;
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).
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'm increasing my system by entering the functionality of loading a page inside a div dynamically, in the other words, the central area of the page is updated. For this I am using the JQuery. But even I having a problem which is the following, when submitting the same FORM one has to load the next page via JQuery-Ajax to send the post to use the data on this second page.
The funny thing is that I'm not getting the pick. Submit() the FORM always and only in one case. I will post the HTML below the two situations:
In the html code below warning test that I created within the form.submit () is being displayed.
<form id="form" accept-charset="utf-8" name="frmPadrao" method="POST" action="HTTP://localhost/fwsibe/index.php/acesso/listarSistemasValidar">
<br>
<fieldset id="tabelainfo" style="width: 560px;">
<legend style="color: #083C06;">
<b>Dados</b>
</legend>
<br>
<table id="tabelainfo">
<tbody>
<tr>
<td>
<b>SIBE:* </b>
</td>
<td>
<select name="slSibe">
</td>
</tr>
<tr>
<td>
<br>
</td>
</tr>
<tr>
<td colspan="2">
<input class="button" type="submit" value="Confirmar" name="btConfirmar">
</td>
</tr>
</tbody>
</table>
</fieldset>
<br>
<br>
</form>
In the second code warning. Submit () is not displayed, or is not recognized submission form:
<form id="form" accept-charset="utf-8" name="frmPadrao" method="POST" action="HTTP://localhost/sibe/index.php/almembal/motivoajustealm/pesquisar">
<br>
<fieldset id="tabelainfo" style="width: 560px;">
<legend style="color: #083C06;">
<b>Filtrar por:</b>
</legend>
<br>
<table id="tabelainfo">
<tbody>
<tr>
<td>
<b>SubTipo Produto:* </b>
</td>
<td>
<select name="slSubTipo">
</td>
</tr>
<tr>
<td>
<br>
</td>
</tr>
<tr>
<td colspan="2">
<input class="button" type="submit" value="Confirmar" name="btConfirmar">
</td>
</tr>
</tbody>
</table>
</fieldset>
<br>
<br>
<div>
<a title="" onclick="window.open('HTTP://localhost/sibe/index.php/almembal/motivoajustealm/incluir', '_blank', 'width=800,height=600,scrollbars=yes,status=yes,resizable=yes,screenx=0,screeny=0');" href="javascript:void(0);">Incluir</a>
</div>
<br>
<table id="tabelainfo">
<tbody>
<tr id="corpotabela">
<td align="center">Não existem Motivos de Ajuste cadastrados para esta pesquisa.</td>
</tr>
</tbody>
</table>
</form>
Below the JQuery script that is already properly initialized in the HEAD of the page, in addition, already tested for other enventos as $ (this). Click and everything is ok.
$(document).ready(function() {
$("#form").submit(function() {
alert("SUBMIT FORM");
// alert($(this));
// console.log($(this));
// $.post($(this).attr("action"), $(this).serialize(), function(data) {
// $("#divCentral").html(data);
// });
// return false;
});
});
Could you help me find the bug that causes. Submit () is not recognized by JQuery?
Edited:
I already discovered the source of the problem. Looks like that when the component is drawn for a page loaded by jquery-ajax, the event .submit() doesn't works, but when the page is loaded for default away, the event works.
The problem is that the is loaded by Ajax, and the JQuery function don't recognize it. I'am creating the function for load the central page of the template by a ajax request to a file. I have two functions, the first just for test, and the second I'am creating for works with the $_POST. The JQuery function for now is well:
function carregaUrl(url) {
//alert("carregaUrl=" + url);
$("#divCentral").load(url);
console.log($('form').attr('name'));
}
function carregaUrl2(url) {
var data = $("form").serialize();
$.ajax({
type: "POST",
url: url,
data: data
}).done(function(data) {
$("#divCentral").html(data);
});
}
What is happening here, is that the handler fires, starts the alert, and then form submit occurs, effectively reloading your page.
You need your event handler to return false if you want to prevent this submit and stay on your current page, or add an alert to the page you're going with this submit.
If you want to stay on your current page, try this:
jQuery(function($){
function formSubmit(form) {
$.post(form.attr('action'), form.serialize(), function(data){
$("#some-outer-container-with-form").html(data);
});
$("#form").submit(function(){ return formSubmit(form) }); //we need to rebind
return false;
}
$("#form").submit(function(){ return formSubmit( $(this) ) });
});