jquery function is being called more than once on single click - javascript

I am having more than one button with same class name and different id. but when I click on button, it's called for more than one everytime. for information about code in action, please see the video : https://nimb.ws/3RMoNP
Here is my code
$(document).on("click", ".delete_attachment_confirmation", function(e){
e.preventDefault();
var attachment_id = $(this).data('attachmentid');
$('#delete_attachment_confirmation_'+attachment_id).attr("disabled", true);
$('#delete_attachment_confirmation_'+attachment_id).text("Deleting file");
$.ajax({
url: "<?php echo base_url('attachment/delete_attachment/')?>"+$(this).data('attachmentid'),
type: "GET",
dataType: "text",
success: function(data){
$("#row_"+attachment_id).remove();
$("#attachment_message_body").text(data);
$('#delete_attachment_'+attachment_id).modal('hide');
// attachment message
$('#attachment_message').modal('show');
// modal issue removal trick
$('.modal-backdrop').removeClass('modal-backdrop');
}
});
});
<button class="btn btn-danger delete_attachment_confirmation" id="delete_attachment_confirmation_<?=$row->id?>" data-attachmentid="<?=$row->id?>" ><?php echo $this->lang->line('btn_modal_delete');?>
updated button code
<button class="btn btn-danger delete_attachment_confirmation" id="delete_attachment_confirmation_<?=$row->id?>" data-attachmentid="<?=$row->id?>" ><?php echo $this->lang->line('btn_modal_delete');?>
Highlighted part is showing us that ajax function is being called more than once.

There is nothing in above JS code that is causing it run twice, just that button does not have closing tag and multiple buttons without closing tags and having same class may be the reason, i just ran your code in codepan and it is running fine.
<button class="btn btn-danger delete_attachment_confirmation" id="delete_attachment_confirmation_<?=$row->id?>" data-attachmentid="<?=$row->id?>" ><?php echo $this->lang->line('btn_modal_delete');?></button>
https://codepen.io/balramsinghindia/pen/OJLzjbo

I have used solution provided in this question.
Ajax, prevent multiple request on click

$(".classNamw").unbind().click(function() {
//Your stuff
})

Related

How to make a html button lead to a php site?

I'm creating the buttons dynamically based on if the user is logged in or not.
I'm trying to set the onclick function for the loginBtn for example using location="login.php", but that doesn't seem to do it.
I also tried it with:
$("#loginBtn").click(function(){
$.ajax({
type:'POST',
url:'login.php'
success: function(data) {
alert(data);
}
});
});
but that didn't work either.
Here's the code that creates the buttons:
window.onload = function () {
var loggedIn = '<?php echo $_SESSION["loggedin"] ?>';
//Set login buttons to register/login or logout
if(loggedIn == 1)
{
document.getElementById("loginButtons").innerHTML =
'<button id="logoutBtn" type="button" class="btn btn-primary myButtons">Abmelden</button>'
}
else{
document.getElementById("loginButtons").innerHTML =
'<button id="regBtn" type="button" class="btn btn-primary myButtons" >Registrieren</button>'+
'<button id="loginBtn" type="button" class="btn btn-primary myButtons" onclick="location="warungyoga.de/login.php"" >Anmelden</button>'
}
When the user clicks the Button, it should just lead to the page without any url parameters.
You'll need to wait on setting up the click event listener until the document is ready. This is because the element you want to set up with an event listener is created dynamically after page load (rather than being part of the initial html) and isn't immediately ready.
To wait for the document to be ready, wrap that portion of code in:
$( document ).ready(function() { /* code here */ });
Alternatively, you could listen for clicks on the document with a selector for the specific element as the first parameter:
$(document).click("#loginBtn",function(){ ...
Some other lil' bugs:
You seem to be missing a comma (See the line url:'login.php').
There's no need for a "onclick" attribute when setting up event listeners with jquery.
There's no need to use Javascript here, you can just set up a basic PHP conditional statement to display a different link depending on if the user is logged in or not:
<?php
$loggedIn = $_SESSION["loggedin"];
if ($loggedIn == 1) {
echo '<a id="loginBtn" class="btn btn-primary myButtons" href="/logout.php">Ausloggen</a>';
} else {
echo '<a id="loginBtn" class="btn btn-primary myButtons" href="/login.php">Anmelden</a>';
}
?>
What are you doing :D
`
// If user logged set session id
if(isUserLogged($email, $pass) > 0){
// Set user id
$_SESSION['user']['id'] = 1;
}
if($_SESSION['user']['id'] > 0){
// user logged
echo 'LogOut';
}else{
echo 'LogIn';
}
?>

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 function call not working

I am trying to learn Ajax function calls in jquery. But I could not get the expected output. My code is below
The HTML and Script File is stored in the file 'addevent.php'
HTML Code:
<form id="addinfo">
Year: <div class="styled-select">
<select id="year">
<option>2017</option><option>2018</option>
<option>2019</option><option>2020</option>
</select>
</div>
Team:<div class="styled-select">
<select id="team">
<option>UG</option><option>PG</option>
</select>
</div>
<button class=btn name="add_event" id="add_event" />Add Event
<span id="result"></span>
</form>
</body>
</html>
Script Part:
<script>
$(document).ready(function(){
$("#add_event").click(function(){
var y= $("#year option:selected").text();
var t= $("#team option:selected").text();
$.ajax({
url: 'checkevent.php',
type: 'POST',
dataType: 'json',
data: {year:y , team: t},
success: function(result) {
console.log(result);
var val=result['result'];
document.getElementById("result").innerHTML=val;
}
error: function(exception) {
alert('Exeption:'+exception);
}
});
});
});
</script>
The code in the file checkevent.php is below
header("Content-Type: application/json", true);
$db = new PDO('mysql:host=localhost;dbname=register;charset=utf8mb4', 'root', '', array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
$year =$_POST['year'];
$team =$_POST['team'];
$table=$team.$year;
try
{
if ($db->query("SHOW TABLES LIKE '" . $table . "'")->rowCount() > 0)
{
$r=array("result"=>"already stored");
echo json_encode($r);
}
else
{
$r=array("result"=>"continue");
echo json_encode($r);
}
}//end of try
catch(PDOException $e)
{
$r=array("result"=>"error");
echo json_encode($r);
}//end of catch
?>
Please Note: I have stored the file 'addevent.php' (HTML+Script) in the location 'registration/view/'
The checkevent.php file is stored in the location 'registration'
I tried to check if the button click function for add_event button is working by placing an alert inside it. But it doesn't work.
My expected output is if the table exist the span should display 'already stored' else it should say 'continue'
P.S: I am new to using these ajax call,so sorry if this seems silly. Please help to understand these concepts clearly.
Thanks in advance
You change this line :
url: 'checkevent.php',
By this :
url: '../checkevent.php',
Type F12 and inspect your ajax Call in the console to see if everything is OK
EDIT
OK got it. You missed a comma between success and error callbacks, which broke your Javascript...
Please change script to this and it should work:
<script>
$(document).ready(function(){
$("#add_event").click(function(){
var y= $("#year option:selected").text();
var t= $("#team option:selected").text();
$.ajax({
url: '/registration/checkevent.php',
type: 'POST',
dataType: 'json',
data: {year:y , team: t},
success: function(result) {
console.log(result);
var val=result['result'];
document.getElementById("result").innerHTML=val;
},
error: function(exception) {
alert('Exeption:'+exception);
}
});
});
});
</script>
You have a <button> element inside a form. The default type of a button is type="submit" and therefore the form is submitted before the button onclick listener works. Also you need to close a button element with </button>
Try to change it from
<button class=btn name="add_event" id="add_event" />Add Event
to
<button type="button" class=btn name="add_event" id="add_event" >Add Event</button>
As for the ajax URL, if you are running it from a page located in 'registration/view' and you're calling a page located in 'registration', you need to change the url to something like: url: '/registration/checkevent.php'
because the php file isn't located in the same place as the script that's calling it.
Good luck

Submitting form with AJAX not working. It ignores ajax

I've never used Ajax before, but from researching and other posts here it looks like it should be able to run a form submit code without having to reload the page, but it doesn't seem to work.
It just redirects to ajax_submit.php as if the js file isn't there. I was trying to use Ajax to get to ajax_submit without reloading anything.
Is what i'm trying to do even possible?
HTML form:
<form class="ajax_form" action="ajax_submit.php" method="post">
<input class="input" id="license" type="text" name="license" placeholder="License" value="<?php echo htmlentities($person['license1']); ?>" />
<input class="input" id="license_number" type="text" name="license_number" placeholder="License number" value="<?php echo htmlentities($person['license_number1']); ?>" />
<input type="submit" class="form_button" name="submit_license1" value="Save"/>
<input type="submit" class="form_button" name="clear1" value="Clear"/>
</form>
in scripts.js file:
$(document).ready(function(){
$('.ajax_form').submit(function (event) {
alert('ok');
event.preventDefault();
var form = $(this);
$.ajax({
type: "POST",
url: "ajax_submit.php",//form.attr('action'),
data: form.serialize(),
success: function (data) {alert('ok');}
});
});
});
in ajax_submit.php:
require_once("functions.php");
require_once("session.php");
include("open_db.php");
if(isset($_POST["submit_license1"])){
//query to insert
}elseif(isset($_POST['clear1'])) {
//query to delete
}
I have "<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>"
in the html head
form.serialize() doesn't know which button was used to submit the form, so it can't include any buttons in the result. So when the PHP script checks which submit button is set in $_POST, neither of them will match.
Instead of using a handler on the submit event, use a click handler on the buttons, and add the button's name and value to the data parameter.
$(":submit").click(function(event) {
alert('ok');
event.preventDefault();
var form = $(this.form);
$.ajax({
type: "POST",
url: "ajax_submit.php",//form.attr('action'),
data: form.serialize() + '&' + this.name + '=' + this.value,
success: function (data) {alert('ok');}
});
});
Your ajax call is working perfectly. You have few conceptual error with your code -
form.serialize() will not attach submit button's info.
If you want to clear your form, you can do it using something like this
$('#resetForm').click(function(){
$('.ajax_form')[0].reset();
});
Lastly complete your task & return success or failed value to ajax call using echo like echo 'successful' or echo failed etc. Use an else condition with your code. It will be more clearer to you.
Remove the "action" and "method" attributes from the form. You shouldn't need them.

combine jQuery click handler with php header on same button

I have a button that is now inside a little form:
<form name="picSubmit" method="post">
<button class="btn btn-block btn-default" id="upload"><?php echo $lrow[10]; ?> <span class="glyphicon glyphicon-forward"></span></button>
</form>
then my code on top of the page:
<script language="JavaScript" src="js/cameraUserScript.js"></script>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
header('Location: view-subscribe');
}
?>
This is some javascript/jQuery ajax code to send the content inside a <div> and a picture that i have taken to a php page where i use this content to get some data out of my database and to rename and save that picture into a folder
document.getElementById("upload").addEventListener("click", function(){
var dataUrl = canvas.toDataURL();
var idVal = $('.hiddenId').html();
$.ajax({
type: "POST",
url: "incl/camsave.php",
data: {
imgBase64: dataUrl,
idVal: idVal
}
}).done(function(msg) {
console.log('saved');
});
I added a click event on that submit button ID so that when i click this script has to run. It works in Chrome, but because in Chrome you allways have to click the trust button if you use mediahandling i want to use Mozilla but there it isn't working... Does it has something to do with the combination of the submit button and the click event?
Thanks for the help!
I'm not sure why you're mixing vanilla JS and jQuery here, but you can likely solve this by changing your code to this -
$('#upload').click(function() { // you can use jQuery here too
var dataUrl = canvas.toDataURL();
var idVal = $('.hiddenId').html();
$.ajax({
type: "POST",
url: "incl/camsave.php",
data: {
imgBase64: dataUrl,
idVal: idVal
}
}).done(function(msg) {
console.log('saved');
});
});

Categories

Resources