When I am using this code it goes in success else condition and show error. But when I refresh the page the record is deleted automatically.
Please suggest me what I can do.
jquery script:
<script>
$(document).ready(function(){
$(".delete").click(function(event){
alert("Delete?");
var href = $(this).attr("href")
var btn = $(this);
$.ajax({
type: "GET",
url: href,
success: function(response) {
if (response == "Success")
{
$(btn).closest('tr').fadeOut("slow");
}
else
{
alert("Error");
}
}
});
event.preventDefault();
})
});
</script>
View file:
<table style="width:100%" border="1" class="table">
<thead>
<tr>
<th>score Id</th>
<th>student name </th>
<th>subject Name</th>
<th>student marks</th>
<th>Action</th>
</tr>
</thead>
<?php foreach($score as $r): ?>
<tbody>
<tr><td><?php echo $r->score_id; ?></td>
<td><?php echo $r->student_name; ?></td>
<td><?php echo $r->subject_name; ?></td>
<td><?php echo $r->marks; ?></td>
<?php if($status <> 1): ?>
<?php if($admin_id == $r->admin_id): ?>
<td><a class="btn btn-info" href="<?php echo base_url(); ?>index.php/score_listing/edit/<?php echo $r->score_id; ?>" > Edit</a><a class="btn delete btn-danger" href="<?php echo base_url(); ?>index.php/score_listing/delete/<?php echo $r->score_id; ?>"> Delete</a></td>
<?php endif; ?>
<?php else: ?>
<td><a class="btn btn-info" href="<?php echo base_url(); ?>index.php/score_listing/edit/<?php echo $r->score_id; ?>" > Edit</a><a class="btn delete btn-danger" href="<?php echo base_url(); ?>index.php/score_listing/delete/<?php echo $r->score_id; ?>" > Delete</a></td>
<?php endif; ?>
</tr>
</tbody>
<?php endforeach; ?>
</table>
Controller file:
public function delete($id)
{
$admin_name = $this->session->userdata('admin_name');
log_message('debug',"this record deleted by Admin = ".$admin_name );
$score = $this->score->delete_operation($id);
$error_data = array('error' => 'Error while deleting record');;
return json_encode(array("success" => true));
}
Just change your controller function's last line:
return json_encode(array("success" => true));
to
echo 'Success';
update you controller function as,
public function delete($id) {
...
...
die('Success');
}
I just tried the below condition in script for ajax and it works. I think I am not confirming or not taking response so thats why it continuously going into else condition where error is written.
Hope this will help some one.
MY new script
<script>
$(document).ready(function(){
$(".delete").click(function(event){
var del = confirm("Delete record?");
var href = $(this).attr("href")
var btn = $(this);
if(del == true)
{
$.ajax({
type: "GET",
url: href,
success: function(response) {
if (response != "Success")
{
$(btn).closest('tr').fadeOut("slow");
}
else
{
alert("Error");
}
}
});
}
event.preventDefault();
})
});
</script>
Your ajax return an object so you cant use if (response == "Success") like this.
change code like this:
public function delete($id)
{
$admin_name = $this->session->userdata('admin_name');
log_message('debug',"this record deleted by Admin = ".$admin_name );
$score = $this->score->delete_operation($id);
$error_data = 2;
echo 1;
}
if it's true it return 1, so chage ajax like this:
if (parseInt(response)==1)
{
$(btn).closest('tr').fadeOut("slow");
}
else
{
alert("Error");
}
}
I assumed you want hide tr if response is true.
Because you passed it as an array (in javascript it will be converted as an object), the value of the response will be available as response.success. You can check the response object if you write it to the console.
Try this in your ajax method:
success: function(response) {
console.log(response);
if (response.success == true)
{
$(btn).closest('tr').fadeOut("slow");
}
else
{
alert("Error");
}
}
EDIT:
And I suggest you to change the output in your controller's method:
$this->output->set_content_type('application/json')->set_output(json_encode(array("result" => true)));
instead of
return json_encode(array("success" => true));
Related
I have the following table:
<table id="skuTable" role="grid">
<thead>
<th class="skuRow">Orden</th>
<th>Fecha Fab.</th>
<th class="skuRow">Norden</th>
<th>Color</th>
<th>Cliente</th>
<th>Metros</th>
<th>Tiempo</th>
<th>Fecha Ent.</th>
<th>Operario</th>
<th class="skuRow">Editar</th>
</thead>
<tbody>
I get the data from the machine 41
<?php
$sql = "SELECT DISTINCT Orden, FFab, N_Orden=Ordenes.OF_N_Orden, Color, Client, Metros, Tiempo, FEnt,Operario
FROM ((
Ordenes INNER JOIN VCLIENTE ON VCLIENTE.Clie_codigo = Ordenes.OF_Cod_Cli
) INNER JOIN ARTITTEC ON ARTITTEC.Tec_codigo = Ordenes.OF_Cod_Art
)
INNER JOIN VTiempos ON VTiempos.Of_n_orden= Ordenes.OF_N_Orden
AND Vtiempos.OF_LIN =Ordenes.OF_Lin
ORDER BY Orden asc, Fecha asc";
$stmt = sqlsrv_query($conn, $sql);
if ($stmt === false) {
die(print_r(sqlsrv_errors(), true));
}
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)){
?>
I write the data in the columns
<td class="orden" id="orden-<?= intval($row['Orden']) ?>"><?php echo $row['Orden'] ?></td>
<td role="gridcell"><?php echo $row['FFab']; ?></td>
<td class="norden" align="center" id="norden-<?= intval($row['N_Orden']) ?>"><?php echo $row['N_Orden']; ?></td>
<td role="gridcell"><?php echo $row['Color']; ?></td>
<td role="gridcell"><?php echo $row['Client']; ?></td>
<td role="gridcell"><?php echo $row['Metros']; ?></td>
<td role="gridcell"><?php echo $row['Tiempo']; ?></td>
<td role="gridcell"><?php echo $row['FEnt']; ?></td>
<td role="gridcell"><?php echo $row['Operario']; ?></td>
<td><input type="button" class="edit" name="edit" value="Edit"></td>
</tr></b></font>
<?php { ?>
</tbody>
</table>
<div class="k-pager-wrap k-grid-pager k-widget k-floatwrap" data-role="pager">
<span class="k-pager-info k-label"></span>
</div>
JavaScript for the Edit function:
$(document).on("click", "#skuTable .edit", function () {
var $this = $(this);
var tds = $this.closest('tr').find('td').filter(function () {
return $(this).find('.edit').length === 0;
});
if ($this.val() === 'Edit') {
$this.val('Save');
if ($this.id !== '.orden') {
tds.prop('contenteditable', true);
}
}
else {
var isValid = true;
var errors = '';
$('#myDialogBox').empty();
var elements = tds;
if (tds.find('input').length > 0) {
elements = tds.find('input');
}
var dict = {};
elements.each(function (index, element) {
var type = $(this).attr('class');
var value = (element.tagName == 'INPUT') ? $(this).val() : $(this).text();
console.log(type);
// ----- Switch statement that provides validation for each table cell -----
switch (type) {
case "norden":
dict["N_Orden"] = value;
break;
case "orden":
dict["Orden"] = value;
break;
}
})
if (isValid) {
console.log(dict);
$this.val('Edit');
tds.prop('contenteditable', false);
var request = $.ajax({
type: "POST", url: "update.php", data: dict
});
request.done(function (response, textStatus, jqXHR) {
if (JSON.parse(response) == true) {
console.log("row updated");
}
else {
console.log("row failed to updated");
console.log(response);
console.log(textStatus);
console.log(jqXHR);
}
});
// Callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown) {
// Log the error to the console
console.log(textStatus);
console.log(jqXHR);
console.error("The following error occurred: " + textStatus, errorThrown);
});
// Callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
});
}
else {
alert(errors);
}
}
});
Script Update.php:
<?php
$Orden = $_POST['Orden'];
$NOrden = $_POST['NOrden'];
$host = "xxxxxxxxxx";
$dbName = "xxxxx";
$dbUser = "xxxxxxxxxxxxxx";
$dbPass = "xxxxxxxxxxxx";
$pdo = new PDO("sqlsrv:server=" . $host . ";Database=" . $dbName, $dbUser, $dbPass);
$sql = "UPDATE Ordenes SET OF_OrdenOFs = '$Orden' WHERE OF_N_Orden = '$NOrden'";
$stmt = $pdo->prepare($sql);
//$stmt->bindValue('[:SKU Group]', $SKU);
//$stmt->bindValue(':Group_ID', $Group_ID)
$result = $stmt->execute();
echo json_encode($result);
if (!$result) {
echo json_encode(sqlsrv_errors());
}
?>
Currently when I press the edit button, it lets me edit the Order field and giving save apparently saves it for me. But when refreshing the page, the records appear blank (that is, if there was no data in the database, it continues to leave it blank and if there was a data before, not only does it not change it, but it also deletes it).
What can I be failing at?
During your JavaScript update call you seem to be setting the value you want to update to dict["N_Orden"]. However, in your Update.php you seem to be wanting the value of $_POST['NOrden'] which I don't believe is defined?
I've two different table, 1st is draft_table, and 2nd is fix_table, each table have same fields ( product & price )
i want to make data from draft_table, can be save to fix_table with checkbox, so just selected data will save to fix_table.
i've code like this :
AJAX
<script>
$(function(){
$("a.paid").click(function(){
if(confirm("Are you sure want save this?"))
{
id_array=new Array()
i=0;
$("input.chk:checked").each(function(){
id_array[i]=$(this).val();
i++;
})
$.ajax({
url:'<?php echo base_url(); ?>fix_data/set',
data:"kode="+id_array,
type:"POST",
success:function(respon)
{
if(respon==1)
{
window.parent.location.reload(true);
}
}
})
}
return false;
})
})
</script>
Views :
<?php
foreach($data_get->result_array() as $dp)
{
?>
<tr><td><input type="checkbox" name="chk[]" class="chk" value="<?php echo $dp['id_draft']; ?>" /></td>
<td><?php echo $dp['product']; ?></td>
<td><?php echo $dp['price']; ?></td>
</td></tr>
<?php
}
?>
Controller :
public function set_stts()
{
if($this->session->userdata('logged_in')!="")
{
$id_get = $this->input->post('kode');
$dt = $this->db->get_where("tbl_draft",$id_get)->row();
$product = $dt->product;
$price = $dt->price;
if ($this->input->post('kode')) {
$query = $this->db->query("INSERT INTO tbl_fix (product,price) VALUES (".$product.",".$price.")");
}
if($query){
echo 1;
}
else{
echo 0;
}
}
else
{
header('location:'.base_url().'dashboard_item');
}
}
After i Click submit in draft form, nothing happen, is there anyone may help me with this case?
Thank you
maybe you can change your controller like this :
public function set()
{
if($this->session->userdata('logged_in')!="")
{
$id_get = $this->input->post('kode');
$quer = $this->db->query("select * from tbl_draft WHERE id IN (".$id_get.")");
if ($this->input->post('kode')) {
foreach($quer->result_array() as $dp)
{
$a = $dp['product'];
$b = $dp['price'];
$query = $this->db->query("INSERT INTO tbl_fix (product,price) VALUES
('".$a."','".$b."')");
}
}
if($query){
echo 1;
}
else{
echo 0;
}
}
else
{
header('location:'.base_url().'dashboard_item');
}
}
Here is my UI Screenshot. Highlighted is the Dropdown
What i want?
As i Select any option in the Dropdown it should get updated for that particular row in Database using AJAX
Below are the Codes that i've written. I'm just a Beginner, please excuse if the code is not neat!!
I'm using Codeigniter
Front End
<?php if( is_array( $fbrecords ) && count( $fbrecords ) > 0 )
foreach($fbrecords as $r) { ?>
<tr>
<td><?php echo $r->fullname; ?></td>
<td><?php echo $r->email; ?></td>
<td><?php echo $r->mobile; ?></td>
<td><?php echo $r->message; ?></td>
<td><?php echo $r->jtime; ?></td>
<td> <?php $data=array(
'name'=>'status',
'row' => '12px',
'id' => 'status',
'selected'=>'none',
'class'=>'statusClass'
);
$data_status = array(
'none' => 'none',
'A&A' => 'Attended & Acted',
'YTA' => 'Yet to Attend',
);
echo form_dropdown($data, $data_status, set_value('status')); ?> </td>
Ajax Code - I've added a Console.log to see weather next row dropdown is being selected or not
$(document).ready( function() {
$(".statusClass").change(function(event) {
//var dropDown = document.getElementById("status");
//var status = dropDown.options[dropDown.selectedIndex].value;
var status = $("select.statusClass").val();
console.log(status);
jQuery.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "index.php/user_authentication/user_data_status_submit",
dataType: 'json',
data: {status:status},
success: function(data){
if (result)
{
alert("success");
}
}
});
});
});
Controller
public function user_data_status_submit(){
$data = array(
'status' => $this->input->post('status'),
);
//Either you can print value or you can send value to database
echo json_encode($data);
$this->login_database->feedback_update($data);
}
*Console Ouputs for the first 3 rows show the 1 row selection thrice - Below is the Screeshots of that *
You are checking the values of all select box. Instead of that you get the values which you are updating to obtain the result this keyword will use.
$(document).ready( function() {
$(".statusClass").change(function(event) {
var status = $(this).val();
I have a select-option and i choose one,i wanna change tablo value from database.
In my View :
<select id="Room" >
<option value="Joseph">Joseph Room</option>
<option value="Macro">Macro Lounge</option>
</select>
<table>
<tr>
<td>Day</td>
<?php
foreach ($posts as $post)
{
echo "<td>{$post->seancehour}</td>";
}
?>
</tr>
<tr>
<td><?php echo $post->seanceday; ?></td><td><?php echo $post->seancename; ?></td>
</tr>
</table>
I use ajax and want to change dynamiccally table value.My javascript is :
<script type="text/javascript">
$(document).ready(function () {
$('#Room').change(function () {
var room = document.getElementById("Room").value;
$.ajax({
type: 'POST',
data: {room: room},
url: '<?php echo site_url('Homepage/index'); ?>',
success: function (result) {
alert(result);//I dont know what has to be here.
}
});
});
});
</script>
In my Controller,I go mymodel and get database value.
public function index()
{
$room = $this->input->post('room');
if ($room == 'Macro')
{
$this->data['pasts'] = $this->SeanceModel->getMacro();
}
else
{
$this->data['posts'] = $this->SeanceModel->getJoseph();
}
$this->load->view('Homepage', $this->data);
}
For example when i open the page day=Sunday hour=12pm,if i change joseph or macro,this values must be change in the table.
I have updated a stock value for product on button click, I want to change my ajax code to magento prototype ajax.
My code :
<tr>
<input type="hidden" class="product_id" id="product_id" value="<?php echo $_obj->getId() ?>"/>
<td><?php echo $_obj->getId() ?></td>
<td><span class="nobr"><?php echo $_obj->getName(); ?></span></td>
<td id="stock-qty<?php echo $_obj->getId() ?>"><?php echo round($_obj->getQty()); ?></td>
<td><span class="nobr"><input type="text" name="update-stock" id="update-stock" value="<?php echo round($_obj->getQty()); ?>" class="update-stock validate-number"/>
<button type="submit" name="stockupdate" class="stockupdate" value="Submit">Update</button>
</td>
My ajax code is:
jQuery('.stockupdate').click(function() {
jQuery('#loading-mask').show();
var update_stock = jQuery(this).parents('tr').find('.update-stock').val();
var numberRegex = /^[+-]?\d+(\.\d+)?([eE][+-]?\d+)?$/;
var product_id = jQuery(this).parents('tr').find('.product_id').val();
var url = "<?php echo Mage::getUrl('marketplace/vendor/stockupdate'); ?>";
jQuery('.success-message').html('');
if(update_stock!="" && numberRegex.test(update_stock)) {
jQuery.ajax({
type: "POST",
data: ({updatestock: update_stock , product_id: product_id}),
url: url,
success: function (result) {
jQuery('.success-message').html('');
if(result != 'null'){
jQuery('#loading-mask').hide();
jQuery('#stock-qty'+product_id).text(result);
var message = "<div class='success-message' style='color:green;'>Updated Successfully.</div>";
jQuery('#stock-qty'+product_id).next('td').find('.update-stock').after(message);
}
}
});
}else{
var message = "<div class='success-message' style='color:red;'>Please enter the number.</div>";
jQuery('#stock-qty'+product_id).next('td').find('.update-stock').after(message);
}
})
Now I want to change this ajax to prototype ajax. but i am not able to do.
My prototype ajax:
function SubmitRequest()
{
var update_stock = jQuery(this).parents('tr').find('.update-stock').val();
var numberRegex = /^[+-]?\d+(\.\d+)?([eE][+-]?\d+)?$/;
var product_id = jQuery(this).parents('tr').find('.product_id').val();
var url = "<?php echo Mage::getUrl('marketplace/vendor/stockupdate'); ?>";
jQuery('.success-message').html('');
if(update_stock!="" && numberRegex.test(update_stock)) {
new Ajax.Request(url, {
method: 'POST',
parameters: ({updatestock: update_stock , product_id: product_id}),
onSuccess: successFunc,
onFailure: failureFunc
});
}
}
function successFunc(response){
alert(response);
if (200 == response.status){
alert("Call is success");
}
var container = $('notice');
var content = response.responseText;
container.update(content);
}
function failureFunc(response){
alert("Call is failed" );
}
Can anyone help me?
Thanks in advance