How do I get the jQuery button css to toggle? - javascript

I'm working on an inherited site which I upgraded from Laravel 5.3 to Laravel 8. It has a lot of jQuery and all the js and css is pre-processed. One button that is supposed to change color when it is clicked doesn't work. This is the jQuery function for that button:
define([], function () {
var VipClass = function () {
// Private vars
var _this = this;
// Private Methods
var _construct = function () {
$(document).on('click', '.button-vip', function (e) {
e.preventDefault();
e.stopPropagation();
var t = $(e.currentTarget),
url = t.data('url'),
status = !t.hasClass('btn-glow');
t.prop('disabled', true);
$.ajax({
url: url,
type: 'POST',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: {
status: status
},
dataType: 'JSON',
async: true,
cache: false,
complete: function () {
t.prop('disabled', false);
},
success: function (response) {
if (response.success) {
t.toggleClass('btn-clean', !status);
t.toggleClass('btn-glow', status);
}
}
});
});
};
// Init
_construct();
};
return VipClass;
});
That's the prettified version of the code. The button either has orange fill if activated or no fill if not. In either case the jQuery doesn't change it when clicked. If I refresh the page or go out and come back the change has been applied so I know the save to the db is working. The ajax success appears to be doing a double toggle.
This is the html of the button:
<button class="button-vip btn btn-warning btn-icon btn-sm btn-glow" data-url="...">
<span class="icon-star"></span>
</button>
Probably, my biggest problem is that I don't know how to manually change the code when the files are preprocessed. I have not worked much with pre-processed files and it seems cumbersome to have to continually re-compile for a small change. How is this generally handled in dev?

Related

script function wont work after I use .load() function

I am adding data inside a table and I am preventing page to reload, so I use load function to just load the table and fetch data from it without reloading the page.
Sample output:
And then after I add payment:
I use this code to load the data without reloading the page:
$('#payment-body').load('client-info.php?id='+c_id+' #payment-body');
And now my problem is. As you can see there is X icon after the printer icon.
I set function with that icon. here is the function:
$(".remove-transaction").click(function()
{
var p_id = $(this).attr("id");
var c_id = $(this).attr("name");
var remove_payment = $(this).attr("id");
$.ajax({
url: 'proccess.php',
type: 'POST',
async: false,
data: {'p_id':p_id,'c_id':c_id, 'remove_payment':remove_payment},
beforeSend : function(){
$("#status").fadeIn(0).delay(2500).hide(0);
$("#recieptModal_"+p_id).modal("hide");
$("#statusModal").modal("show");
$(".header-status").html('<h4>Please Wait...</h4>');
$("#status").html('<h3 class="center"><em class="fas fa-sync fa-spin checking-client"></em> Deleting Payment...</h3>');
},
success: function(response){
$("#status").fadeIn(0, function(){
$(".header-status").html('<h4>Done!</h4>');
$("#status").html('<h3 class="center"><em class="far fa-trash-alt invalid-client"></em> Payment Removed!</h3>');
$("#payment-row"+p_id).fadeOut('slow');
$('#total-paid').load('client-info.php?id='+c_id+' #total-paid');
$('#total-balance').load('client-info.php?id='+c_id+' #total-balance');
$('#remarks').load('client-info.php?id='+c_id+' #remarks');
window.setTimeout(function () {
$("#statusModal").modal("hide");
}, 3000);
});
},
error: function(error){
console.log(error.responseText);
//you could debug your php code if some error raises
}
});
});
It is working when I reload the page. But what I want to happen is make it work without reloading the page. Or as you can see. just using .load() function.
try doing this, I think it is because the newly appended data function will not work,
$(document).on('click', '.remove-transaction', function(){

Binding two JQuery and ajax functions

I have the follwoing JQuery/AJAX code:
<script>
$('.warning-dialog').click(function () {
alert($(this).data("id"));
});
$(function () {
//twitter bootstrap script
$("button#delete").click(function () {
$.ajax({
type: "GET",
url: "deleteArticleType.php",
data: { 'typeID': $('.warning-dialog').data("id") },
success: function (msg) {
$("#thanks").html(msg)
$("#form-content").modal('hide');
},
error: function () {
alert("failure");
}
});
});
});
</script>
The first function gets the data-id of a button . The second function calls a PHP page and with the method GET should get the value from the first function.
I tried the code above but it didn't work.
My question is why and how can I fix it?
If these are two separate events, disconnected in time and you want to store the value from the first click and then use it in the second click, then you will have to store it somewhere. There are several options, the simplest being a variable.
$(function () {
var lastClickId;
$('.warning-dialog').click(function () {
lastClickId = $(this).data("id");
});
//twitter bootstrap script
// FIXME: you need to add logic here for what to do if lastClickId isn't set yet
// or create a default behavior in that case
$("button#delete").click(function () {
$.ajax({
type: "GET",
url: "deleteArticleType.php",
data: { 'typeID': lastClickId },
success: function (msg) {
$("#thanks").html(msg)
$("#form-content").modal('hide');
},
error: function () {
alert("failure");
}
});
});
});
Since it looks like you are requiring the first click to happen before the second click can have something to operate on, then you should probably either modify the UI to use different types of controls or you will need to add some error handling if the user doesn't click in the right order.
Actually it should have worked using $('.warning-dialog').data("id")
If your page contains only a single class warning-dialog, you approach will be worked. It seems you're referring this class to many elements.

Function.prototype.apply: Arguments list has wrong type

The error in the title of the post came from jQuery version 1.10.2, line 637
I've got a modal that pops up on a button click with some textboxes and when a button inside the modal is clicked, the information that's in the text boxes is added to a database via AJAX. In order to make the page a little more user-friendly I added a setTimeout function to pause the hiding of the modal so the user can see a verification message that the data was added to the database. Block 1 of my code adds the record to the database, but the setTimeout call doesn't work right:
function insert(data) {
data = JSON.stringify(data);
$.ajax({
type: "POST",
url: "../Service.asmx/InsertPerson",
dataType: "json",
contentType: "application/json",
data: data,
//record gets added to the database
//something about the setTimeout function
//that gives the error in the title
success: function () {
console.log('success before setTimeout');
var successMessage = $('<div>').text('Successfully added to the database...').css('color', 'green');
$('.modal-body').append(successMessage);
//*******this function doesn't run
window.setTimeout(function () {
$('#contact').modal('hide');
$('.modal-body input').each(function () {
$(this).val('');
}, 1000);
});
}
});
}
I fixed it using the code:
(the success function is what we need to pay attention to here)
function insert(data) {
data = JSON.stringify(data);
$.ajax({
type: "POST",
url: "../Service.asmx/InsertPerson",
dataType: "json",
contentType: "application/json",
data: data,
//record gets added to the database
success: function () {
console.log('success before setTimeout');
var successMessage = $('<div>').text('Successfully added to the database...').css('color', 'green');
$('.modal-body').append(successMessage);
window.setTimeout(function () {
$('.modal-body input').each(function () {
$(this).val('');
});
$('#contact').modal('hide');
}, 1000);
}
});
}
I see that I in the first block I didn't close the each function, and I fixed that in the second block and that's why it works, but for future reference, what does this error really MEAN in this context?
It means that you left off the second argument to setTimeout and instead passed it as the second argument to .each().
edit — it looks like jQuery is picking up the argument (that 1000) and trying to pass it through to its internal each implementation. The .apply() function expects it to be an array.

Ajax Div toggle avoiding reloading content

I had a question regarding Ajax loading of html into a DIV. Ideally what I want is this:
A toggle div with close button, which I have the code for here: http://jsfiddle.net/tymeJV/uhEgG/28/
$(document).ready(function () {
$('#country').click(function () {
$("#country_slide").slideToggle(function() {
if ($(this).is(":visible")) {
alert("im visible!");
}
});
});
$('#close').click(function (e) {
e.preventDefault();
$('#country_slide').slideToggle();
});
});
Then I want some AJAX code to load a html file into the div when the div is expanded. The trick is that if the HTML is loaded successfully, I want it to avoid reloading the HTML file again if the div is closed and repoened, since I have already loaded it, and just simply toggle the content in and out with the button. The code I have for this (which I got help on from here is this):
http://jsfiddle.net/spadez/uhEgG/55/
$(function () {
$('#country_link').on('click', function (e) {
// Prevent from following the link, if there is some sort of error in
// the code before 'return false' it would still follow the link.
e.preventDefault();
// Get $link because 'this' is something else in the ajax request.
var $link = $(this);
// Exit if the data is loaded already
if ($link.data('loaded') === true)
return false;
$.ajax({
type: 'GET',
dataType: 'html',
url: '/ajax/test.html',
timeout: 5000,
beforeSend: function () {
},
success: function (data, textStatus) {
$("#country_slide").html(data);
alert('request successful');
// If successful, bind 'loaded' in the data
$link.data('loaded', true)
},
error: function (xhr, textStatus, errorThrown) {
$("#country_slide").html('Error');
},
complete: function () {
},
});
});
});
I haven't been able to get this working yet though. So my question is, is it actually possible to do this, and if it is, can anyone with more experience with jquery please help me integrate the div toggle with the ajax loading script.
This is one of my first jquery scripts and I am having a bit of a hard time with it, perhaps it is not for beginners. Thank you.
I edited the fiddle you posted adding the call to slideToogle() where appropriate. Also added a div element to hold the loaded html code.
<div id="country_slide">
Close
<div class=".content"></div> <!-- This is the div I added -->
</div>
You can check the log messages in the console to verify that the code is doing what you expect. The URL for the Ajax call you were doing always returned an error so I changed to the URL that jsfiddle provides for testing: /echo/html/.
Here's the modified JS code:
$(function () {
$('#close').click(function (e) {
e.preventDefault();
$('#country_slide').slideToggle();
});
$('#country_link').on('click', function (e) {
e.preventDefault();
var $link = $(this);
// Exit if the data is loaded already
if ($link.data('loaded') === true) {
console.log('Not using Ajax.');
$("#country_slide").slideToggle();
return false;
}
$.ajax({
type: 'GET',
dataType: 'html',
url: '/echo/html/',
timeout: 5000,
beforeSend: function () {
$("#country_slide .content").html('<p>Loading</p>')
},
success: function (data, textStatus) {
console.log('Fecthed with Ajax.');
$("#country_slide .content").html(data);
$("#country_slide").slideToggle();
// If successful, bind 'loaded' in the data
$link.data('loaded', true)
},
error: function (xhr, textStatus, errorThrown) {
alert('request failed');
},
complete: function () {
},
});
});
});

make sure ajax request doesn't get fired multiple time

I was working on a simple form page and I was wondering what happens if someone clicks the submit button many many times (incase my shared hosting somehow seems to be slow at that time).
Also, incase anyone wants to look at my code
$.ajax({
url: "submit.php",
type: 'POST',
data: form,
success: function (msg) {
$(".ressult").html("Thank You!");
},
error: function () {
$(".result").html("Error");
}
});
Is there a way to make it so after the user clicks it once, it won't run it again until the first click is done?
Thank you
You can use jQuery's .one() function:
(function handleSubmit() {
$('#submitBtn').one('click', function() {
var $result = $('.result');
$.ajax({
url: 'submit.php',
type: 'POST',
data: form,
success: function (msg) {
$result.html('Thank You!');
handleSubmit(); // re-bind once.
},
error: function () {
$result.html('Error');
}
}); // End ajax()
}); // End one(click)
}()); // End self-invoked handleSubmit()
*Edit: * Added recursion for multiple submissions.
Use a boolean flag
if (window.isRunning) return;
window.isRunning = true;
$.ajax({
url:"submit.php",
type: 'POST',
data: form,
success: function (msg){
$(".ressult").html("Thank You!");
},
error: function (){
$(".result").html("Error");
},
complete : function () {
window.isRunning = false;
}
});
var $button = $(this);
$button.prop('disabled', true); // disable the button
$.ajax({
url:"submit.php",
type: 'POST',
data: form,
success: function (msg){
$(".ressult").html("Thank You!");
},
error: function (){
$(".result").html("Error");
},
complete: function() {
$button.prop('disabled', false); // enable it again
}
});
Have you considered replacing your submit button with a loader image while the query executes, then re-adding it once the query is complete?
EDIT: Using the loader image is a sort of universal "I'm doing something" indicator, but disabling the button would work too!
You could disable the submit button, before the ajax call is made. And then, if required, enable it on success.

Categories

Resources