Select checkbox - > click button - > update table values - jquery-plugins

initially values under reattempt column will be blank . Once we select checkboxes of some rows and click on button reattempt , i want to update the values of column reattempt to reattempt.
html
<button id="reattempt">reattempt</button>
<tr>
<th class="table-header">Reattempt</th>
</tr>
<tr>
<td id="<?php echo $orderrecords[$k]["tracking_id"];?>reattempt">
<?php echo $orderrecords[$k]["reattempt"]; ?>
</td>
</tr>
script
$('#reattempt').click(function() {
var selected = [];
$('.assigneeid-order:checked').each(function() {
selected.push($(this).val());
$('.assigneeid-order').prop('checked', false);
});
var jsonString = JSON.stringify(selected);
$.ajax({
type: 'POST',
url: 'reattempt.php',
data: { data: jsonString },
success: function(response) {
response = $.parseJSON(response);
$.each(response, function(index, val) {
$('#' + index + '').html(val);
$('#' + index + 'reattempt').html(val.reattempt);
});
}
});
});
reattempt.php
$data = json_decode(stripslashes($_POST['data']));
foreach($data as $id)
{
$orderid = $id;
$reattempt='';
$sqlecom = "UPDATE do_order set reattempt = '$reattempt' where tracking_id=".$orderid;
$db_handleecom = new DBController();
$resultecom = $db_handleecom->executeUpdate($sqlecom);
$response[$orderid] = [ 'reattempt' => $reattempt ];
}
echo json_encode($response);
Result
Values not updating , below is response :

You are setting all of your checkboxes to unchecked with $('.assigneeid-order').prop('checked', false);, please edit with $(this).prop('checked', false); which will point to the current checkbox in the loop. Also, update your html with missing TDs
Nothing in your code is updating because in your php file, you are setting $reattempt=''; and without any further changes, you are returning it as empty.. So, you can't expect other than an empty value..

Related

How to remove dublicate values using codeigniter and ajax?

I return passports from my database when I select user using codeigniter and I'm getting these data using ajax.
This is my php code in the controller:
public function contactsPassports(){
// POST data
$this->load->model('contacts/contacts_international_pass_m');
$data = $this->input->post();
$passports = array();
$where = array('contact_id'=>$data['selected_id']);
$passports = $this->contacts_international_pass_m->where($where)->order_by('id','DESC')->get_all();
if(!empty($passports)) {
foreach($passports as $item)
{
$item->pass = $this->contacts_international_pass_m->get($item->nat_passport_num);
}
}
$this->data->passports = $passports;
echo json_encode($this->data);
}
And this is my ajax code:
$.ajax({
url:'/companies/ajax/contactsPassports',
method: 'post',
data: {"selected_id": contactID},
dataType: 'json',
async: true,
success: function(data){
var html = '';
$.each(data.passports, function(key, value) {
console.log(data);
html += '<div class="nationality_name" style="float:left">'+ value.nat_passport_num + '</div>' + '<div class="nationality_name_delimiter" style="float:left">'+', '+'</div>';
});
$('#passport').html(html);
}
});
But I want to remove the dublicate passports for every user. For example now I am getting this:
User 1
12345678, 1234, 1234, 123456, 123456
And I want to getting this:
User 1
12345678, 1234, 123456
You can use distinct query builder to select only distinct values:
$passports = $this->contacts_international_pass_m->distinct()->select('nat_passport_num')->where($where)->order_by('id','DESC')->get_all();

AJAX 500 Internal Server ERROR But The Proccess is Success

I am Facing Problem With Ajax It Keep Showing 500 internal Server Error
But The Ajax Proccess is Success I don't know Why I Have Been Trying To Fix This All Day But I Got Nothing But Weird Is The Process Is Success
Here is My Ajax Code
<script type="text/javascript" >
$(document).ready(function(){
$('#add_button').click(function(){
$('#user_form')[0].reset();
$('.modal-title').text("Add User");
$('#action').val("Add");
$('#user_uploaded_image').html('');
})
var dataTable = $('#user_data').DataTable({
});
$(document).on('click', '.delete_image', function(){
var user_id = $(this).attr("id");
var link = $(this).attr("style");
var mana = $(this).attr("name");
//console.log()
var dom_parent = $(this).context.parentElement.parentElement
if(confirm("Apakah Anda Yakin Ingin Menghapus Data Gambar Ini?"))
{
$.ajax({
url:"<?php echo base_url(); ?>produk/hapus_gambar",
method:"POST",
data:{mana:mana,link:link,user_id:user_id},
success:function(data)
{
alert(data);
}
});
}
else
{
return false;
}
});
});
</script>
And This Is My Button Code
<td align="center"> <button type="button" name="gambar" id="<?=$list_produk['id']?>" class="btn btn-danger delete_image" style="<?= $list_produk['gambar']; ?>"><img style="width:120px; height:120px;" src="http://localhost/proyek/gambar/thumb/<?=$list_produk['gambar']?> "></button></td>
Here Is My Script That Handle The Process
function hapus_gambar() {
$data['link'] = $_POST['link'];
$data['id'] = $_POST['user_id'];
$data['mana'] = $_POST['mana'];
$select =$this->db->query('SELECT `gambar` FROM `produk` WHERE `id` = "'.$data['id'].'"');
foreach($select->result_array() as $gambar) {
unlink('./gambar/'.$data['link']);
unlink('./gambar/thumb/'.$data['link']);
}
$query =$this->db->query("DELETE '".$data['mana']."' FROM `produk` WHERE id = '".$data['id']."' ");
echo 'Data Telah Dihapus';
}
I Am Using Codegniter
Thank You
SOLVED
Turns Out Some Of My Query Makes It Error
So I change My Query Little Bit And It Works
Thanks For The Help

PagedList MVC With JQuery UI Autocomplete Causing Error

I'm trying to use JQuery UI Autocomplete on a text box to filter through a Paged List and dynamically update the list so it only shows anything that starts with the value from the filter. However whenever I start typing into the search box I get the following error:
Syntax Error: Unexpected Token <
Here's my controller:
[HttpGet]
public ActionResult Index(string filter, int currentPage = 1)
{
List<string> allEmails = null;
if (!string.IsNullOrEmpty(filter))
{
allEmails = dataContext.Emails
.Where(x => x.email.StartsWith(filter))
.Select(x => x.email)
.ToList();
}
else
{
allEmails = dataContext.Emails
.Select(x => x.email)
.ToList();
}
PagedList<string> model = new PagedList<string>(allEmails, page, pageSize);
ViewBag.Emails = allEmails.OrderBy(x => x).Skip((page - 1) * pageSize).Take(pageSize);
ViewBag.Filter = filter;
return View(model);
}
Here's My view:
#model PagedList<string>
#using PagedList
#using PagedList.Mvc
<div id="paginatedDiv">
<table id="pageinatedTable">
<tr>
<th>
Email
</th>
</tr>
#foreach (var item in ViewBag.Emails)
{
<tr>
<td>
#item
</td>
</tr>
}
</table>
#Html.PagedListPager(Model,
(page) => Url.Action("Index", "Home", new
{
page,
pageSize = Model.PageSize,
filter = ViewBag.Filter
}),
PagedListRenderOptions.ClassicPlusFirstAndLast)
</div>
#Html.TextBox("search")
#section scripts
{
<script type="text/javascript">
$(document).ready(function () {
$('#search').autocomplete({
source: function(request, response)
{
$.ajax({
url: '#Url.Action("Index", "Home")',
dataType: "json",
contentType: 'application/json, charset=utf-8',
data: {
filter : $("#search").val(),
page : '#Model.PageNumber'
},
error: function (xhr, status, error) {
alert(error);
}
})},
minlength: 1
});
});
</script>
}
Is what I'm trying to do here possible? Am I going about it the wrong way? If you need more information let me know.
The Ajax function is returning a HTML error which is trying to getting parsed to the function. It will fail and error out because the first character will be '<' like

How can I reload HTML table after AJAX success on Django web page?

I'm using two datepickers from the jQuery library for start and end dates. Once I have the two dates I send them to my django view via ajax. I then run the model query in my views which will return a filtered dict into my django context. My question now is how can I reload the table on the template?
Would I have to define a Javascript function to load a table and call it on ajax success? Or perhaps a better way?
html
<table class="table table-bordered">
<tr>
<th>Start Date: <input id="mail_start_date"/></th>
<th>End Date: <input id="mail_end_date"/></th>
<th><button id='btn'>Filter</button></th>
</tr>
<tr>
<th>Desk</th>
<th># of Packages</th>
</tr>
{% for desk, count in pick_dict.items %}
<tr>
<td>{{desk}}</td>
<td>{{count}}</td>
</tr>
{% endfor %}
Javascript
$(document).ready(function(){
$('#mail_start_date').datepicker({ dateFormat: "yy-mm-dd" });
$('#mail_end_date').datepicker({ dateFormat: "yy-mm-dd" });
$('#btn').click(function(){
var start = $('#mail_start_date').val();
var end = $('#mail_end_date').val();
$.ajax({
url: "/apps/centraldesk/mail/stats/",
type: "POST",
data: {
'start': start,
'end': end,
csrfmiddlewaretoken: '{{ csrf_token }}',
},
success: "SOMTHING NEEDS TO HAPPEN HRERE"
});
});
views.py
def mail_stats(request):
pick_dict = {}
if request.is_ajax():
pick_start = request.POST['start']
pick_end = request.POST['end']
pick_start = str(pick_start)
pick_end = str(pick_end)
in_date = datetime.datetime.strptime(pick_start, "%Y-%I-%d")
out_date = datetime.datetime.strptime(pick_end, "%Y-%I-%d")
pick_list = MailRecord.objects.filter(timeIn__range=(pick_start, pick_end))
for item in pick_list:
if pick_dict.has_key(item.desk.name):
pick_dict[item.desk.name] += 1
else:
pick_dict[item.desk.name] = 1
context = {
"mail_list" : mail_list,
"pick_dict" : pick_dict,
}
return render("mail_stats.html", context, context_instance=RequestContext(request, processors=[custom_proc]))
Yes, you define a javascript function, like so
...
},
success: function(json) {
// Access your table here and manipulate it with the returned data from "json" (json is the dictionary given by your django view)
}
});
...
You could also add an error-function next to the success function.

jQuery on 'keyup' no longer working after AJAX request

I have a shopping cart application that will change the cart prices on the page 'on-the-fly' using an AJAX request using the following updateCart() function - it calls the render_cart() function to display each item in the basket using an 'keyup' event.
For some reason it all works fine on the initial keyup press - but if I attempt to do this again it doesnt' work, even though I can see the .cart-qty class on the input field, can anyone suggest why this is happening?
// on keyup event call the update cart function
$(".cart-qty").on('keyup',function( e ) {
var qty = $(this).val(); // e.g '2'
var rowid = $(this).data("rowid"); // e.g 740fdjhirtj3swnjf463
$( ".basket-item" ).remove();
updateCart( qty, rowid );
} );
function updateCart( qty, rowid ){
$.ajax({
type: "POST",
url: "/cart/ajax_add_item",
data: { rowid: rowid, qty: qty },
dataType: 'json',
success: function(data){
render_cart(data);
}
});
}
function render_cart(json) {
total = json.total;
cart = json.contents;
var html = '';
if (cart) {
$.each(cart, function (i, item) {
html += '<div class="basket-item"><div class="col-sm-6 col-no-pad"><p><img class="img-responsive" src="'+ item.custom.image +'" alt="'+ item.name +'" /></p><div class="remove-item"><p><a class="btn btn-sm btn-yellow" href="#">Remove</a></p></div></div><div class="col-sm-6 col-no-pad"><p class="model"><span class="heading">Model:</span><br />'+ item.name +'<br />'+ item.options.attributes +'</p><p class="buyer"><span class="heading">Buyer:</span>'+ item.options.merchant +'</p><p class="price"><span class="heading">Price:</span>$'+ item.subtotal.toFixed(2) +'</p><p class="condition"><span class="heading">Condition:</span>'+ item.options.condition +'</p><p class="quantity"><span class="heading">Quantity:</span><input type="text" class="form-control cart-qty" value="'+ item.qty +'" data-rowid="'+ item.rowid +'" /></p></div></div>';
})
}
$('#basket_start').after( html );
$('#total-value').text( total );
}
You need to use event delegation .on() for dynamically added elements like this
$(document).on('keyup','.cart-qty',function( e ) {
Bind it to document or the closest static parent
$('.cart-qty').on('keyup', (function(event) {
//do code
}));

Resources