I am using bootbox to create the following modal:
$("a.delete").on("click", function() {
var id = $(this).attr('id').replace('item_', '');
var parent = $(this).parent().parent();
var table = $(this).attr('rel');
bootbox.dialog({
message: "Are you sure you want to delete this entry?",
title: "Delete Confirmation",
buttons: {
success: {
label: "Yes",
className: "btn-danger",
callback: function() {
$.ajax({
type: "POST",
url: "",
data: 'deleteItem=' + id + '&table=' + table,
beforeSend: function () {
parent.animate({
'backgroundColor': '#E3E3E3'
}, 400);
},
success: function (msg) {
if (msg == "success") {
$('#projects').DataTable().row(parent).remove().draw();
$("html, body").animate({
scrollTop: 0
}, 600);
count();
} else if (msg == 'last') {
$('#rld_div').load("<?php echo $_SERVER['REQUEST_URI']; ?> #rld_div");
} else {
bootbox.alert(msg);
}
count();
}
});
}
},
danger: {
label: "No",
className: "btn-primary"
},
}
});
});
HTML:
Delete Project
It strips the id from the id of the <a> and and gets the name of the table from the rel. Everything seems to be working but the parent (namely the tr), will not animate and just disappears
When I log the var parent I get this [tr.odd, prevObject: m.fn.init[1], context: a#item_250558768.delete] so it seems to be selecting the right object. What am I doing wrong?
If you're after the closest parent <tr> (assuming your link is in a table row), just use parents('tr') (note the 's').
As far as the animation goes, I'm not sure that beforeSend will let you modify the DOM - the manual makes it seem like it's purpose is to allow you to modify the XMLHttpRequest object before the request it made. It might make more sense to move your animation outside the ajax request, and make the request in the "complete" callback for the animation.
If that seems workable, you can also somewhat simply your code by using the $.post helper instead of $.ajax:
parent.animate({ 'backgroundColor': '#E3E3E3' },
400,
function(){
var data = {
deleteItem : id,
table: table
};
$.post(url, data)
.done(function (msg, jhr, status) {
if (msg == "success") {
$('#projects').DataTable().row(parent).remove().draw();
$("html, body").animate({
scrollTop: 0
}, 600);
count();
} else if (msg == 'last') {
$('#rld_div').load("<?php echo $_SERVER['REQUEST_URI']; ?> #rld_div");
} else {
bootbox.alert(msg);
}
count();
});
});
Related
I have 10 rows with data inserted and I'm able to delete any of those, but after I insert from 11th row onwards I can't delete any of the rows after the 10th.
EDIT (I CAN'T DELETE ANYTHING WHEN THE RESPONSIVE FORM IS SHOWING)
$(document).ready(function(){
$('#list').dataTable({
responsive: true
});
$('.delete_piece').click(function(){
_conf("Are you sure to delete this piece?","delete_piece",[$(this).attr('data-id')])
})
})
function delete_piece($id){
start_load()
$.ajax({
url:'ajax.php?action=delete_piece',
method:'POST',
data:{id:$id},
success:function(resp){
if(resp==1){
alert_toast("Data successfully deleted",'success')
setTimeout(function(){
location.reload()
},1500)
}
}
})
}
DELETE FUNCTION AJAX
if($action == "delete_piece"){
$delsete = $crud->delete_piece();
if($delsete)
echo $delsete;
}
DELETE FUNCTION FOR THE ADMIN (ME)
function delete_piece(){
extract($_POST);
$delete = $this->db->query("DELETE FROM mro_inventory where id = ".$id);
if($delete){
return 1;
}
}
Consider the following.
$(function() {
function delete_piece($id) {
start_load()
$.ajax({
url: 'ajax.php?action=delete_piece',
method: 'POST',
data: {
id: $id
},
success: function(resp) {
if (resp == 1) {
alert_toast("Data successfully deleted", 'success')
setTimeout(function() {
location.reload()
}, 1500);
}
}
});
}
$('#list').dataTable({
responsive: true
});
$('tbody').on("click", ".delete_piece", function(e) {
_conf("Are you sure to delete this piece?", "delete_piece", [$(this).attr('data-id')])
});
});
This uses the .on() method to delegate the click event to a class.
Delegated event handlers have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated event handlers to avoid the need to frequently attach and remove event handlers.
See more: https://api.jquery.com/on/
It was not clear from your post what the HTML structure looks like; yet, you are using DataTables, so I know there should be a Table Body element that should be present.
this is how I solved the problem!!
$(document).ready(function() {
$('#list').dataTable({
responsive: true
});
$('tbody').on("click", ".delete_piece", function() {
_conf("Are you sure to delete this piece?","delete_piece",[$(this).attr('data-id')])
})
})
function delete_piece($id){
start_load()
$.ajax({
url: 'ajax.php?action=delete_piece',
method: 'POST',
data: {
id:$id
},
success: function(resp) {
if (resp == 1) {
alert_toast("Data successfully deleted",'success')
setTimeout(function() {
location.reload()
}, 1500)
}
}
})
}
I have what I assume is a relatively simple issue. For testing purposes I have made it so simple so as to locate the issue.
I have a jQuery script that works alongside AJAX to return some results next to checkboxes, here it is below:
$.ajax({
type:'GET',
url: '/customers/details/emails',
dataType:'json',
data: {
'customerID': $('select[name=payer_id]').val(),
'_token': $('input[name=_token]').val(),
},
success: function(data) {
$('.errorTitle').addClass('hidden');
$('.errorContent').addClass('hidden');
if ((data.errors)) {
setTimeout(function () {
$('#createOrigin').modal('show');
toastr.error('Check your inputs!', 'Error Alert', {timeOut: 5000});
}, 500);
if (data.errors.title) {
$('.errorTitle').removeClass('hidden');
$('.errorTitle').text(data.errors.title);
}
if (data.errors.content) {
$('.errorContent').removeClass('hidden');
$('.errorContent').text(data.errors.content);
}
} else {
$.each(data, function(i,val) {
$('<tr>').append(
$('<td>').html('<input type="checkbox" id="emailCheckboxSelect">'),
$('<td>').text(val)).appendTo('#customerEmails');
});
}
}
});
As you can see near the end, for each result a table row is appended, with a checkbox with an id of "emailCheckboxSelect".
Now to my problem, these are obviously dynamically created elements so I believe this is the issue with this script (a simple dummy just to locate the issue). Here is that script that should work:
$(function(){
$('#emailCheckboxSelect').click(function(){
alert('clicked');
});
});
This doesn't work with the dynamically created elements. However, I did add <input type="checkbox" id="emailCheckboxSelect">Checkbox directly to my page, and this does set off the alert.
So what am I doing wrong and what do I need to do so that jQuery can recognize dynamically created elements?
Try to bind the click event after the $.each(data, function() {}) inside the sucess: function() {}
You are using multiple elements with same id in the DOM : Element IDs should be unique within the entire document.
use classes instead
your code will look like:
$.ajax({
type: 'GET',
url: '/customers/details/emails',
dataType: 'json',
data: {
'customerID': $('select[name=payer_id]').val(),
'_token': $('input[name=_token]').val(),
},
success: function(data) {
$('.errorTitle').addClass('hidden');
$('.errorContent').addClass('hidden');
if ((data.errors)) {
setTimeout(function() {
$('#createOrigin').modal('show');
toastr.error('Check your inputs!', 'Error Alert', {
timeOut: 5000
});
}, 500);
if (data.errors.title) {
$('.errorTitle').removeClass('hidden');
$('.errorTitle').text(data.errors.title);
}
if (data.errors.content) {
$('.errorContent').removeClass('hidden');
$('.errorContent').text(data.errors.content);
}
} else {
$.each(data, function(i, val) {
$('<tr>').append(
$('<td>').html('<input type="checkbox" class="emailCheckboxSelect" />'),
$('<td>').text(val)).appendTo('#customerEmails');
});
$('.emailCheckboxSelect').click(function(e) {
alert('clicked');
});
}
}
});
Try changing your click event to something like
$('td').on('click', '.emailCheckboxSelect', function () {
alert('clicked');
});
This would work on dynamically created elements. Also, use class instead of id for dynamically created elements.
I have a function which makes a jQuery ajax call to a REST endpoint. This function will be run 5-6 times with different endpoints to collect data to validate against. During this time I would like to display a spinner on the browser screen to indicate to the end user that the program is processing. I'd like to then hide the spinner once complete. I'm struggling to figure out how to get this to work. My thought would be a simple callback function. I've tried putting the callback function in the click method and the css method as well as directly in the ajax call (validateAcctStr) and none of these seem to work. I feel like there is something simple I am missing?
$(document).ready(function(){
$("#submit").click(function(disableSpinner){
$("#json-overlay").css("display", "block");
validateAcctStr("ValidationAccount", "#accountTxt", "#acctValid");
validateAcctStr("ValidationBusiness", "#businessTxt", "#busValid");
});
function disableSpinner(){
$("#json-overlay").css("display", "none");
alert("test");
}
});
This is what I have so far for my ajax call (it pulls data from a SharePoint list):
function validateAcctStr(list, inputField, validationField)
{
$.ajax({
url: "https://urlAddress/_api/web/lists/getbytitle('"+list+"')/items?$orderby=Title asc&$top=4999",
type: "GET",
dataType: "json",
headers: {
Accept: "application/json;odata=verbose"
},
success: function(data){
$.each(data.d.results, function(index, item){
var arrayVar = $(inputField).val();
if(item.Title === arrayVar){
$(validationField).html("Valid").css({"background-color": "green", "color": "white", "text-align": "center"});
return false;
} else {
$(validationField).html("Invalid").css({"background-color": "red", "color": "white", "text-align": "center"});
}
});
}
});
}
You have almost all pieces in place, just have to put the thing in the proper order.
The issue is that you never call the disableSpinner function.
As you have several other small things, I'll show you changing your code.
So your $(document).ready() staff will became:
$(document).ready(function(){
$("#submit").click(function(ev){
activeSpinner();
validateAcctStr("ValidationAccount", "#accountTxt", "#acctValid");
validateAcctStr("ValidationBusiness", "#businessTxt", "#busValid");
});
});
When you have the other javascript code:
// You worked well wrapping the code to disable the spinner in a function
// let's do it for the activation too.
function activeSpinner() {
$("#json-overlay").css("display", "block");
}
function disableSpinner() {
$("#json-overlay").css("display", "none");
// this is just for test:
// alert("test");
}
And the ajax call:
function validateAcctStr(list, inputField, validationField) {
$.ajax({
url: "https://urlAddress/_api/web/lists/getbytitle('"+list+"')/items?$orderby=Title asc&$top=4999",
type: "GET",
dataType: "json",
headers: {
Accept: "application/json;odata=verbose"
},
success: function(data){
disableSpinner(); // As the first task you have to disable the spinner.
$.each(data.d.results, function(index, item){
var arrayVar = $(inputField).val();
if(item.Title === arrayVar){
$(validationField).html("Valid").css({"background-color": "green", "color": "white", "text-align": "center"});
return false;
} else {
$(validationField).html("Invalid").css({"background-color": "red", "color": "white", "text-align": "center"});
}
});
},
error: function(err) {
disableSpinner(); // to avoid spinner active on an error
// do something with the error.
}
});
}
UPDATE
If you need to wait untill a list of callbacks are complete, than you should use a slighty complicated approach.
You could introduce promises, but you have to rewrite almost all your code.
in your case you should use callbacks:
function callbackCounter () {
var count = 0;
return {
set: function (n) {
count = n;
},
incr: function () {
cont++;
},
done: function() {
count--;
},
doneAll: function() {
count = 0;
},
isDone: function() {
return count === 0;
}
}
}
// ...
$("#submit").click(function(ev){
activeSpinner();
var countCallbacks = callbackCounter ();
countCallbacks.set(2);
validateAcctStr("ValidationAccount", "#accountTxt", "#acctValid", countCallbacks);
validateAcctStr("ValidationBusiness", "#businessTxt", "#busValid", countCallbacks);
});
function validateAcctStr(list, inputField, validationField, countCallbacks) {
// snipp...
success: function(data){
// here you decrement the callbacks:
countCallbacks.done();
if (countCallbacks.isDone()) disableSpinner(); // As the first task you have to disable the spinner.
},
The same code in the error handler.
I am implementing a video conference room and I have a variable (room_status) which holds the status of the room (0 = close & 1 = open). Now this variable is only accessible my the client who clicks open-room.
I need to save the room_status variable to the server so that it can be accessed on other client's side. Here is a piece of my code:
var room_status = 0; //room closed
$('#open-room').click(function () {
// http://www.rtcmulticonnection.org/docs/open/
$.ajax({
type: 'GET',
url: "../invite",
data: {
videoconference_id: $('#meetingID').val(),
invitee_id: 1111,
status: "Accepted"
},
success: function() {
alert("success!");
},
error: function() {
alert("fail");
}
});
//room_status = 1; //room opened
rmc.open();
rmc.streams.mute({video : true});
document.getElementById("on-off-video").style.color= 'red';
});
$('#join-room').click(function () {
if(room_status) {
// http://www.rtcmulticonnection.org/docs/connect/
rmc.connect();
rmc.streams.mute({video: true});
document.getElementById("on-off-video").style.color= 'red';
} else {
console.log("Waiting for meeting organizer");
}
});
Ajax is your friend.
Here is an example from a prject of mine with jquery ui :
function prepare_ajax_button(l){
$("#button").button().click(function(event,ui){
$.ajax({type: "GET",data: {"arg1":l},url: "update_variable.php",success: function(data){
alert("Success ?!");
},error: function(data){alert("Problem ?!");}});
});
}
The page "update_variable.php" can for instance write the variable in a text file, mysql...
I am using the qtip2 Jquery plug-in to provide suggestions on keyup in an input but what I would like to do is instead of refreshing the entire tool-tip bubble every time the content is updated id rather just refresh the content of the tool-tip without closing it.
So effectively if there is no tool tip present it will show the tool-tip and call the content via Ajax but if there is an existing tool-tip it will just update the content of the existing tool tip.
http://jsfiddle.net/fDavN/11723/
Ok Iv updated my code and it kinda works but I am getting an error: typeError: $(...).updateContent is not a function.
Anbody know why?
$(document).ready(function() {
var title = 'KnowledgeBase Suggestions';
$('#name').on("keyup", function () {
if($(this).data('qtip') ) {
var getFormUrl = "http://qtip2.com/demos/data/owl";
$.ajax({ url: getFormUrl,
success: function (data) {
$(this).updateContent($(".qtip-content").html(data));
}
});
}
else {
$(this).qtip({
content: {
text: "Loading...",
ajax:{
url: 'http://qtip2.com/demos/data/owl', // Use href attribute as URL
type: 'GET', // POST or GET
data: {}, // Data to pass along with your request
success: function(data, status) {
// Process the data
// Set the content manually (required!)
this.set('content.text', data);
}
},
title: {
button: true,
text: title
}
},
position: {
my: 'top left',
at: 'center right',
adjust: {
mouse: false,
scroll: false,
y: 5,
x: 25
}
},
show: {
when: false, // Don't specify a show event
ready: true, // Show the tooltip when ready
delay: 1500,
effect: function() {
$(this).fadeTo(800, 1);
}
},
hide: false,
style: {
classes : 'qtip-default qtip qtip qtip-tipped qtip-shadow', //qtip-rounded'
tip: {
offset: 0
}
}
});
}
});
});
A stab in the dark as I don't know what updateContent does but you might have an issue with how you are referencing $(this)
try changing
$('#name').on("keyup", function () {
var $this = $(this);
if($this.data('qtip') ) {
var getFormUrl = "http://qtip2.com/demos/data/owl";
$.ajax({ url: getFormUrl,
success: function (data) {
$this.updateContent($(".qtip-content").html(data));
}
});
}
else {
....
the reason is this is a different this when inside the ajax callback