changing the class of clicked button on ajax function success - javascript

i have a several html buttons (not within a form).
When clicked they call a JavaScript function that after conformation, runs an ajax call.
This part all works OK, but i would then like to change the class of whichever button was clicked on success of the ajax call.
i have tried various methods seen on stackOverflow, but none of them seem to work...
can i please ask what am i doing wrong?
here is the simplified HTML (buttons)
<button class="btn btn-primary" onclick="primaryImage(4107,19372,'/abbie1.jpg'); return false;">
set as profile image
</button>
<button class="btn btn-primary" onclick="primaryImage(4107,19373,'/abbie2.jpg'); return false;">
set as profile image
</button>
<button class="btn btn-success" onclick="primaryImage(4107,19374,'/abbie3.jpg'); return false;" disabled="disabled">
profile image
</button>
Please note: the last button is already the active/success button, and i would also like to remove the class on success too (as only one should be active), but that is maybe my next stage....
here is the javaScript, (i have left in some of the methods i have tried, but commented them out)
function primaryImage(eid,pid)
{
if (confirm("Are you sure you wish to use this as your profile image?"))
{
$.ajax({
type: "POST",
async: false,
cache: false,
dataType: "json",
url: "ajax_photo.php",
data: "action=primary&eid="+eid+"&pid="+pid,
//context: this,
success: function(data){
if(data.result=='success')
{
alert('The image is now set as the profile image');
//$('button').click(function(){
// $(this).addClass('btn-success');
//});
//$('button').on(data.result=='success', function(e) {
// $(this).toggleClass("btn btn-success"); //you can list several class names
// e.preventDefault();
//});
//$(this).removeClass('btn-primary').addClass('btn-success');
}
else
{
alert('An error occurred when trying to set the image: ' + data.result);
}
}
});
}
}
I would be very grateful for any advice of what i am doing wrong
(as you can see, i am not too good with JS (yet))
Thanks!
Ford

As noted in your commented out code, you are binding the click event after click event has already been fired.
I would suggest you to pass a reference of the button that was clicked in the primaryImage() function itself as such:
<!-- In your HTML -->
<button class="btn btn-success" onclick="primaryImage(this, 4107,19374,'/abbie3.jpg'); return false;" disabled="disabled">
profile image
</button>
function primaryImage(button, eid,pid){
/** ... */
Then using that referenced button, you can add or remove CSS classes to the element, as well as the siblings of the element (using jQuery's siblings() method).
//your ajax call
success: function(data){
if(data.result=='success') //make sure this really is success
{
alert('The image is now set as the profile image');
$(button).removeClass('btn-primary').addClass('btn-success');
$(button).siblings('button').removeClass('btn-success').addClass('btn-primary');
}
}

As you don't use the jQuery .click() event, I think you need to pass the button in your function args.
So your button will look like
<button class="btn btn-primary" onclick="primaryImage(this, 4107,19373,'/abbie2.jpg'); return false;">
set as profile image
</button>
Then your function will be like
function primaryImage(el, eid,pid)
{
if (confirm("Are you sure you wish to use this as your profile image?"))
{
$.ajax({
type: "POST",
async: false,
cache: false,
dataType: "json",
url: "http://anzvirtuel.org",
data: "action=primary&eid="+eid+"&pid="+pid,
//context: this,
success: function(data){
if(data.result=='success')
{
$(el).addClass('btn-success');
alert('The image is now set as the profile image');
// keep doing whatever you want...
}
else
{
alert('An error occurred when trying to set the image: ' + data.result);
}
}
});
}
}
As I have not fully understood your commented JS I'll let you put the code you want, just remember that your button will be accessible in jQuery with $(el).
Hope it may helps you

You should pass the clicked element to the primaryImage() function, and use it on success to do whatever you like.
<button class="btn btn-primary" onclick="primaryImage(this, 4107,19372,'/abbie1.jpg'); return false;">set as profile image</button>
And in your JS
function primaryImage(element, eid,pid)
{
[...]
success: function(data){
if(data.result=='success')
{
$(element).addClass('btn-success');
}
else
{
alert('An error occurred when trying to set the image: ' + data.result);
}
}
[...]
}

You could use data-* attributes instead of onclick (MDN Documentation) and then access those throught jQuery, so your code is more clean and HTML / JS are separated.
Try this code, I've created three data attributes (data-eid, data-pid and data-image) for your params and also replaced your JS to make the whole stuff work with those data attributes. Those attributes can be accessed with following jQuery code - var eid = $(this).attr('data-eid'); as an example
This line of code removes the btn-primary class from the clicked button, adds a btn-success class to it and disables it, so it can't be toggled again.
pushedBtn.removeClass("btn-primary").addClass("btn-success").prop("disabled", true);
HTML
<button class="btn btn-primary" data-eid="4107" data-pid="19372" data-image="/abbie1.jpg">
profile image
</button>
<button class="btn btn-primary" data-eid="4107" data-pid="19373" data-image="/abbie2.jpg">
profile image
</button>
<button class="btn btn-primary" data-eid="4107" data-pid="19374" data-image="/abbie3.jpg">
profile image
</button>
JS
$(".btn").click(function (e) {
if (confirm("Are you sure you wish to use this as your profile image?")) {
var eid = $(this).attr('data-eid'); //like 4107
var pid = $(this).attr('data-pid'); //like 19372
var image = $(this).attr('data-image'); //like /abbie1.jpg
var pushedBtn = $(this);
$.ajax({
type: "POST",
async: false,
cache: false,
dataType: "json",
url: "ajax_photo.php",
data: "action=primary&eid=" + eid + "&pid=" + pid,
//context: this,
success: function (data) {
if (data.result == 'success') {
alert('The image is now set as the profile image');
pushedBtn.removeClass("btn-primary").addClass("btn-success").prop("disabled", true);
} else {
alert('An error occurred when trying to set the image: ' + data.result);
}
}
});
}
});

Related

Update view without page refresh in Ajax

I have the following code which runs when a button is clicked.
$.ajax({
type: "POST",
url: base_url+"/controller/method",
data: {val: value},
success: function(data){
data = jQuery.parseJSON(data);
if(data.status === true){
show_notify_message("Success",data.msg,'success');
} else {
show_notify_message("Error",data.msg,'error');
}
}
});
HTML Code:
<button class='btn btn-xs alert-success' onclick='method(1)'><font color='black'>Take</font></button>
Once the changes are made the entire page refreshes and the updated values are seen in the view.
How can I perform the same action without the entire page refreshing?
try it this way
HTML code
<button class='btn btn-xs alert-success' data-method='1'><font color='black'>Take</font></button>
JQuery script
$(document).ready(function(){
$("[data-method]").click(function(event){
event.preventDefault();
//value from the button
value=$(this).data("method");
// ajax call
});
});
if you use a <button> element, set it's type to "button" like this:
<button type="button">Click Me</button>
for some reason the default type is "submit"

Ajax replace div with another div (new css)

I have a button and user's name on the template and if a user clicks on button, Ajax should replace user's name and button with some messages using new CSS styling.
This is my Ajax :
$('#fulfillButton').bind('click',function() {
$.ajax({
type : "GET",
contentType : "application/json; charset=utf-8",
url : "order/${orderID}",
dateType : "json",
cache: false,
success: function (data) {
if(data.statusCode=="OK")
{
$('#replace').replaceWith("<div class ="error_message">"+ data.body +"</div>");
}
},
error: function (data) {
alert("Something went wrong, please retry again");
},
});
});
This is my html:
<div id="replace">
<div class="full_name">
${name}
</div>
<button id="fulfillButton" type="button" class="action-button shadow animate green">
FulFill
</button>
</div>
<button id="goBackButton" type="button" class="go_back_button">
Go Back
</button>
However, when I clicked on the button, nothing happened. I am missing something here? I am using Jquery 1.6.
You code is fine in general, and working. The only thing went wrong, is the html escaping of the replace element:
// before
$('#replace').replaceWith("<div class ="error_message">"+ data.body +"</div>");
// after
$('#replace').replaceWith('<div class="error_message">' + data.body + '</div>');
And you should really update your jQuery version. 1.6 is a hundred years old! :)
Working example.

check if button was clicked in the controller

I have the following button and when clicked it's invoking a function,
Is there a way to know in the controller that this button was clicked ?
$("#RemoveFile").on("click", RemoveFile);
<button class="btn" style="height: 25px" type="button" id="RemoveFile"><p >Remove File</p></button>
As Edurado Says this the implementation which you asked to him
First set hidden field in html page (razor view/ aspx page)
<input type="hidden" id="StakeholderId" name="stakeholderId" />
Then add script like below
$( "#buttonID" ).click(function() {
$( "StakeholderId" ).val(true);
});
And get the value and posting the value to controller like below
var hidden= $('StakeholderId').val();
$.ajax({
type: "post",
url: "Controller/Method",
data: {
hiddenField1: hidden,
hiddenField2: "hiddenValue2",
},
success: function() {
alert("yay")
},
error: function(e) {
console.log(e);
}
});
Hope this helps....
When you click in the button, add an onclick event to this very button and save the clicked status in a hidden field. Then, whenever you send data to the controller, send this hidden field value, stating whether the button was clicked.
UPDATED:
Here is the HTML
<input id="hdnRemoveClicked" type="hidden" value="false" />
And here is the javascript which adds the click event in the button with ID="RemoveFile", and set the hidden field value as true, to show it is clicked.
$( "#RemoveFile" ).click(function() {
$( "hdnRemoveClicked" ).val(true);
// do other things, if needed
});
The only way I know of to so this in MVC is to make an Ajax call to the server via an anonymous function in the JQuery component. Example:
$("#RemoveFile").on("click", "RemoveFile", function () {
// tell server
var jqxhr1 = $.ajax({ type: 'POST', url: "/myControllerUrl",
data: { buttonID: "RemoveFile" } });
$.when(jqxhr1).done(function (response, textStatus, jqXHR) {
if (textStatus != "success") {
alert("Error, please try later");
return false;
}
// update the user interface
});
});
Make an ajax call to a method in Controller where a session keeps track if button was clicked.

Bootstrap popover repeats an action/ event twice?

Why Bootstrap's popover repeats an action twice? For instance, I want to submit a form inside the popover's data-content via ajax. It repeats all the form data twice and the posts form twice.
Any idea what I can do about it?
jquery + bootstrap,
$('.bootstrap-popover-method').popover({
placement: 'bottom',
container: 'body',
html:true,
content: function () {
var p = $(this);
var data = $('#popover-content').html();
$('#popover-content').remove();
p.attr("data-content", data);
p.popover('show');
}
});
$('.bootstrap-popover-method').on('shown.bs.popover', function () {
// do something…
console.log(this); // I get twice of the button element <button class="btn btn-default bootstrap-popover-method"...>
console.log($(".btn-submit").length); // I get twice of '1'.
$(".link").click(function(){
console.log($(this).attr("href")); // I get once of 'test.html'.
return false;
});
$(".btn-submit").click(function(){
console.log($(this).closest("form").attr("action")); // I get twice of '1.php'
var form = $(this).closest("form");
console.log(form.serialize()); // I get twice of 'username=hello+world!'
$.ajax({ // it posts twice to 'POST https://localhost/test/2014/css/bootstrap/1.php'
type: "POST",
url: form.attr("action"),
data: $(this).serialize(), // serializes the form's elements.
success: function(data){
//alert(data); // show response from the php script.
}
});
return false;
});
});
bootsrap + html,
<button type="button" class="btn btn-default bootstrap-popover-method" data-title="body" data-container="body" data-toggle="popover" data-placement="bottom">
Popover on bottom
</button>
<div id="popover-content">
hello
<form action="1.php" class="myform">
<input type="text" name="username" value="hello world!"/>
<input type="submit" value="submit" class="btn-submit"/>
</form>
</div>
This happens because popover.content checks if the tooltip is empty or not.
A simple fix would be to add a title attribute to popover.
$('.bootstrap-popover-method').popover({
placement: 'bottom',
container: 'body',
html:true,
title: "New Title",
content: function () {
var p = $(this);
var data = $('#popover-content').html();
$('#popover-content').remove();
p.attr("data-content", data);
p.popover('show');
}
});
https://github.com/twbs/bootstrap/issues/12563#issuecomment-56813015
This might be an old post, but i'm gonna leave here my work around.
I'm using bootstrap 3.3.5.
So the buggy behavior is that on every execution of "popover('show')", Bootstrap calls the rendering function twice, and only the second call is the one that actually renders the popup.
My fix is to return a short html string for the first call, and for the second call i let run the whole rendering function:
jQuery('.bootstrap-popover-method').popover({
html: true,
trigger: 'manual',
content: function(){//This is our rendering function for the popup's content
var __G_bs_popover_shown= jQuery.data(jQuery('body')[0], '__G_bs_popover_shown');
//Create a global variable, attached to the body element, to keep track of the repeating calls.
__G_bs_popover_shown= (typeof __G_bs_popover_shown == 'undefined') ? 1 : (__G_bs_popover_shown + 1) % 2;
//Update the global var
jQuery.data(jQuery('body')[0], '__G_bs_popover_shown', __G_bs_popover_shown);
//return a short string on every first call (this will not be rendered, anyway)
if(__G_bs_popover_shown == 1) return '<div>BLANK</div>';//==>this should not be an empty string!
//PLACE YOUR CODE HERE, E.G. AJAX CALLS, ETC..
//DON'T FORGET TO RETURN THE HTML FOR THE POPUP'S CONTENT!
}
});
I think you need to prevent the default event of the submit button
$(".btn-submit").click(function(e){
e.preventDefault();
console.log($(this).closest("form").attr("action")); // I get twice of '1.php'
var form = $(this).closest("form");
console.log(form.serialize()); // I get twice of 'username=hello+world!'
$.ajax({ // it posts twice to 'POST https://localhost/test/2014/css/bootstrap/1.php'
type: "POST",
url: form.attr("action"),
data: $(this).serialize(), // serializes the form's elements.
success: function(data){
//alert(data); // show response from the php script.
}
});
return false;
});
$('.bootstrap-popover-method').off('shown.bs.popover')
.on('shown.bs.popover', function (e) {
e.preventDefault();
}
// unbind your submit button click
$(".btn-submit").off('click').on('click',function(){
console.log($(this).closest("form").attr("action")); // I get twice of '1.php'
var form = $(this).closest("form");
console.log(form.serialize()); // I get twice of 'username=hello+world!'
$.ajax({ // it posts twice to 'POST https://localhost/test/2014/css/bootstrap/1.php'
type: "POST",
url: form.attr("action"),
data: $(this).serialize(), // serializes the form's elements.
success: function(data){
//alert(data); // show response from the php script.
}
});
return false;
});

Call This Function Outside of Form Submit

I have a submit button at the end of my form that is labeled like this:
<button id="sendbutton" style="margin-left:25px;" class="btn btn-large btn-primary" type="submit">Send Responses</button>
This button calls this script:
<script type="text/javascript">
$(function() {
$('form').unbind('submit').bind('submit', function(){
$.ajax({
type: 'post',
url: 'chapter.php',
data: $("form").serialize(),
success: function() {
alert('Your answers have been saved.');
}
});
return false;
});
});
</script>
How do I create a button outside of this form structure that will call the same function?
You may create whatever button you'd like, even if its outside of the form. And then, to get that button to do the same thing you could simply do
$('#yourNewButton').click(function(){
$('form').submit();
});
Or, why not wrap up your original logic into its own function
function submitMyForm(){
$.ajax({
type: 'post',
url: 'chapter.php',
data: $("form").serialize(),
success: function() {
alert('Your answers have been saved.');
}
});
return false;
}
And then
$('#yourNewButton').click(submitMyForm);
$('form').submit(submitMyForm);
You can write a click handler to the new button and in the handler trigger the form submit using script
<button id="test" style="margin-left:25px;" class="btn btn-large btn-primary" type="button">Send Responses</button>
then
jQuery(function($){
$('#test').click(function(){
$('form').submit()
})
})
Rather than make the submit handler an anonymous function you make it a named function
function submitHandler() {
$.ajax({
type: 'post',
url: 'chapter.php',
data: $("form").serialize(),
success: function () {
alert('Your answers have been saved.');
}
});
return false;
}
then change your code to
$('form').unbind('submit').bind('submit', submitHandler);
That way you can call that function whenever you like simple by writing submitHandler();

Categories

Resources