JavaScript Function to Post clicking checkbox keeps multiplying - javascript

This code its working okay but every time that I click on the checkbox it sends 1 post, then 2 posts, then 4 posts, then 8 posts etc.. to "insert.php". How can I prevent this error?
$(document).ready(function() {
$('#submiter').click(function() {
$("input:checkbox").change(function() {
if ($(this).is(":checked")) {
console.log('checked ' + $(this).val());
$.ajax({
url: "insert.php",
method: "POST",
data: {
test1: $(this).val()
},
success: function(data) {
$('#result').html(data);
}
});
}
});
});
});
<html>
<head>
<title>Ajax Jquery</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<input type="checkbox" value="PHP" id="submiter" />PHP <br />
<div id="result"></div>
</body>
</html>

Initially you have 1 handler for your input, an onclick handler.
When clicked, it adds an onchange listener to same element, from now on, you have 2 listeners for your input.
The next click, it adds one more onchange listener, and so on...
Do you really need an onclick listener? Maybe just the onchange isn't sufficient? See below code (I removed ajax part to avoid requests in this example)
$(document).ready(function() {
$("#submiter").change(function() {
if ($(this).is(":checked")) {
console.log('checked ' + $(this).val());
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<input type="checkbox" value="PHP" id="submiter" />PHP <br />
<div id="result"></div>

Related

Jquery too many ajax requests fired

Why does this code send exactly two requests for each slider change?
I have server application on flask python, and i am using ajax from JQuery to send request to my endpoint, which returns new html plot code. Flask server always getting two request per slider change. How i can to fix it, that it would send one request?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link href="../static/style.css" rel="stylesheet" type="text/css">
<title>plot</title>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script type='text/javascript'>
$(function () {
var form = $('form');
$('#myRange').on('change mouseup', function () {
$.ajax({
type: "POST",
url: "/update_view",
data: form.serialize(),
}).done(function (res) {
$("#plot").html(res)
});
});
});
</script>
</head>
<body>
<div id="body_page">
<form>
<p>Default range slider:</p>
<input type="range" min="1" max="100" value="50" id="myRange" name="slider">
</form>
<div id="plot">
{{ html_plot|safe }}
</div>
</div>
</body>
</html>
because you are subscribed to two events change mouseup.
$(function () {
var form = $('form');
$('#myRange').on('change mouseup', function (e) {
console.log(e.type); // return TWO events
/* $.ajax({
type: "POST",
url: "/update_view",
data: form.serialize(),
}).done(function (res) {
$("#plot").html(res)
}); */
});
});
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<form>
<p>Default range slider:</p>
<input type="range" min="1" max="100" value="50" id="myRange" name="slider">
</form>
In this case, you can only leave change

AJAX request not showing on same page

I want a user to fill in a website url and when clicking on the submit button I want a ajax request to fire and show the response on the same page in <div id="test"></div> but when I fill in the input field and click submit nothing shows. But if I check the console I see the ajax page getting requested.
Here is pagespeed.html
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<form method="post">
<input type="text" id="website" name="website">
<button id="button_1" value="val_1" name="but1">button 1</button>
</form>
<script>
$("button").click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "/lighthouse.php",
data: {
email: $('#website').val() // < note use of 'this' here
},
success: function(result) {
$('#test').html(data);
},
error: function(result) {
alert('error');
}
});
});
</script>
<div id="test">
</div>
And here is lighthouse.php
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script>
$(document).ready(function() {
// INTRODUCTION RIGHT
$("#test").text("Let's get in touch");
});
</script>
So the jQuery function is not showing on the pagespeed.html page because the <div id="test"></div> keeps empty.
Thanks for your time!
You need to change from
$('#test').html(data);
to
$('#test').html(result);
because

jQuery not executing .then()

I am having trouble with a .when() .then() call in jQuery.
I am a teacher taking attendance in class by scanning student IDs. So I have a form that the ID scanner successfully populates and then hits the submit button. This successfully triggers a .when() call and the .ajax() successfully calls my code that populates a Google Sheet.
What I want is a list of students that I have successfully scanned to appear at the bottom of the page. I try to append to this list in the .then() call but it doesn't seem to execute.
<!DOCTYPE html>
<html>
<head>
<title>Student Automations</title>
<!--[if IE]><script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script><![endif]-->
<link rel="stylesheet" type="text/css" href="../css/main.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('button').click(function() {
var student = $('#studentId').val();
var response;
$.when(
$.ajax('/logAttendance.php', {
type: 'POST', // http method
data: {
studentId: $('#studentId').val(),
spreadsheetId: $('#spreadsheetId').val(),
worksheet: $('#worksheet').val(),
studentIdCol: $('#studentIdCol').val()
}, // data to submit
success: function(data, status, xhr) {
response = student + " - added sucessfully";
},
error: function(jqXhr, textStatus, errorMessage) {
response = student + " - something went wrong";
}
})
).then(function(response) {
$('#listOfScanned').append('<li>' + response + '</li>'); //does not work
return false;
})
});
});
</script>
</head>
<body>
<form id='studIdForm'>Student ID: <input type='text' name='studentId' id='studentId' value=''>
<input type='hidden' name='spreadsheetId' value='mygooglesheetid' id='spreadsheetId'>
<input type='hidden' name='worksheet' value='Sheet1' id='worksheet'>
<input type='hidden' name='studentIdCol' value='A' id='studentIdCol'>
<button>Submit</button>
</form>
<script type='text/javascript' language='JavaScript'>
document.forms['studIdForm'].elements['studentId'].focus();
</script>
<p>Already scanned:</p>
<ul id="listOfScanned">
</ul>
</body>
</html>
Edit:
Thank you all for so much quick input. I had a few things wrong, including the fact that the URL that I was calling was not returning JSON which meant that the success: statements were not being called. I removed the .when and have added some bells and whistles and ended up with this.
<!DOCTYPE html>
<html>
<head>
<title>Student Automations</title>
<!--[if IE]><script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script><![endif]-->
<link rel="stylesheet" type="text/css" href="../css/main.css" />
</head>
<body>
<form id='studIdForm'>Student ID: <input type='text' name='studentId' id='studentId' value=''>
<input type='hidden' name='spreadsheetId' value='mygooglesheetid' id='spreadsheetId'>
<input type='hidden' name='worksheet' value='Sheet4' id='worksheet'>
<input type='hidden' name='studentIdCol' value='A' id='studentIdCol'>
<button>Submit</button>
</form>
<script type='text/javascript' language='JavaScript'>document.forms['studIdForm'].elements['studentId'].focus();</script>
<p>Already scanned:</p>
<ul id="listOfScanned">
</ul>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function()
{
$('button').click(function(e){
e.preventDefault();
var student = $('#studentId').val();
$('#studentId').val('');
$.ajax('/logAttendance.php', {
type: 'POST', // http method
data: { studentId: student,
spreadsheetId: $('#spreadsheetId').val(),
worksheet: $('#worksheet').val(),
studentIdCol: $('#studentIdCol').val()
}, // data to submit
success: function (data, status, xhr) {
$('#listOfScanned').prepend('<li>'+ student + ' - added sucessfully</li>');
return false;
},
error: function (jqXhr, textStatus, errorMessage) {
$('#listOfScanned').preppend('<li>'+ student + ' - something went wrong</li>');
return false;
}
});
$('#listOfScanned').find('li').eq(3).remove();
$('#listOfScanned').find('li').eq(4).remove();
$('#listOfScanned').find('li').eq(5).remove();
});
});
</script>
</body>
</html>

how to redirect other url from form action

I have created a form in which on submitting name my url is getting redirected but i want after form action it should get redirect to my mobile validation page. after putting the code, i want it to show the offer page. I am not able to write ajax. my function is not getting called. here is what i have tried till now
http://plnkr.co/edit/3DA7YGb58BgcVcD0d10f?p=preview
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<form name="msform" action="another.html" method="post" id="msform">
<input name="name" type="text" placeholder="First Name" />
<input class="bl" id="submitbl" type="submit" value="Submit" />
</form>
<script type="text/javascript">
$("#submitbl").click(function(){
if($("#msform").valid() === true) {
var name = $('input[name|="name"]').val();
//use ajax to run the check
$.ajax({
type : 'POST',
url : 'mobile.html',
success: function(responseText){
resp = responseText.trim().substring(14);
if(resp == 'qualified') {
url_redirect({url: "offer.html",
method: "post",
data: { "fname": name }
});
}
}
});
}
});
</script>
</body>
</html>
For this you can do something like:
write a jQuery onsubmit function and trigger click event for submit button.
$("#msform").on('submit',function(){
$("#submitbl").trigger('click');
});
Or
submit your form through ajax and in success function redirect to mobile.html

jquery, cannot have an ajax call in a callback function

<head>
<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#submit").click(function(){
$.get("invite_friends_session.php", function(){
});
});
});
</script>
</head>
<body>
<form >
<input type="submit" name="submit" id="submit" style="margin-top:100px; margin-left:100px;" />
</form>
</body>
the $.get("invite_friends_session.php") part does not work. But it works if i keep it outside the callback function.
But i need to call the invite_friends_session.php whenever there is a click on the #submit.
how to do that?
Since the submit button is inside a form, clicking the submit button bubbles up and submits the form. You need to add a return false to the end of the handler:
$("#submit").click(function(){
$.get("invite_friends_session.php", function(){
});
return false;
});
[Edit] You should prevent the default form submit action upon click.
$(document).ready(function(){
$("#submit").click(function(e){
e.preventDefault(); //edit
$.get({ url: "invite_friends_session.php",
success: function() {
alert('success');
},
error: function() {
alert('error');
},
complete: function() {
alert('complete');
}
});
});
});
Remove the <form> tags around the submit button. Since you're using jQuery's .get method, you don't need that form tag (technically, it doesn't even need to be a submit input button). Right now, it's trying to post using the form instead of getting the page via jquery.
Example: http://jsfiddle.net/R3CWp/
<head>
<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#submit").click(function(){
alert("i got clicked");
$.get("invite_friends_session.php", function(){
});
});
});
</script>
</head>
<body>
<input type="submit" name="submit" id="submit" style="margin-top:100px; margin-left:100px;" />
</body>

Categories

Resources