I have created a button. When I click the button, I want it to run a PHP file and display alert. Here's what I'm trying:
HTML:
<button id="testid" style="height:20px; width: 50px; cursor: pointer" onclick="logoutfunc()">Logout</button>
JavaScript:
function logoutfunc() {
$(document).ready(function() {
$("#testid").click(function() {
$.ajax({
url: 'logoutt.php',
type: 'post',
success: function(result11) {
//$(location).attr('href', 'login.php');
alert(result11);
},
error: function() {
alert("no");
}
});
});
});
}
logoutt.php
<?php
$a="Hello";
echo $a;
?>
Now the problem is that when I click the button first time, it doesn't display the alert. But when I click it again, it displays same alert twice. And when I click it again, it alerts 3 times and so on. What wrong have I written?
You are binding the click handler inside the inline event handler, thus when the button is clicked first time the event handler is attached. So it works second time.
Get rid of the inline click handler. just bind the event handler using jQuery
$(document).ready(function() {
$("#testid").click(function() {
$.ajax({
url: 'logoutt.php',
type: 'post',
success: function(result11) {
//$(location).attr('href', 'login.php');
alert(result11);
},
error: function() {
alert("no");
}
});
});
});
Why are you again and again binding the same event?
....onclick="logoutfunc()"...
Remove this part from your HTML and in your javascript remove the function which surrounds the document ready handler.
$(document).ready(function(){
$("#testid").click(function(){
// your ajax code.
});
});
Related
CODE:
<span class="clickable" id="span_resend">Resend</span>
<script>
$('#span_resend').click(function (e) {
e.preventDefault();
var save_this = $(this);
var middle_this = $('<span class="loader">now_loading</span>');
$(this).replaceWith(middle_this)
$.ajax({
url:'/ajax/',
type:'post',
dataType:'json',
cache:false,
data:{
com: 'some',
},
success:function (data) {
console.log(data)
if (data.res === 'success'){
middle_this.replaceWith(save_this)
}
}
});
})
</script>
It works well when I click resend first.
However cause of script tag, there will be term of now_loading and after loaded, then clicking #span_resend does not works well.
I think it's from that I did not bind click function well on #span_resend.
But I don't know how to do it.
How can I do this?
More explanation: This code is to get ajax response from server, and that ajax response takes some time, maybe 10~15 seconds. So I want to change my resend button to show that ajax is being called, at the same time user cannot click during the waiting of ajax response from server.
The Problem:
Here's what's happening in your code that isn't obvious right away. On first click, you create a jQuery object containing the clicked span, you save this to a variable and after your post completes, you then replace the temporary span with the value of the variable.
Seems like everything should be just fine, but what you've actually done is dynamically added a control to your HTML and while the html of the control is identical to the original span, it is not the same control.
Why does this matter?
Events. It's all about events. When you copy a control, you aren't copying those event listeners associated with it too. So when that event fires again, it looks for the original control and doesn't find it.
You can read in depth about events and event listeners here.
So great, what do you do about all this?
The Solution:
The answer here is to bind those events to a control that is higher than the one you're replacing and won't be replaced itself. So maybe your body tag, or even the document tag. Here's what that would look like in your code:
// Instead of this:
$('#span_resend').click(function (e) {
// Some code.
});
// Do this:
$(document).on('click', '#span_resend', function (e) {
// Some code.
});
This ensures that those event listeners aren't removed when you replace the control.
Here's a mock up of your code using this method:
$(document).on('click', '#span_resend', function (e) {
e.preventDefault();
var save_this = $(this);
var middle_this = $('<span class="loader">now_loading</span>');
$(this).replaceWith(middle_this)
$.ajax({
url:'https://reqres.in/api/users?delay=3',
type:'post',
dataType:'json',
cache:false,
data:{
com: 'some',
res: 'success'
},
success:function (data) {
if (data.res === 'success'){
middle_this.replaceWith(save_this);
}
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="clickable" id="span_resend">Resend</span>
Hope that helps!
I recommend not replacing the button with a now loading but to hide it and show a separate loading indicator, then revert back once it's done
$(document).ready(function() {
$("#saveBtn").click(saveData);
});
function saveData() {
$('#saveBtn').hide();
$('#nowLoadingInd').show();
//AJAX here instead of timeout (just for demo purpose)
window.setTimeout(function() {
$('#saveBtn').show();
$('#nowLoadingInd').hide();
}, 10000);
}
#saveBtn {
display:inline-block;
background:green;
color:white;
border-radius:10px;
cursor:pointer;
padding:3px 5px
}
#nowLoadingInd {
color:gray
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<div id="saveBtn">Save!</div>
<div id="nowLoadingInd" style="display:none">Now Loading...</div>
</body>
</html>
Alternatively, you can pass an element to your ajax options and reference it in the then callback with the this object:
$.ajax({
url:"yourUrl",
data:{your:"data"},
extraProperty:$('#yourElem')
}).then(function() {
this.extraProperty.show()
});
I am passing a table with a button in drupal 7 and trying to print the values but iam not getting any alert
$(document).ready(function() {
$('#edit-title-poc').change(function() {
alert('sdsd'); //**this alert works**
var poc_valueasdasd = $("#edit-title-poc option").filter(":selected").val();
$.ajax({
url: Drupal.settings.basePath + 'ajaxpocsdas3',
data: {
pocdasd: poc_valueasdasd
},
success: function(aasdsabc) {
//data: value returned from server
$('#msg-diasdsadsad').html(aasdsabc);
}
});
});
$('#poc3modulepdf-generator').click(function() {
alert("Handler for .click() called."); //this alert is not working
});
});
This is the screen shot
Use
$(document).on('click','#poc3modulepdf-generator',function(){
alert('clicked')
})
The reason why your code is not working is because you are binding an event to the element which is not yet created.
Using $(document).on('click','#poc3modulepdf-generator') will bind the event to document. This is event delegation. For more details on event delegation see here
I hope this will help.
I have an MVC application and one of the views contains a button with a condition.
<i class="fa fa-sticky-note-o"></i>Did Not Eat
<button type="button" id="btnRemoveDidNotEat" class="btn btnRemoveDidNotEat">Remove Did Not Eat</button>
On click of btnRemoveDidNotEat,btnRemoveDidNotEat is hidden.
If btnDidNotEat is clicked,btnRemoveDidNotEat is shown.
Here is my JS code.
$('.btnDidNotEat').on('click', function () {
$.ajax({
}).done(function (partialViewResult) {
$('#btnRemoveDidNotEat').show();
});
});
$('#btnRemoveDidNotEat').on('click', function () {
$.ajax({
}).done(function (partialViewResult) {
$('#btnRemoveDidNotEat').hide();
});
});
The functionality works for the first time. On click of ".btnDidNotEat", the other button '#btnRemoveDidNotEat' is shown. On click of '#btnRemoveDidNotEat', it is hidden as required.
However the second time,On click of ".btnDidNotEat", the other button '#btnRemoveDidNotEat' is shown. But the button click function for '#btnRemoveDidNotEat' is not called.
I have tried doing the same with style="display:none;", but that gives me the same issue. I have also tried using toggle.
Am I missing something?
EDIT : Simplified the question to make it more clear.
I am not sure I understand your question right, but it looks like your AJAX response seems to have a partial view result. If you are trying to access the button click event of that partial view of AJAX, it will not hit the click event because it will not be attached to the DOM. So instead of your code, you should use something like this.
$("body").on("click", ".btnRemoveDidNotEat", function() {
$.ajax({
}).done(function (partialViewResult) {
$('#btnRemoveDidNotEat').hide();
});
}
I'm not sure if I understood your question correctly, but here is what I got fiddle
Here is some improvements of your script:
$('.btnDidNotEat').click(function () {
$.ajax({
}).done(function (partialViewResult) {
$('#btnRemoveDidNotEat').toggle();
});
});
$('#btnRemoveDidNotEat').click(function () {
$.ajax({
}).done(function (partialViewResult) {
$('#btnRemoveDidNotEat').toggle();
});
});
You can use toggle() function instead of adding and deleting class.
I have three checkboxes that who have checked/unchecked values populated from a model. I'm using an Ajax post on button click event to call controller actions for each checkbox changed event in order to update the DB.
Here is the code for one of the checkboxes (apart from the selector ID, they are all the same):
$(document).ready(function () {
//document.getElementById('UpdateButton').onclick = function () {
$("UpdateButton").click = function () {
$('#NatAm').change(function () {
// if ($('#NatAm').is(':checked')) {
$.ajax({
//url: '#Url.Action("NativeUpdate", "Transactions")',
url: '/Transactions/NativeUpdate',
//data: { isNativeUp: true },
type: 'POST',
dataType: "json"
});
//}
});
Edit (HTML/View Code):
#Html.CheckBox("NatAm", (bool)#ViewBag.NativeAm)
<input name="UpdateButton" id="UpdateButton" type="submit" value="Update" style="margin-left: 15px; margin-top: 3px;" class="btn btn-success" />
I cannot get this to work. Before adding the button, the ajax post was working fine. Thank you for your help!
Your click handler isn't right. You need to pass in the id of the button and use jQuery click handler. You also need not to nest the handlers:
$(document).ready(function() {
$("#UpdateButton").click(update);
$('#NatAm').change(update);
});
function update() {
$.ajax({
url: '/Transactions/NativeUpdate',
type: 'POST',
dataType: 'json'
});
}
JSFiddle Demo: https://jsfiddle.net/vLzwuwdo/
You're telling JQuery to look for 'UpdateButton' tags which in your case does not exist. You're missing the # which indicates an ID in your button.
Try this
$(document).ready(function () {
//document.getElementById('UpdateButton').onclick = function () {
$("#UpdateButton").click(function () {
$('#NatAm').change(function () {
// if ($('#NatAm').is(':checked')) {
$.ajax({
//url: '#Url.Action("NativeUpdate", "Transactions")',
url: '/Transactions/NativeUpdate',
//data: { isNativeUp: true },
type: 'POST',
dataType: "json"
});
//}
}));
id should be unique in same document (NatAm and UpdateButton), replace the duplicate ones by global classes will solve the first problem.
You should not define event inside another since every time you trigger the first it will create new event for the element, in your case every time you click new change event will be created and attached to the first element with NatAm.
Hope this helps.
The short question is when I fill a <div> containing a type=submit button the .click(function(){...} function fails.
What I'm doing is this, #formDialogButton opens #accordion populated by .ajax() containing #userForm with an input type=submit. When client clicks submit it is supposed to fire .ajax() where php does database stuff and returns one of the #userform.
$(".formDialogButton").click(function(){
var userDialog = "#" + this.id + "Dialog";
$("#userForm, #siteForm, #limitForm").html("<img src='ajax-loader.gif' />");
$("#userForm, #siteForm, #limitForm").load("ajax.php", {op: "forms"}, function(responseTxt,statusTxt,xhr){
$("#userForm").html($("#user").html());
$("#siteForm").html($("#site").html());
$("#limitForm").html($("#limit").html());
if(statusTxt=="success") {
$(userDialog).dialog({
autoOpen: false,
draggable: true,
modal: true,
resizable: true,
width: 700,
position: { within: "#mainContent" }
});
$(userDialog).dialog("open");
$( "#accordion").accordion({
collapsible: true,
heightStyle: "content",
});
};
if(statusTxt =="error")
alert("Error: "+xhr.status+": "+xhr.statusText);
});
});
This is working and returns a <input class="submitAndReturn" type="submit" value="Submit" /> in the form. But I can't "find" it to do anything.
$(".submitAndReturn").click(function() {
alert ('this is where I call my regular .formSubmitButton and let success: function() do a .formDialogButton ');
});
I'm a total self taught amateur so please forgive me and try to help. Thanks
Sounds like you are trying to add the click event before the element is loaded on the page. Change
$(".submitAndReturn").on("click", function() {
alert ('as .submit and return is dynamically loaded. so, use on function');
});
to
$(document).on("click", ".submitAndReturn", function(e) {
e.preventDefault(); //cancel the click action if needed
alert ('as .submit and return is dynamically loaded. so, use on function');
});
$(".submitAndReturn").on("click", function() {
alert ('as .submit and return is dynamically loaded. so, use on function');
});
What I'm doing is this, #formDialogButton opens #accordion populated by .ajax() containing #userForm with an input type=submit
If I understand it correct .formDialogButton DOM element is getting loaded in .ajax() callback event.
If you are loading the javascript in question above in header or at the page end, most likely the $(".formDialogButton").click(function() event is not getting attached to DOM.
This happens because the script has already fired before the AJAX has fetched the required DOM to which event has to be attached. You would need to attach the event in .ajax() success callback. Something like
$.ajax({
url: 'YOUR_URL_TO_FETCH_FORM',
success: function(data) {
// associate click
$(".formDialogButton").click(function() // rest of the code
}
});