JQuery Click function not responding to a click - javascript

I have the following JQuery script :
<script>
$(document).ready(function() {
setInterval(function() {
$.ajax({
type: "GET",
url: "<?php echo base_url(); ?>transactions/user_requests",
dataType: "JSON",
success: function(request) {
request_list = $('#request_list').empty();
if (request === null) {
request_list.append("<p>No Active Requests</p>");
}
else {
$.each(request, function(i, request) {
request_list.append('<ul><a class="request_list" id="request_list" href="#active_request_list">' + request.department_name + '</a></ul>');
$.ajax({
type: "GET",
url: "<?php echo base_url(); ?>transactions/user_requests_detials",
dataType: "JSON",
success: function(request_list) {
request_list_details = $('#request_list_details').empty();
if (request_list === null) {
request_list_detials.append("<ul>No Active Requests</ul>");
} else {
$.each(request_list, function(i, request_list) {
request_list_details.append('<dt span="font_color:white !important;">' + request_list.department_name + '</dt>\n\
<dd><label style="float:left !important;">Commodity Name:</label><span style="color:red !important;">' + request_list.commodity_name + '</span></dd>\n\
<dd><label style="float:left !important;"> Quantity Requested:</lable><span style="color:red !important;">' + request_list.total_quantity_requested + '</span></dd>\n\
<dd><label style="float:left !important;">Request Order ID:</label><span style="color:red !important;">' + request_list.request_order_id + '</span></dd>\n\
<dd><label style="float:left !important;">Date Requested : </label><span style="color:red !important;">' + request_list.date_added + '</span></dd> \n\
<a class="approve" id="approve" href="#stock_details">Approve </a>');
});
}
},
error: function(data) {
}
});
});
}
},
error: function(data) {
// alert('An error occured, kindly try later');
}
});
}, 2000);
});
</script>
<div class='request'>
<p>Request List</p><br>
<ul id='request_list'></ul>
</div>
The above loads a list of all requests made and a link for approving the details of the requests, when the link is clicked, the following script is supposed to run:
<script>
$(document).ready(function() {
alert('Alert!!!');
$('.approve').click(function() {
alert('Alert!!');
request_order_id = $('#request_order_id').val();
alert(request_order_id);
html1 = '';
htmlhead1 = '';
$.ajax({
type: "GET",
url: "<?php echo base_url();?>transactions/to_be_issued_details/" + request_order_id,
dataType: "json",
success: function(data) {
for (i = 0; i < data.length; i++) {
html1 += '<tr>\n\
<td><input type="text" id="commodity_name' + i + '" name="commodity_name[]" value="' + data[i].commodity_name + '"/></td>\n\
<td><input type="text" class="SmallInput" id="batch_no' + i + '" name="batch_no[]" value="' + data[i].batch_no + '"/></td>\n\
<td><input type="text" class="SmallInput" id="total_quantity_requested' + i + '" name="total_quantity_requested[]" value="' + data[i].total_quantity_requested + '"/></td>\n\
<td><input type="text" id="request_order_id' + i + '" name="request_order_id[]" value="' + data[i].request_order_id + '"/></td>\n\
<td><input type="text" class="SmallInput" id="total_quantity' + i + '" name="total_quantity[]" value="' + data[i].total_quantity + '"/></td>\n\
<td><input type="text" class="SmallInput" id="department' + i + '" name="department[]" value="' + data[i].department + '"/></td>\n\
<td><input type="text" class="SmallInput" id="user_name' + i + '" name="user_name[]" value="' + data[i].user_name + '"></td> \n\
<td></td><td></td></tr> ';
}
htmlhead1 += '\n\
<th>Commodity Name</th>\n\
<th>Batch Number</th> \n\
<th> Category</th> \n\
<th>Units per Pack </th> \n\
<th>No of Packs</th>\n\
<th>Total Quantity</th>\n\
';
$('#thead1').empty();
$('#tbody1').empty();
$('#thead1').append(htmlhead1);
$('#tbody1').append(html1);
},
error: function(data) {
}
})
});
});
</script>
Which is supposed to give me more details about the request, when I click the Approve button, the click function does not respond at all, which is the best way I can approach this problem?

This is because you are assigning the click event to .approve before it even exists.
What you want is to do this:
$("body").on("click", ".approve", function () {
//Your code
});
This way, using delegation, you assign a listener to the body (but preferably you should assign it to a less generic container like #request_list_details if it exists at the time you create the event listener) and the click event "bubbles up" trying to find an element with the class approve. This way you can dynamically add elements with that class and they still will respond to that event.
You can read more about it at the official jQuery API Documentation page.

Using delegation with on():
$('#request_list_details').on('click','.approve',function(){
//...
});

Related

Address a specific looped input with jQuery ajax

I have HTML code looped with another jQuery. There is an input which looped too. I want to address it in jQuery Ajax... but only the first input works... and the same values are printed for the rest in the console.
success: function (r) {
var posts = JSON.parse(r)
$.each(posts, function (index) {
$('.timelineposts').html(
$('.timelineposts').html() + '<blockquote><p>' + posts[index].PostBody + '</p><footer>Posted by ' + posts[index].PostedBy + ' on ' + posts[index].PostDate + '<button class="btn btn-default" data-id="' + posts[index].PostId + '" type="button" style="color:#eb3b60;background-image:url("none");background-color:transparent;"> <i class="glyphicon glyphicon-heart" data-aos="flip-right"></i><span> ' + posts[index].Likes + ' Likes</span></button><button class="btn btn-default comment" type="button" data-postid="' + posts[index].PostId + '" style="color:#eb3b60;background-image:url("none");background-color:transparent;"><i class="glyphicon glyphicon-flash" style="color:#f9d616;"></i><span style="color:#f9d616;"> Comments</span></button></footer><input type="text" class="c"><button comment-postid="' + posts[index].PostId + '">comment</button></blockquote>'
)
/////////////////////ajax/////////////////////////
$('[comment-postid]').click(function () {
var buttonid = $(this).attr('comment-postid');
var value = $('.c').val();
$.ajax({
type: "POST",
url: "api/comments1?id=" + buttonid,
processData: false,
contentType: "application/json",
data: '{ "commentBody": "' + value + '"}',
success: function (r) {
//var res = JSON.parse(r)
console.log(buttonid);
console.log(value);
value = "";
buttonid = "";
},
error: function (r) {
console.log("ddd")
}
});
})
})
I have figured it out!
I named each class with a different postid value...so when the loop iterates, each post will have anew class, so I address it in the ajax!
<input type="text" class="'+posts[index].PostId+'" >
and in ajax: var buttonid = $(this).attr('comment-postid');
var v=$('.'+buttonid).val();

Quick and simultaneous ajax call

I am currently working on add sale for POS using laravel. Here we can use barcode to scan the product code, when barcode is entered it then calls check function, if same product code is found in the cart table then it simply adds the quantity value by 1 else it make an ajax call which will return the detail of that particular product. My jQuery function looks like this:
function check() {
if ($(".product_code").length) {
var product_code = $("#product_code").val();
var total = $('#cart_contents tr').length;
$('#cart_contents tr').each(function(index) {
var p_code = $(this).find(".product_code").val();
if (product_code == p_code) {
var num = +$(this).find('.product_quantity').val() + 1;
$(this).find('.product_discount').val(0);
$(this).find('.product_quantity').val(num).keyup();
return false;
} else if (index === total - 1) {
populatecart();
}
});
} else {
populatecart();
$(".cart_content_area").hide();
}
}
function populatecart() {
var product_code = $("#product_code").val();
$.ajax({
url: "{{ url('getproductdata')}}",
data: {
p_id: product_code
},
datatype: "JSON",
type: "get",
success: function(data) {
if (data == 'null') {
alert('No product code found!');
} else {
$.each(data, function(k, v) {
$("#cart_contents").append('<tr>' +
'<td class="quantity"> {!! Form::text('sales_quantity[]', 1, ['class'=>'product_quantity form-control']) !!} </td>' +
'<td class="product_codes"><input type="text" name="product_code[]" value="' + v["product_code"] + '" class="form-control product_code" readonly/></td>' +
'<td><input type="text" name="product_name[]" value="' + v["product_name"] + '" class="form-control product_name" readonly/> </td>' +
'<td><input type="text" name="unit_value[]" value="' + v["sell_price"] + '" class="form-control unit_value" readonly/></td>' +
'<td>{!! Form::text('product_discount[]', 0, ['class'=>'product_discount form-control']) !!}</td>' +
'<td><input type="text" name="line_total[]" value="' + v["sell_price"] + '" class="form-control line_total" readonly/></td>' +
'<td class="remove_row"><input name="product_id[]" type="hidden" value="' + v["id"] + '" /><button type="button" class="removebutton" title="Remove this row">X</button></td>' +
'</tr>');
calculateTotalSum();
});
}
}
});
}
However, the problem here is that when I try to scan same product(ie; product having same product code) simultaneously it adds up the quantity but if i try the same thing really quick, the same product is populated into two different rows of the cart table but what I actually want is to have the quantity value of the product be 2 instead of creating 2 rows for same product code.
How can I deal with this problem?
rather than use callback based api.
I suggest you use promise based .
the flow goes like this.
var cart = {};
if(cart[product_code] == undefined)
{
cart[product_code] = $.ajax(url: "{{ url('getproductdata')}}" ,
data:{
p_id:product_code
},
datatype:"JSON",
type: "get");
cart[product_code].done(function(data){
//do the initialization
});
}
else
{
cart[product_code].done(function(){
//do the update.
});
}
The ajax calls may overlap.
You should probably do the check for existance in the ajax callback only, not already in check();

.empty() function won't work after loading contents with ajax

I did a multilevel ajax call .i.e. make an ajax call and use the id value from the call to make another call... I tried calling a jquery .empty() isn't working for the data generated in the inner ajax call... But when i place the .empty() function on the outer generated element, it worked just fine... How can i fix this issue? This is my code../
$(document).on('click', '.stories', function(e) {
e.preventDefault();
var request = $.ajax({ //first ajax call///
url: 'includes/functions.php?job=front_title',
cache: false,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
type: 'get'
});
request.done(function(output) {
if (output.result === 'success') {
$('.blog').empty();
var jsonArray = $(jQuery.parseJSON(JSON.stringify(output.data))).each(function() {
var id = this.titleID;
var storyTitle = this.story_view;
var frontTitle = '<div class="blog-item"><h3>' + storyTitle + '</h3>' + '<img class="img-responsive img-story" src="images/blog/blog1.jpg" width="100%" alt="" />' + '<div class="blog-content"><div class="entry-meta"><h4>Episodes</h4></div>' + '<div class="well" style="padding-right: 10px; padding-left: 5px; width: 105%;">' + '<ul class="tag-cloud stories">';
var request2 = $.ajax({ ////inner ajax call//////
url: 'includes/functions.php?job=story_episodes',
cache: false,
data: 'id=' + id,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
type: 'get'
});
request2.done(function(output2) {
var i = 1;
if (output2.result === 'success') {
var jsonArray2 = $(jQuery.parseJSON(JSON.stringify(output2.data))).each(function() {
var id2 = this.id;
var title = this.title;
var count = this.episode_count;
if (count == 0) {
frontTitle += id2;
} else if (i % 20 == 0) {
frontTitle += '<li data-id="' + id2 + '" id="singleEpisode"><a class="btn btn-sm btn-primary" href="#story/' + storyTitle + '/' + title + '">' + i + '</a></li></ul><ul class="tag-cloud">';
} else {
frontTitle += '<li style="margin: 1px" data-id="' + id2 + '" id="singleEpisode"><a class="btn btn-sm btn-primary" href="#story/' + storyTitle + '/' + title + '">' + i + '</a></li>';
}
i += 1;
})
}
$('.blog').append(frontTitle);
frontTitle += '</ul></div></div>';
})
})
} else {
console.log('failed');
}
});
});
I really need help for this, i av been on this for two days now... I would really appreciate the help.. or is there a better way i could do this?

AJAX is not passing data via POST to its intended URL

I want to pass an array through AJAX but I am not getting any feed back on what it is I am sending. I tried to do a var_dump($_POST); on the PHP side (next.php) but nothing is showing up. I'm guessing there is something wrong with my code.
function sendToServer(data) {
$.ajax({
type: "POST",
data: { arr: JSON.stringify(data) },
url: "next.php",
success: function() {}
});
}
next.php:
<?php
var_dump($_POST);
$data = json_decode(stripslashes($_POST['arr']));
foreach ($data as $item) {
echo $item;
// insert to db
}
?>
Full snippet of my code:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<style type="text/css">
<!-- #main {
max-width: 800px;
margin: 0 auto;
}
-->
</style>
</head>
<body>
<div id="main">
<h1>Add or Remove text boxes with jQuery</h1>
<div class="my-form">
<!-- <form action="next.php" method="post">-->
<button onclick="addAuthor()">Add Author</button>
<br>
<br>
<div id="addAuth"></div>
<br>
<br>
<button onclick="submit()">Submit</button>
<!-- </form>-->
</div>
<div id="result"></div>
</div>
<script type="text/javascript">
var authors = 0;
function addAuthor() {
authors++;
var str = '<br/>' + '<div id="auth' + authors + '">' + '<input type="text" name="author" id="author' + authors + '" placeholder="Author Name:"/>' + '<br/>' + '<button onclick="addMore(\'auth' + authors + '\')" >Add Book</button>' + '</div>';
$("#addAuth").append(str);
}
var count = 0;
function addMore(id) {
count++;
var str =
'<div id="bookDiv' + count + '">' + '<input class="' + id + '" type="text" name="book' + id + '" placeholder="Book Name"/>' + '<span onclick="removeDiv(\'bookDiv' + count + '\')">Remove</span>' + '</div>';
$("#" + id).append(str);
}
function removeDiv(id) {
$("#" + id).slideUp(function() {
$("#" + id).remove();
});
}
function submit() {
var arr = [];
for (i = 1; i <= authors; i++) {
var obj = {};
obj.name = $("#author" + i).val();
obj.books = [];
$(".auth" + i).each(function() {
var data = $(this).val();
obj.books.push(data);
});
arr.push(obj);
}
sendToServer(arr);
//$("#result").html(JSON.stringify(arr));
}
function sendToServer(data) {
$.ajax({
type: "POST",
data: {
arr: JSON.stringify(data)
},
url: "next.php",
success: function() {
}
});
}
</script>
</body>
</html>
The problem is when you try to echo the item. As $item is an object (stdClass), and the echo command expects a string, the echo command fails with "stdClass could not be converted to a string". You can either change to:
echo print_r($item, true);
or:
var_dump($item);

How to reload a jQuery plugin when appending new data to window. No reload() method provided

I'm working on a site where a user can create however many domains he wishes on a server. Each domain can belong to a group(this overall does nothing to the domain itself it's there for easier sorting).
A user can add/delete/modify each group separately.
I'm using a jQuery plugin called Spectrum so that a user can assign a color to each of his groups. See here.
I'm doing some ajax to dynamically update the groups(change the color/name). Everything is working great, except for one thing: the above mentioned plugin doesn't work properly for appended html(which I suppose is to be expected).
Normally for such a thing I'd reload the plugin, however I don't see any method in the documentation that would allow me to do that.
Is there some other way that I could reload it? Maybe some jQuery method? Bind to some event? Something?
Any help is appreciated.
function ajaxAddDomainGroup(group_color_add, group_name_add) {
$.ajax({
url: "<?= URL::route('domains_ajax_add_group'); ?>",
type: 'POST',
data: 'data[group_name]=' + group_name_add + '&data[group_color]=' + group_color_add,
success: function (data)
{
if(data.status == 'OK') {
$.notify('Group added successfully.', {
type: 'info',
delay: 120000
});
$('#js--groups_table tr:first').before(
'<tr>' +
'<td class="ccs-table__label" style="background-color: ' + data.data.group_color + '!important;"' + '>' + data.data.group_name + '</td>' +
' <td class="ccs-table__action js--groups_edit">' +
'<span class="icon-edit-ccs icon-ccs"></span>' +
'</td>' +
'<td class="ccs-table__action"><a id="delete_' + data.data.id + '" class="ccs-groups_delete" href="#"><span class="icon-delete-ccs icon-ccs"></span></a></td>' +
'</tr><tr><td colspan="3"><div class="js--edit_info css-hide_edit_info box__controls">' +
'<div class="col-md-6"> <input class="input--block js--input_group_name_edit" type="text" placeholder="New group name">' +
'</div><div class="col-md-6"><a class="btn btn--action btn--default js--group_edit btn__text" id="js--edit_' + data.data.id + '" href="#">Modify</a>' +
'<input class="js--spectrum-color-edit"/> <input type="hidden" class="js--group_color_edit" value="#000000"/> </div> </div> </td> ' +
'</tr>'
);
}
else {
$.notify('An error has occurred when trying to add the group.', {
type: 'info',
delay: 120000
});
}
}
});
}
function ajaxEditDomainGroup(group_name_edit, group_color_edit, group_id_edit) {
$.ajax({
url: "<?= URL::route('domains_ajax_edit_group'); ?>",
type: 'POST',
data: 'data[new_group_name]=' + group_name_edit + '&data[new_group_color]=' + group_color_edit + '&data[group_id]=' + group_id_edit,
success: function (data)
{
if(data.status == 'OK') {
$.notify('Group edited successfully.', {
type: 'info',
delay: 120000
});
$('#js--edit_' + group_id_edit).closest('tr').prev('tr').find('td:first-child').replaceWith(
'<td class="ccs-table__label" style="background-color: ' + group_color_edit + '!important;">' + group_name_edit + '</td>'
);
}
else {
$.notify('An error has occurred when trying to edit the group.', {
type: 'info',
delay: 120000
});
}
}
});
}
$('body').on('click','.js--group_edit', function() {
var group_name_edit = $(this).closest('td').find('.js--input_group_name_edit').val();
var group_color_edit = $(this).closest('td').find('.js--group_color_edit').val();
var group_id_edit = parseInt($(this).attr('id').replace(/[^\d]/g, ''), 10);
if($.trim(group_color_edit) == '') {
alert('The group color is required.');
return false;
}
else if( $.trim(group_name_edit) == '') {
alert('The group name is required.');
return false;
}
ajaxEditDomainGroup(group_name_edit, group_color_edit, group_id_edit);
});
Relevant html:
#foreach($domain_groups as $key => $domain_info)
<tr>
<td class="ccs-table__label"
#if(isset($domain_info['color']) && $domain_info['color'] != ''))
style="background-color: {{ $domain_info['color'] }}!important;"
#endif
>{{ $domain_info['group_name']; }}
</td>
<td class="ccs-table__action js--groups_edit">
<span class="icon-edit-ccs icon-ccs"></span>
</td>
<td class="ccs-table__action"><a id="delete_{{ $domain_info['id'] }}" class="ccs-groups_delete" href="#"><span class="icon-delete-ccs icon-ccs"></span></a></td>
</tr>
<tr>
<td colspan="3">
<div class="js--edit_info css-hide_edit_info box__controls">
<div class="col-md-6">
<input class="input--block js--input_group_name_edit" type="text" placeholder="New group name">
</div>
<div class="col-md-6">
<a class="btn btn--action btn--default js--group_edit btn__text" id="js--edit_{{ $domain_info['id'] }}" href="#">Modify</a>
<input class="js--spectrum-color-edit"/>
<input type="hidden" class="js--group_color_edit" value="#000000"/>
</div>
</div>
</td>
</tr>
#endforeach
Spectrum init and such:
$(".js--spectrum-color-edit").spectrum({
color: '#000',
showAlpha: true,showInput: true,
// Set the hext value of the color to a hidden input
move: function(color){
$(this).closest('td').find('.js--group_color_edit').val(color.toHexString());
}
});
I realize this isn't the most easy-on-the-eyes code. Odds are it's gonna be refactored in the future using angular or something like that.
You need to apply spectrum to any newly created matching elements within the dynamically loaded rows:
var $newtr = $('<tr>' +
'<td class="ccs-table__label" style="background-color: ' + data.data.group_color + '!important;"' + '>' + data.data.group_name + '</td>' +
' <td class="ccs-table__action js--groups_edit">' +
'<span class="icon-edit-ccs icon-ccs"></span>' +
'</td>' +
'<td class="ccs-table__action"><a id="delete_' + data.data.id + '" class="ccs-groups_delete" href="#"><span class="icon-delete-ccs icon-ccs"></span></a></td>' +
'</tr><tr><td colspan="3"><div class="js--edit_info css-hide_edit_info box__controls">' +
'<div class="col-md-6"> <input class="input--block js--input_group_name_edit" type="text" placeholder="New group name">' +
'</div><div class="col-md-6"><a class="btn btn--action btn--default js--group_edit btn__text" id="js--edit_' + data.data.id + '" href="#">Modify</a>' +
'<input class="js--spectrum-color-edit"/> <input type="hidden" class="js--group_color_edit" value="#000000"/> </div> </div> </td> ' +
'</tr>');
$('#js--groups_table tr:first').before($newtr)
$(".js--spectrum-color-edit", $newtr).spectrum({
color: '#000',
showAlpha: true,
showInput: true,
// Set the hext value of the color to a hidden input
move: function (color) {
$(this).closest('td').find('.js--group_color_edit').val(color.toHexString());
}
});

Categories