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();
Related
I have created a loop which contains a dropdown list and input field.
What I need is:
When I select a value from dropdown list of Fruit Genres, the Unit Price field will display value come from database. I did all of these, but could not display value to the Unit Price field.
Here is my code:
View page:
<div class="table-responsive">
<table class="table table-hover" id="item-tbl">
<thead>
<tr>
<th class="text-center">Fruit Type</th>
<th class="text-center">Fruit Genres</th>
<th class="text-center">Qty</th>
<th class="text-center">Unit Price</th>
<th class="text-center">Sub Total</th>
</tr>
</thead>
<tbody>
<?php for($i=1; $i<=3; $i++){ ?>
<tr style="">
<td><?php echo $this->Form->input('fruit_type_id', ['options'=>$fruit_types, 'empty'=>'Select Fruit Type', 'label'=>false, 'name'=>'detail_orders['.$i.'][fruit_type_id]']); ?></td>
<td><?php echo $this->Form->input('fruit_genre_id', ['options'=>$fruit_genres, 'empty'=>'Select Fruit Genre', 'label'=>false, 'name'=>'detail_orders['.$i.'][fruit_genre_id]', 'class'=>'fruit_genre']); ?></td>
<td><?php echo $this->Form->input('quantity', ['type'=>'text', 'label'=>false, 'name'=>'detail_orders['.$i.'][quantity]', 'class'=>'quantity', 'id'=>'quantity_'.$i]); ?></td>
<td><?php echo $this->Form->input('price', ['type'=>'text', 'label'=>false, 'name'=>'detail_orders['.$i.'][price]', 'class'=>'price', 'id'=>'price_'.$i]); ?></td>
<td><?php echo $this->Form->input('sub_total', ['type'=>'text', 'label'=>false, 'name'=>'detail_orders['.$i.'][price]', 'class'=>'sub_total']); ?></td>
</tr>
<?php } ?>
</tbody>
</table>
Javascript:
<script type="text/javascript">
$(document).ready(function() {
$(".fruit_genre").on('change' , function() {
var fruitGenreId = +$(this).val();
var priceId = $(this).closest('tr').find('.price').attr('id');
// alert(priceId);
$.ajax({
type: "GET",
url: baseURL+"orders/getFruitById/"+fruitGenreId+".json",
beforeSend: false,
success : function(returnData) {
if(returnData.response.code == '200'){
console.log(returnData.response.data.unit_price);
// $(this).closest('tr').find('.price').val(returnData.response.data.unit_price);
$(priceId).val(returnData.response.data.unit_price);
};
}
})
}).trigger('change');
});
OrdersController.php
public function getFruitById($id){
$this->viewBuilder()->layout('ajax');
$this->loadModel('FruitGenres');
$item = $this->FruitGenres->get($id);
if (!empty($item)) {
$response['code'] = 200;
$response['message'] = 'DATA_FOUND';
$response['data'] = $item;
}else{
$response['code'] = 404;
$response['message'] = 'DATA_NOT_FOUND';
$response['data'] = array();
}
$this->set('response', $response);
$this->set('_serialize', ['response']);
}
I have got the expected data to the javascript console. but could not pass the data to the input field.
I have tried:
$(this).closest('tr').find('.price').val(returnData.response.data.unit_price);
instead of
$(priceId).val(returnData.response.data.unit_price);
into the ajax success function, but it did not worked.
if I add a static id like the following:
$('#price_1').val(returnData.response.data.unit_price);
then it works.
Can anyone please help me? I am stuck on it.
I am using cakephp 3 for my project.
priceId is a value like price_1 without #. To make it a selector by id - prepend it with #:
$("#" + priceId).val(returnData.response.data.unit_price);
You can even simplify your code:
// you get id of the found element so as to find this element again
// you can store founded element instead of it's id
var priceDiv = $(this).closest('tr').find('.price');
// in success callback:
priceDiv.val(returnData.response.data.unit_price);
You can select the element directly instead of getting its ID and select with another jQuery call.
Another thing to note - this in the submit callback refer to the callback function itself, not the element.
$(document).ready(function() {
$(".fruit_genre").on('change' , function() {
var fruitGenreId = +$(this).val();
var $price = $(this).closest('tr').find('input.price'); // Get the element
$.ajax({
type: "GET",
url: baseURL+"orders/getFruitById/"+fruitGenreId+".json",
beforeSend: false,
success : function(returnData) {
if(returnData.response.code == '200'){
console.log(returnData.response.data.unit_price);
// Use $price directly as a jQuery object
$price.val(returnData.response.data.unit_price);
};
}
})
}).trigger('change');
});
I usually figure things out for myself but this one is giving me a really difficult time. I need to change the text value of a button in a table that is created by php from a database, after it gets clicked on.
<td id="order_num"><?php echo $order -> order_num; ?></td>
<td><?php echo $order -> data; ?></td>
<td><?php echo $order -> data; ?></td>
<td><?php echo $order -> data; ?></td>
<td><?php echo $order -> data; ?></td>
<td><?php echo $order -> data; ?></td>
<td><?php echo $order -> data; ?></td>
<td><?php echo $order -> data; ?></td>
<!-- **** this is the button. ******** -->
<td><button type="submit" class="accept_order" id ="row_<?php echo $order -> order_num; ?>"
data-row_id = "row_<?php echo $order -> order_num; ?>" data-current_user = "<?php echo $user_id; ?>"
data-order_num = "<?php echo $order -> order_num; ?>">Accept</button>
here is the big mess of an ajax call
$(document).ready(function () {
$('.shop').on('click', 'button', function(e){
var button = $(this).find('button'); //trying to put the value of the current button in a variable to pass to the ajax function.
var current_user = $(this).closest('.shop').find('.accept_order').data('current_user');
console.log(current_user);
var row_id = $(this).closest('.shop').find('.accept_order').data('row_id');
var accepted_order = $(this).closest('.shop').find('.accept_order').data('order_num');
console.log(accepted_order);
e.preventDefault();
$.ajax('url', {
type: "POST",
data: { order_id: accepted_order, user_id: current_user },
success: function(msg){
console.log(msg);
console.log(this);
//change the text of the button to something like "accepted"
***************this is where I have problems ***********************
$(this).html('accepted'); or
$(this).closest('.shop').find('button').html(msg); or
button.text(msg);
},
error: function(){
$(this).closest('.shop').find('.accept_order').html("failure");
}
});
});
});
</script>
I did use $('button').html(msg);
but that changes all of the buttons. It seems like I lose scope to the object when inside the success function. Any ideas or help will be greatly appreciated. Thanks in advance.
I believe I found your problem source but I'm not sure. And The problem came from this keyword because this in the ajax function direct to the ajax object not the button node object. So you can use bind function in the success and error functions to make this directs to the button. here is the modification:
and another thing the url in ajax function is a variable not a string as you wrote above.
$.ajax(url, {
type: "POST",
data: { order_id: accepted_order, user_id: current_user },
success: function(msg){
console.log(msg);
console.log(this);
//change the text of the button to something like "accepted"
***************this is where I have problems ***********************
$(this).html('accepted'); or
$(this).closest('.shop').find('button').html(msg); or
button.text(msg);
}.bind(this),
error: function(){
$(this).closest('.shop').find('.accept_order').html("failure");
}.bind(this)
});
I'm not sure from the solution because there is no demo for what you asked about.
I hope it works.
Maybe you can use the class to select the button
$.ajax('url', {
type: "POST",
data: { order_id: accepted_order, user_id: current_user },
success: function(msg){
console.log(msg);
console.log(this);
//change the text of the button to something like "accepted"
***************this is where I have problems ***********************
$("button.accept_order").html(msg);
},
error: function(){
$(this).closest('.shop').find('.accept_order').html("failure");
}
});
or better..
var button = $(this);
and inside your ajax call just use:
button.html(msg);
In each row, i want to add a editable td to insert "mavandon" into DATABASE dsdonhang. I read this on http://phppot.com/php/php-mysql-inline-editing-using-jquery-ajax/ but it doesn't work :((
<script src="../lib/jquery-3.1.0.min.js"></script>
<script>
$(document).ready(function(){
function saveToDatabase(editableObj,column,idd) {
$.ajax({
url: "saveedit.php",
type: "POST",
data:'column='+$(this).column+'&editval='+$(this).editableObj.innerHTML+'&idd='+$(this).idd,
success: function(data){
$(editableObj).css("background","#FDFDFD");
//alert ("hello");
}
error: function() {}
});
}
});
</script>
<?php $query = mysqli_query($conn,"SELECT * FROM dsdonhang");
while($row=mysqli_fetch_assoc($query)) {$data[] = $row;}
foreach($data as $k=>$v) {
?>
<tr>
<td><?php $madon = $data[$k]["idd"];echo $k+1; ?></td>
<td><?php echo $data[$k]["ngaydat"]; ?></td>
<td><?php echo $data[$k]["hoten"]; ?></td>
<td><?php echo $data[$k]["diachi"]; ?></td>
<td><?php echo $data[$k]["sdt1"]; ?></td>
<td><?php echo $data[$k]["donhang"]; ?></td>
<td><?php echo $data[$k]["tongtien"]; ?>.000VNĐ</td>
<td><?php echo $data[$k]["nguoinhan"]; ?></td>
<td contenteditable="true" onchange="saveToDatabase(this,'mavandon','<?php echo $madon; ?>')"><?php echo $data[$k]["mavandon"]; ?></td>
<td>Xem</td>
</tr>
<?php
}
?>
saveedit.php
<?php
require_once("../lib/connection.php");
mysqli_query($conn,"UPDATE dsdonhang set " . $_POST["column"] . " = '".$_POST["editval"]."' WHERE idd='".$_POST["idd"]."'");
?>
Any help? Thanks
use onblur instead of onchange
<td contenteditable="true" onblur="saveToDatabase(this,'mavandon','<?php echo $madon; ?>')" onClick="showEdit(this);"><?php echo $data[$k]["mavandon"]; ?></td>
Typo / incorrect while passing params in the ajax call. Modify it as mentioned below
add this in ajax call.
'&idd='+idd
Instead of this
'&idd='+$(this).idd
Make sure that ur event is getting called.(u can check in firebug also.)
Pass parameters as
{column: $(this).column,editval:$(this).editableObj.innerHTML,idd:$(this).idd}
Try this:
<script>
$(document).ready(function(){
function saveToDatabase(editableObj,column,idd) {
var data = {'column':$(this).column,'editval':$(editableObj).text(),'idd':$(this).idd };
$.ajax({
url: "saveedit.php",
type: "POST",
contentType: "application/json; charset=utf-8",
datatType: "json",
data:JSON.stringify(data),
success: function(data){
$(editableObj).css("background","#FDFDFD");
console.log("received data=>"+data);
alert ("hello");
}
error: function(err) {
console.log("error=>"+err); //print error if exist
}
});
}
});
</script>
I am getting no response from ajax request . i am posting a ajax call to processor.php file and the processor.php file is processing the file and sending the processed file back to javascript i am gerring my result in my console log but it is not showing in the html.
My javascript code is :
function add_to_cart(item_name,item_price){
$('.user-info').slideUp('1200');
$('.cart-status').slideDown('1200');
var dataString = "item_name=" + item_name + "&item_price=" + item_price + "&page=add_to_cart";
$.ajax({
type: "POST",
url: "php/processor/processor.php",
data:dataString,
beforeSend:function(){
$(".cart-show-product").html('<h3>Your Cart Status</h3><img src="images/loading.gif" align="absmiddle" alt="Loading...." class="center" /><br><p class="center">Please Wait...</p>');
},
success: function(response){
console.log(response);
$(".cart-show-products").html(response);
}
});
}
and my php is :
if(isset($_POST['item_name']) && !empty($_POST['item_name']) && isset($_POST['item_price']) && !empty($_POST['item_price']))
{
$sql = mysqli_query($conn,
'SELECT * FROM
products_added
where
username = "'.mysqli_real_escape_string($conn, $_SERVER['REMOTE_ADDR']).'"
and
item_added="'.mysqli_real_escape_string($conn, $_POST['item_name']).'"'
);
if(mysqli_num_rows($sql) < 1)
{
mysqli_query($conn,
"INSERT INTO products_added values(
'',
'".mysqli_real_escape_string($conn, $_SERVER['REMOTE_ADDR'])."',
'".mysqli_real_escape_string($conn, $_POST['item_name'])."',
'".mysqli_real_escape_string($conn, $_POST['item_price'])."',
'".mysqli_real_escape_string($conn, '1')."',
'".mysqli_real_escape_string($conn, $_POST['item_price'])."'
'".mysqli_real_escape_string($conn, date("d-m-Y"))."')"
);
?>
<table class="cart-show-products">
<thead>
<tr>
<td>Sl.No</td>
<td>Item</td>
<td>Qty</td>
<td>Price</td>
<td>Action</td>
</tr>
</thead>
<tbody>
<?php
$sl_no = 1;
$sql = mysqli_query(
$conn,
'SELECT sum(amount) as grandtotal
FROM products_added
WHERE username = "'.mysqli_real_escape_string($conn, $_SERVER['REMOTE_ADDR']).'"
ORDER BY id'
);
$row = mysqli_fetch_array($sql);
$grandtotal = strip_tags($row['grandtotal']);
$sql = mysqli_query(
$conn,
'SELECT
id,
item_added,
price,
quantity
FROM products_added
WHERE username = "'.mysqli_real_escape_string($conn, $_SERVER['REMOTE_ADDR']).'"
ORDER BY id'
);
$row = mysqli_fetch_array($sql);
$item_id = strip_tags($row['item_id']);
$item_name = strip_tags($row['item_added']);
$item_price = strip_tags($row['price']);
$quantity = strip_tags($row['price']);
?>
<tr class="items_wrap items_wrap<?php echo $item_id; ?>">
<td><?php echo $sl_no++; ?></td>
<td><?php echo $item_name ?></td>
<td><?php echo $quantity ?></td>
<td><?php echo $item_price ?></td>
<td><i class="fa fa-times"></i></td>
</tr>
</tbody>
</table>
<?php
}
If you're getting a response in the console, then the issue must be with your HTML. I think part of the problem is you've created a section on the HTML page wiht a class that is the same as the table the AJAX call is bringing into the page. I would suggest changing the HTML element to us an ID instead. Something like
<div id="products-table"></div>
And then change your JavaScript to
function add_to_cart(item_name,item_price){
$('.user-info').slideUp('1200');
$('.cart-status').slideDown('1200');
var dataString = "item_name=" + item_name + "&item_price=" + item_price + "&page=add_to_cart";
$.ajax({
type: "POST",
url: "php/processor/processor.php",
data:dataString,
beforeSend:function(){
$("#products-table").html('<h3>Your Cart Status</h3><img src="images/loading.gif" align="absmiddle" alt="Loading...." class="center" /><br><p class="center">Please Wait...</p>');
},
success: function(response){
console.log(response);
$("#products-table").html(response);
}
});
}
If you stay with the class names you've used, subsequent updates are going to have problems because you'll have 2 elements on the page with the same class. Your script could potentially be confused about which one to change.
If this is your actual code, then you have a syntax error in your PHP file. There are a missing close bracket for:
if(isset($_POST['item_name']) && !empty($_POST['item_name']) && isset($_POST['item_price']) && !empty($_POST['item_price']))
The second problem is, you are not print anything, if this condition has failed.
Note
You do not need to use isset, if you are checking empty. empty will return false, if the variable not set.
You can debug your respons by check NET tab in your web developer tools, or see, what is the response of the AJAX.
I am using codeigniter to load data on datatables, on the data table each row has a link that when clicked data is sent elsewhere. The data in that particular row should disappear and only links that have not been clicked remain. I have managed to do that with AJAXbut on success i am forced to reload the page on jQuery timeout
sample:
//Table headers here
<tbody class="tablebody">
<?php foreach ($worksheets as $sheets) : ?>
<tr>
<td><?php echo $sheets->filename ?></td>
<td class="bold assign">
<?php echo $sheets->nqcl_number ?>
<?php echo anchor('assign/assing_reviewer/' . $sheets->nqcl_number, 'Assign') ?>
<a id="inline" href="#data">Assign1</a>
<input type="hidden" id="labref_no" value="<?php echo $sheets->nqcl_number; ?>" />
</td>
<td><?php echo $sheets->uploaded_by ?></td>
<td><?php echo $sheets->datetime_uploaded ?></td>
<td></td>
</tr>
<?php endforeach; ?>
</tbody>
I would like that on AJAX success, the row of the datatables where the link was is dynamically removed from the table without page refresh.
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>assign/sendSamplesFolder/" + labref,
data: data1,
success: function(data) {
var content = $('.tablebody');
$('div.success').slideDown('slow').animate({opacity: 1.0}, 2000).slideUp('slow');
$.fancybox.close();
//Reload the table data dynamically in the mean time i'm refreshing the page
setTimeout(function() {
window.location.href='<?php echo base_url();?>Uploaded_Worksheets';
}, 3000);
return true;
},
error: function(data) {
$('div.error').slideDown('slow').animate({opacity: 1.0}, 5000).slideUp('slow');
$.fancybox.close();
return false;
}
});
I have tried this but it loads two same pages. what's the work around?
content.load(url);
You can use fnDraw() to force the datatable to re-query the datasource. Try this:
// store a reference to the datatable
var $dataTable = $("#myTable").dataTable({ /* Your settings */ });
// in the AJAX success:
success: function(data) {
$dataTable.fnDraw();
},
Have a read of the fnDraw entry in the documentation.
var $dataTable = $("#myTable").dataTable({ /* Your settings */ });
var oSettings = $dataTable.fnSettings();
var page = Math.ceil(oSettings._iDisplayStart / oSettings._iDisplayLength);
$dataTable.fnPageChange(page);