I have problem inserting modal button inside my html table. I'm using AJAX and append built in function. I tried this approach
" Open modal"
but it did'nt work. I tried to remove the button properties like 'class', 'type' , etc and it worked but I need those. Any approach for this. Thank you.
This is my code
<script type=text/javascript>
$(document).ready(function() {
});
function getData(id){
$('#myModal').modal('show');
$.ajax({
type: "GET",
url: "getproducts/",
dataType: 'json',
data: {id: id},
success: function (response) {
var len = 0;
if(response['data'] !=null){
len = response['data'].length;
}
$('#userTable tbody').empty();
if(len > 0){
for(i = 0; i < len; i++) {
var p_id = response['data'][i].p_id;
var p_name = response['data'][i].p_name;
var p_amount = response['data'][i].p_amount;
var m_fname = response['data'][i].m_fname;
var tr_str =
"<tr>" +
"<td>" + p_id + "</td>"+
"<td>" + p_name + "</td>" +
// HOW CAN I ADD MODAL BUTTON HERE THIS APPROACH DOESN'T WORKED
"<td> <button type="button" class="btn btn-primary" data-bs-toggle="modal"
data-bs-target="#myModal2">Open modal</button></td>"
"<tr>";
$('#userTable tbody').append(tr_str);
}
}
}
});
};
</script>
Expected output should be like this
I think the problem with string concatenation
I am giving a code. please replace it.
"<td> <button type='button' class='btn btn-primary' data-bs-toggle='modal'
data-bs-target='#myModal2'>Open modal</button></td>"
Related
I have a table the outputs as MYSQL VALUEJAVASCRIPT TIMER
and im looking at re calling the AJAX that sends across the mysql result to update it in the table without restarting the timer.
but i get a unexpected token ) and no matter which way i write it a still get unexpected token line 56 ,I have tried changing it to }); or } and get the same all throughout and if i remove it it says its missing
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
url: 'fetch.php',
type: 'get',
//type: 'post',
dataType: 'JSON',
success: function(response){
var len = response.length;
for(var i=0; i<len; i++){
var beacon = response[i].beacon;
var location = response[i].location;
var tr_str = "<tr>" +
"<td align='center'>" + beacon + "</td>" +
"<td align='center'> <span class='minutes'>00</span>:<span
class='seconds'>00</span> </td>" +
"</tr>";
$("#userTable tbody").append(tr_str);
}
}
})
});
function updateTable() {
$.ajax({
url: 'fetch.php',
type: 'get',
//type: 'post',
dataType: 'JSON',
success: function(response){
var len = response.length;
for(var i=0; i<len; i++){
var beacon = response[i].beacon;
var location = response[i].location;
var tr_str = "<tr>" +
"<td align='center'>" + beacon + "</td>" +
"</tr>";
$("#userTable tbody").append(tr_str);
}
}
});
var updateTableInterval = setInterval(updateTable, 5000);
});
</script>
Your variable updateTableInterval is inside your AJAX option object. Moves it one line below.
Then, your function updateTable is not closed, so adds a } at the end.
Finally, your $(document).ready anonymous function is not closed either. Adds }) at the very end.
Do not forget to also close your <script> tag.
For the last three points, I said that because your code snippet have not all these. But maybe it is right on your local code.
I’m trying to update values in a table pulled in from MySQL but the function is not re-running?
Alternatively, if there is another solution to allow me to update the values from the MySQL database on a 60 second interval please let me know.
EDIT: error has been resolved but now i get a new error instead of replacing the mysql value in the table cell it adds new cells into the table what part of the code would need to be changed or added to resolve this?
The code below returns no errors:
<script type="text/javascript">
$(document).ready(function(){
console.log(1+0);
$.ajax({
url: 'fetch.php',
type: 'get',
//type: 'post',
dataType: 'JSON',
success: function(response){
var len = response.length;
for(var i=0; i<len; i++){
var beacon = response[i].beacon;
var location = response[i].location;
var tr_str = "<tr>" +
"<td align='center'>" + beacon + "</td>" +
"<td align='center'> <span class='minutes'>00</span>:<span class='seconds'>00</span> </td>" +
"</tr>";
$("#userTable tbody").append(tr_str);
}
setInterval(updateTable, 10000);
}
})
})
function updateTable() {
console.log(1+1);
$.ajax({
url: 'fetch.php',
type: 'get',
//type: 'post',
dataType: 'JSON',
success: function(response){
var len = response.length;
for(var i=0; i<len; i++){
var beacon = response[i].beacon;
var location = response[i].location;
var tr_str = "<tr>" +
"<td align='center'>" + beacon + "</td>" +
"</tr>";
$("#userTable tbody").append(tr_str);
}
}
});
};
</script>
If you format it well you'll see that youre setInterval is inside your function...
You sould place it in the $(document).ready callback function.
$(document).ready(function () {
$.ajax({
url: 'fetch.php',
type: 'get',
//type: 'post',
dataType: 'JSON',
success: function (response) {
var len = response.length;
for (var i = 0; i < len; i++) {
var beacon = response[i].beacon;
var location = response[i].location;
var tr_str = "<tr>" +
"<td align='center'>" + beacon + "</td>" +
"<td align='center'> <span class='minutes'>00</span>:<span class='seconds'>00</span> </td>" +
"</tr>";
$("#userTable tbody").append(tr_str);
}
// <===== You should place youre set interval here
}
})
});
function updateTable() {
console.log(1 + 1);
$.ajax({
url: 'fetch.php',
type: 'get',
//type: 'post',
dataType: 'JSON',
success: function (response) {
var len = response.length;
for (var i = 0; i < len; i++) {
var beacon = response[i].beacon;
var location = response[i].location;
var tr_str = "<tr>" +
"<td align='center'>" + beacon + "</td>" +
"</tr>";
$("#userTable tbody").append(tr_str);
}
}
});
var updateTableInterval = setInterval(updateTable, 10000);
}
It looks like you are calling setInterval(updateTable) from inside updateTable.
You're not calling updateTable from anywhere outside of updateTable, which means the function is never running, and the setInterval is never executed.
To fix, either:
Put your setInterval outside of updateTable, or
Add updateTable() to the end of your script.
I recommend the former.
Instead of using setInterval,
setInterval(updateTable, 10000);
try using setTimeout after you process and update the table:
function updateTable() {
$.ajax({
...
,complete: function(data){
// do something
setTimeout(updateTable, 10000);
...
});
}
This will allow your code to wait for the information to arrive prior to make another request and not be considered a DoS attack.
Let me know if this works for you or not. We can try something else.
I'm generating a table using jQuer, Ajax .
All the thing working fine but the edit button not working perfectly.
I want to copy all data-(properties) on click.
If I do the same with php it works fine, But I need using jquery.
here is my code.
==================== table code ===========
$("#get_spare_list").click(function() {
var ht = "";
$.ajax({
url: "<?php echo base_url('Spare/get_all_spare_json'); ?>",
type: 'POST',
dataType: 'json',
data: {"param1": 'value1'},
})
.done(function(data) {
var no = 1;
var ht = "<table class='table'><thead><tr><th>No</th><th>Name</th><th>Code</th><th>Min qty</th><th>uni</th><th>Group</th><th>Sub Category</th><th>Part Number</th><th>Location</th><th>Image</th><th>Barcode</th><th>Tyre</th><th>Back</th></tr></thead>";
$.each(data, function(key, val) {
ht +="<tr>"+"<td>"+no+"</td>"+"<td>"+val.name+"</td>"+"<td>"+val.code+"</td>"+"<td>"+val.min_qty+"</td>"+"<td>"+val.unit+"</td>"+"<td>"+val.group+"</td><td>"+val.sub_category+"</td><td>"+val.part_number+"</td><td>"+val.location+"</td>";
if (val.image) {
ht += "<td><a target='_blank' href='"+"<?php echo base_url('../images/'); ?>/"+val.image+"'><button class='fa fa-picture-o'></button></a></td>";
}else{
ht += "<td></td>";
}
ht += "<td><button class='btn btn-info btn-xs' onclick=PrintBar('val.code')>Print</button></td>";
ht +="<td>"+val.tyre+"</td>";
ht += "<td>";
if (val.reusable) {
ht +="yes";
}else{
ht+="no";
};
ht += "</td>";
ht += "<td><button class='btn edit btn-info btn-xs' data-toggle='modal' data-target='#editModel' data-id='"+val.id+"' data-name='"+val.name+"' data-code='"+val.code+"' data-min_qty='"+val.min_qty+"' data-unit='"+val.unit+"' data-group='"+val.group+"' data-sub_category='"+val.sub_category+"' data-part_number='"+val.part_number+"' data-location='"+val.location+"' data-tyre_number='"+val.tyre+"' data-back='"+val.reusable+"'><span class='fa fa-edit'></span></button></td>";
ht += "</tr>";
no++;
});
$("#js_res").append(ht);
console.log(ht);
})
.fail(function() {
alert("error");
});
});
======== Class code to copy data ============
$(".edit").click(function() {
$("#id").val($(this).data('id'));
$("#name").val($(this).data('name'));
$("#code").val($(this).data('code'));
$("#min_qty").val($(this).data('min_qty'));
$("#unit").val($(this).data('unit'));
$("#group").val($(this).data('group'));
$("#sub_category").val($(this).data('sub_category'));
$("#part_number").val($(this).data('part_number'));
var location = $(this).data('location');
var l1 = location.split("->");
$("#room").val($.trim(l1[0]));
$("#rake").val(l1[1]);
$("#line").val(l1[2]);
$("#box").val(l1[3]);
if ($(this).data('tyre_number')) {
$("input[name=tyre][value=" + $(this).data('tyre_number') + "]").prop('checked', true);
}else{
$("input[name=tyre][value='']").prop('checked', true);
};
if ($(this).data('back') == "1") {
$("#back").attr('checked', true);
}else{
$("#back").removeAttr('checked');
};
});
Instead of click function you can use .on() function
$(document).on('click','.edit', function() { will bind the event on the .edit elements which are not present at the time of binding event. This is called event delegation
$(document).on("click", ".edit", function() {
// your code here
})
This is because the element is dynamically generated, so does not exist on initial page load.
Use $.fn.on()
From the documentation
$(staticAncestors).on(eventName, dynamicChild, function() {});
In your case, it would be:
$(document).on("click", ".edit", function() {
$("#id").val($(this).data('id'));
$("#name").val($(this).data('name'));
$("#code").val($(this).data('code'));
$("#min_qty").val($(this).data('min_qty'));
$("#unit").val($(this).data('unit'));
$("#group").val($(this).data('group'));
$("#sub_category").val($(this).data('sub_category'));
$("#part_number").val($(this).data('part_number'));
var location = $(this).data('location');
var l1 = location.split("->");
$("#room").val($.trim(l1[0]));
$("#rake").val(l1[1]);
$("#line").val(l1[2]);
$("#box").val(l1[3]);
if ($(this).data('tyre_number')) {
$("input[name=tyre][value=" + $(this).data('tyre_number') + "]").prop('checked', true);
}else{
$("input[name=tyre][value='']").prop('checked', true);
};
if ($(this).data('back') == "1") {
$("#back").attr('checked', true);
}else{
$("#back").removeAttr('checked');
};
})
For more detail on why this doesn't work, see: Event binding on dynamically created elements?
I have a page that uses a couple of AJAX calls to get and update data. A user enters a product number in an input box, then clicks a <button>, which runs a function that has a jQuery AJAX call to populate a div. See below.
HTML
<form rol="form">
<div class="form-group">
<label for="sku" id="sku-label">Please enter the SKU below</label>
<input class="form-control text-center" type="input" id="sku">
<button class="btn btn-primary col-md-12" type="button" id="bClick" onclick="getSku( $( '#sku' ).val() );">Get SKUs</button>
</div>
<input type="hidden" id="badgeNum" value="<?php echo $_SESSION['BADGE_NUMBER']; ?>">
</form>
<div class="col-md-12" id="sku-results"><!--This div gets populated. -->
</div>
jQuery
function getSku(sSku) {
//AJAX call to get SKUs goes here.
$.ajax({
type: 'POST',
url: 'sku-query.php',
async: false,
mimeType: 'json',
//dataType: 'application/json',
data: {sku: sSku},
success: function(data) {
var disp = "";
disp += "<div class='col-md-12' id='skuDisplay'>";
disp += "<div class='col-md-2'><strong>SKU</strong></div>";
disp += "<div class='col-md-3'><strong>Description</strong></div>";
disp += "<div class='col-md-2'><strong>Master</strong></div>";
disp += "<div class='col-md-2'><strong>Daughter</strong></div>";
disp += "<div class='col-md-2 text-center'><strong>Location</strong></div>";
disp += "<div class='col-md-1 text-center'><strong>Update</strong></div>";
disp += "</div>";
counterp = 0;
$.each(data, function(i, data) {
disp += "<div class='col-md-12' id='skuDisplay'>";
disp += "<div class='col-md-2' id='dSku' >" + data[0] + "</div>";
disp += "<div class='col-md-3' id='dDesc'>" + data[1] + "</div>";
disp += "<div class='col-md-2' id='dMast'>" + data[2] + "</div>";
disp += "<div class='col-md-2 text-center' id='dDaughter'>";
disp += "<input class='col-md-6 text-center' type='number' value='"+ data[3] + "' id='dChange'>";
disp += "</div>";
disp += "<input type='hidden' id='oldQty' value='" + data[3] + "'>";
disp += "<div class='col-md-2 text-center' id='dLoc'>" + data[4] + "</div>";
disp += "<div class='col-md-1 text-center'><a class='inv-click' id='" + counterp + "' onclick='updateDaughter(this.id)' value='" + counterp + "'><i class='fa fa-check-square-o'></i></a></div>";
disp += "</div>";
counterp = counterp + 1;
});
//Success function if all goes well.
$( "#sku-results" ).empty();
$( "#sku-results" ).append( disp );
},
error: function() {
alert('There seems to be an error fetching SKUs.');
}
});
}
So the above code works fine. In each div that is appended to the page, there is an <a> element. The purpose of these divs being added is that each div has an input box where the user can change a value. When the value is changed and the a element is clicked, another function, with another AJAX call is run. When the second AJAX call in this function is done running, I need to then run the first function AGAIN to update the page with the updated value. See the second function below.
function updateDaughter(getId)
{
var master = $( "#" + getId ).closest("#skuDisplay").children("#dMast").html();
var daughter = $( "#" + getId ).closest("#skuDisplay").children("#dDaughter").children("#dChange").val();
var loc = $( "#" + getId ).closest("#skuDisplay").children("#dLoc").html();
var oldQty = $( "#" + getId ).closest("#skuDisplay").children("#oldQty").val();
var emp_id = $( "#badgeNum" ).val();
var sku = $( "#" + getId ).closest("#skuDisplay").children("#dSku").html();
var dDate = new Date();
var dDay = ("0" + dDate.getDate() ).slice(-2);
var dMonth = ("0" + dDate.getMonth()).slice(-2);
var dYear = dDate.getFullYear();
var dHour = ("0" + dDate.getHours() ).slice(-2);
var dMin = ("0" + dDate.getMinutes()).slice(-2);
var dSec = ("0" + dDate.getSeconds()).slice(-2);
var dFullDate = dYear + "-" + dMonth + "-" + dDay;
var dFullTime = dHour + ":" + dMin + ":" + dSec;
var dAllDate = dFullDate + " " + dFullTime;
var move_from = "Adjustment";
//var created = date('Y-m-d h:i:s');
var worktype = "Reslot";
var qty = daughter - oldQty;
alert("DATE:" + dAllDate + ". SKU:" + sku + ". MASTER:" + master + ". LOC:" + loc + ". DAUGHTER:" + daughter + ". OLD:" + oldQty + ". EMPID:" + emp_id + ". QTY:" + qty + ". MOVEFROM:" + move_from + ". TYPE:" + worktype);
var workTypeId = "";
if (worktype = 'Putaway') {workTypeId = 1;}
if (worktype = 'RTI') {workTypeId = 2;}
if (worktype = 'Replen') {workTypeId = 3;}
if (worktype = 'Manual Replen'){workTypeId = 4;}
if (worktype = 'Reslot') {workTypeId = 5;}
if (worktype = '01 Replen') {workTypeId = 6;}
if (worktype = '03 Replen') {workTypeId = 7;}
if (worktype = '02 Replen') {workTypeId = 8;}
$.ajax({
type: 'POST',
url: 'http://a/location/that/works',
async: false,
data: JSON.stringify({
workTypeID: workTypeId,
completedDate: dAllDate,
startLocation: move_from,
endLocation: loc,
quantity: qty,
assignedAdministratorID: emp_id,
createdDate: dAllDate,
startedDate: dAllDate,
createdAdministratorID: emp_id,
sku: sku
}),
contentType: 'application/json',
success: function(data) {
if(data.status == 'Success') {
$('#result').text(data.status);
} else {
$('#result').text('Failed on update: ' + data.status + ', ' + data.errorMessage);
}
},
error: function() {
$('#result').text('There might be some problem on the web service. Please contact administrator.');
}
});
$( "#bClick" ).click();
}
What's the problem?
The second function works in that it updates the corresponding database with the information that it needs to update it with. The problem is that I cannot get my page to then reload with the updated information. After I change the value and click the <a> tag, the page runs the first function again but the old value shows up. The only way I can get the new value to show up is if I click on the button with the same product number again.
Upon reading about this, I came across that AJAX will run its own process apart from the rest of your function. So in my second function, if I am calling my first function again, what looks like is happening is that my first function is being called in my second function before the AJAX call is even done.
What I tried
-I figured that I would try adding async: false to both of my jQuery AJAX functions, which did not work.
-I tried running my first function in my second function in various places. Inside of the AJAX success parameter, after the AJAX call altogether, etc... This did not work either.
-I tried to patch this by replacing the old value with the new value in the input box manually (empty() then append()) just to show the user than their changes have "updated", but even this gets overwritten by the old data (which is not even there anymore because of the second AJAX call). The AJAX call is getting "outraced" by the rest of the function, it seems.
-I tried just triggering the button to be "clicked" again inside, and after the second AJAX call by $( "#bClick" ).click();. Same thing. Didn't work.
What I need
This is what I need to happen:
-The user types a product number (works)
-The user clicks a button (works)
-The button triggers a function that runs an AJAX call to populate the page with info; each row of info has an input box with a number that can be changed, and an <a> button that will run another function. (works)
-When the <a> button is clicked, another function is run that has another AJAX call that updates a database with information, including the changed value in the input box. (works)
-Inside of the second function, after the AJAX call is run, the first function with the first AJAX call should be run again to update the page with the changed information. (does not work)
Can someone help me figure this out?
Here is my submit button written dynamically through AJAX:
var htmlpage = "<div class='pages'>"
for (i=1 ; i < pages+1 ; i++)
{
htmlpage += "<li><input type='submit' value='"+i+"' onclick='updatefilters;' /></li"
}
htmlpage += "<div>"
htmlpage += "</ul>";
I am trying to rerun the updatefilters() function to change the items that are displayed. I imagine its a bit tough to conceptualize without seeing all the code...but essentially, all I need to do is run the function again on each click of the submit button...right now, its giving me a updatefilters is undefined error in firebug.
Heres my whole JS for reference
$(function() {
$( "#selectable" ).selectable({
selected: updatefilters
});
getactivesession();
function getactivesession(ev, ui){
var i = 0;
var actfilter, strfilter;
var strfilterarray = new Array();
$.ajaxSetup({cache: false})
$.ajax({
type: "POST",
async: false,
url: 'welcome/getactivesession',
dataType: 'json',
success: function (data){
strfilter = JSON.stringify(data)
strfilterarray = strfilter.split(',')
for (i=0 ; i < strfilterarray.length ; i++) {
strfilter = strfilterarray[i]
strfilter = strfilter.replace(/[\[\]'"]+/g,'');
var strfilterdash = strfilter.replace(/\s+/g, '-')
actfilter = '#'+ strfilterdash
$(actfilter).addClass('ui-selected')
}
updatefilters();
}
});
}
function updatefilters(ev, ui){
// get the selected filters
var template, html;
var i = 0;
var page;
if(! page){
page = 0;
}
var $selected = $('#selectable').children('.ui-selected');
// create a string that has each filter separated by a pipe ("|")
var filters = $selected.map(function(){return this.id;}).get().join("\|");
$.ajax({
type: "POST",
async: false,
url: 'welcome/updatefilters',
dataType: 'json',
data: { filters: filters, page: page },
success: function(data){
var html = "";
html += "<div id=board>"
html += "<div class='board' id='table'>"
html += "<div id='row'>header here</div>"
var pages = Math.ceil(data['num_threads']/10);
var htmlpage = "<div class='pages'>"
for (i=1 ; i < pages+1 ; i++)
{
htmlpage += "<li><input type='submit' value='"+i+"' onclick='updatefilters;' /></li"
}
htmlpage += "<div>"
htmlpage += "</ul>";
htmlpage += "</br>";
html += htmlpage;
for (i=0 ; i < data['threads'].length ; i++)
{
html += "<div id=row>";
html += " <div id='author' style='background: url("+data['threads'][i].location + ") no-repeat; background-position: center;'><p>"+data['threads'][i].username + "</p></div>";
html += " <div id='arrow'></div>";
html += " <div id='subject' title='"+ data['threads'][i].body +"'>";
html += " "+ data['threads'][i].subject +"<p>Created: "+data['threads'][i].posttime+"</p></div>";
html += " <div id='info'>";
html += " <div id='replies'>" + data['threads'][i].replies_num + "</div>";
html += " <div id='lastpost'>"+ data['threads'][i].lastreply+"</div>";
html += " </div>";
html += "</div>";
}
html += "</div></div>";
$('#board').html(html);
}
});
}
});
There appears to be a few problems with this approach.
First, you're not actually calling the function in your onclick handler.
htmlpage += "<li><input type='submit' value='"+i+"' onclick='updatefilters;' /></li"
should be:
htmlpage += "<li><input type='submit' value='"+i+"' onclick='updatefilters();' /></li"
Second, the updatefilters function isn't accessible from the global scope, which is where that anonymous function will be executed from. You'd have to move function updatefilters(ev, ui) outside the onload callback, perhaps to the top of your script block.