AJAX HTTP post request is triggered 3 times - javascript

In my webapp, the Ajax request is executed 3 times, and I have no idea why this is happening.
Can someone please help here?
My Javascript:
$(document).ready(function() {
console.log("ready!");
$('form').on('submit', function(e) { //
e.preventDefault();
// on form submission ...
console.log("the form has beeen submitted");
// grab values
valueOne = $('input[name="perfid"]').val();
valueTwo = $('input[name="hostname"]').val();
valueThree = $('input[name="iteration"]').val();
console.log(valueOne)
console.log(valueTwo)
console.log(valueThree)
$.ajax({
type: "POST",
url: "/",
dataType:'json',
data : { 'first': valueOne,'second': valueTwo,'third': valueThree},
success: function(data) {
var res = data.AVG;
var p = '<p><pre>'+res+'</pre></p>';
$('#result').append(p);
},
error: function(error) {
console.log(error)
}
});
}); });
And my HTML is:
<form role="form" method="post" onsubmit="return false;">
<div class="form-group">
<input type="text" class="input-medium" id="perfid" name="perfid" placeholder="Enter a Perf ID" required style="height:30px;">
<input type="text" class="input-medium" id="hostname" name="hostname" placeholder="Enter a HostName" style="height:30px;">
<input type="text" class="input-medium" id="iteration" name="iteration" placeholder="Enter a Iteration" required style="height:30px;">
<button type="submit" class="btn btn-default" style="height:30px;">Get Data</button>
</div>
</form>
I have written the code for only one AJAX POST request,
EDIT:
This is the console output:

Please make sure you have included the js file only once,
and add a return false at the end of the submit event callback

look at the selector
$('form').on('submit', function(e) {
if the page has 3 forms, the above selector will execute 3 times
Try to add id to the form like this. sorry about my bad english

Related

Why can I not run javascript (Js2Py) in Python (Streamlit)?

I am using Streamlit to build a simple app. In this app I made a simple form using FormSubmit to let people contact me. But I don't want them to leave the website when they click on Send button, so I am trying to send the form using AJAX.
To integrate JS in Python I am using Js2Py, but I can't solve this.
This is the form:
contact_form = """
<form id="myForm">
<input type="hidden" name="_captcha" value="false">
<input type="text" name="name" style="font-size:20px;background-color:#72c2dd; color:#000000" placeholder="Your name" required>
<input type="email" name="email" style="font-size:20px;background-color:#72c2dd; color:#000000" placeholder="Your email" required>
<textarea name="message" style="font-family:'Alegreya, serif';
font-size:20px;" placeholder="Your message here" required></textarea>
<input type="hidden" name="_template" value="table">
<button type="submit" value="Submit" id="sendButton" class="block">Send</button>
</form>
"""
so I made a javascript variable, to check when Send button is clicked:
check_submit = '''<script src="https://code.jquery.com/jquery-3.6.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#sendButton").click(function(e) {
e.preventDefault();
var form = $('myForm'[0]);
var data = new FormData(form);
$.ajax({
method: "POST",
url: "https://formsubmit.co/my-email",
dataType: 'json',
data: data,
success: (data) => console.log(data),
error: (err) => console.log(err)
});
});
});
</script>
'''
then:
st.markdown(contact_form, unsafe_allow_html=True)
So I am passing the javascript variable into the function eval_js() from Js2Py:
js2py.eval_js(check_submit)
I got my form up, and an error message below the form:
JsException: SyntaxError: Line 1: Unexpected token <
and when I fill the form and clicking the Send button, nothing happens.
This means according to me that I misunderstood how to use JS2Py in Python!!!
Any help/suggestion to show me where I did wrong, is very appreciated

Stop form from redirecting on submit

I'm very aware that this question has been asked several times but I have tried at least 6 solutions and it has not worked. I'm collecting data to send to a google form but on form submission the browser redirects to a success page. I'd like for it to all happen using AJAX but my code isn't working.
HTML:
<form id="userinfo" method="get" action="https://script.google.com/macros/s/xxx/exec" accept-charset="UTF-8" onsubmit="return false">
<input type="text" name="name" id="formname" placeholder="Name">
<input type="text" name="email" id="formemail" placeholder="Email">placeholder="Game Days">
<input type="submit" value="submit" id="upload_data"/>
</form>
JS:
$("#userinfo").submit(function(e) {
var urll = "https://script.google.com/macros/s/xxx/exec"; // the script where you handle the form input.
$.ajax({
type: "GET",
url: urll,
data: $("#userinfo").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
You could use the jQuery Form Plugin to send the form without doing a submit.
Your code should look kinda like this:
$("#userInfo").ajaxSubmit({
success: function(data)
{
alert(data); // show response from the php script.
}
});

Form get submitted even the form validation fails

I am using http://www.formvalidator.net/index.html to validate my form but the form gets submitted even when the validation get failed.
Form code:
<form name="add-todo" class="form-horizontal" action="" method="post">
<h5>Add New Item</h5>
<div class="form-group">
<div class="col-md-12">
<input type="text" data-validation="required" class="form-control" id="todo-text-input" name="todo-text">
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<button type="submit" class="btn btn-primary btn-add">Add</button>
</div>
</div>
</form>
jQuery code:
$(document).ready(function() {
$.validate({
modules: 'security'
});
$('form[name=add-todo]').submit(function(e) {
e.preventDefault();
var text = $("#todo-text-input").val();
$('.btn-add').text('Saving ....');
$.ajax({
url: this.action,
type: this.method,
data: {
text: text
},
success: function(response) {
$("#todo-text-input").empty();
$('.messages').removeClass('hide-element');
$('.alert').addClass('alert-success');
$('.alert').text('To do item added successfully.');
$('.alert').fadeTo(2000, 500).slideUp(500, function() {
$('.alert').slideUp(500);
});
}
});
});
});
dont use submit button. You can use
<button type="button" class="btn btn-primary btn-add">Add</button>
after that check your validation status. if its valid then submit the form.
<input type="text" data-validation="required" class="form-control" id="todo-text-input" name="todo-text">
In your input field you don't need to use data-validation="required" just use required like
<input type="text" required class="form-control" id="todo-text-input" name="todo-text">
Please change you form validation code configuration like this:
$.validate({
form : '#registration-form',
modules : 'security',
onSuccess : function($form) {
alert('The form '+$form.attr('id')+' is valid!');
// write your ajax code to submit form data on server
return false; // Will stop the submission of the form
}
});
For more info follow:
http://www.formvalidator.net/index.html#configuration

How to submit form using Ajax in MVC

I am getting problem to save my form data in the database. I am done small code on that which is shown below, when i enter data in form and click on my submit button it not work.
$(".btn").click(function(e) {
e.preventDefault();
var form = $("#frm");
$.ajax({
url: '/Form/Index',
data: form.serialize(),
type: 'POST',
success: function(data) {
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form role="form" id="frm">
<div class="form-group">
<div class="col-sm-6 col-lg-12 col-md-12">
<div class="form-group">
<label for="name" style="color:black;">Product Name</label>
<input type="text" class="form-control" id="name"
placeholder="Product Name" style="color:black;">
</div>
<div class="form-group">
<label for="name" style="color:black;">Product Date</label>
<input type="text" class="form-control" id="Text1"
placeholder="Date" style="color:black;">
</div>
<div class="form-group">
<label for="name" style="color:black;">Product Price</label>
<input type="text" class="form-control" id="Text2"
placeholder="Date" style="color:black;">
</div>
</div>
</div>
<button type="submit" class="btn btn-default" id="ok" >Submit</button>
</form>
Above is my code please give me solution on that
As I've checked you code, client side code is working fine, The only problem I can imagine in this case is you url path.
make sure you are providing correct url path.
You should check if its hitting the that page or not.
Which Framework you are using. Different framework has different syntax to pass the value in URL. Check the path you are getting in the page source page view in URL parameter or you can check the error in console log after the submit. It may be not getting the correct path of your action.
Make sure ajax library loaded successfully, and try to have alert messages to have forward step where you reached, have this test:
$(".btn").click(function(e) {
e.preventDefault();
var form = $("#frm");
$.ajax({
url: '/Form/Index',
data: form.serialize(),
type: 'POST',
success: function(data) {
},
beforeSend: function() {
alert('before send alert')
},
error: function (request, status, error) {
alert(error);
},
});
});
if beforeSend not executed so your issue is related to ajax library.
use this :
$("#ok").click(function(e) {
// your code
}
Refer to id in javascript rather than class attribute.
If you refer class attribute than once it has click javascript perform preventDefault on that class so that if not refresh your page, The button is not working.
Put preventDefault function at last of your function.
Remove the type="submit" from button
You have to get the form submit with id and serialize the form data
`
$("#formid").submit(function(e) {
var url = "urlpathtohandlerequest";
$.ajax({
type: "POST",
url: url,
data: $("#formid").serialize(),
success: function(response)
{
alert(response);
}
});
e.preventDefault(); // stops default submit.
});
`

Contact form using e.preventDefault(); not working live

UPDATE - the contact form is found at this URL.
I am trying to get the following contact form to function, using this tutorial.
I manage to get everything to work as expected on my computer using apache webserver.
After uploading the files to an online website, the ajax function does not kick in.
I seems like the e.preventDefault(); stops working after the upload, and the form is redirected to a new site,and not just being processed on the site without the reload.
I have also been trying to use the return false; instead of e.preventDefault(); without any success.
Her is my code:
.html
<form method="post" action='mail/mail.php'>
<label>Name</label>
<input name="name" id="name" placeholder="Name.." required="true" class="input-field">
<label>Mail</label>
<input type="email" name="email" placeholder="Mail.." required="true" class="input-field">
<label>Msg</label>
<textarea name="message" id="message" class="textarea-field" required="true"></textarea>
<input type="submit" id="submit" name="submit" value="Send">
</form>
<div id="loading">
Sender melding...
</div>
<div id="success">
</div>
.js
$(function(){
$('form').submit(function(e){
var thisForm = $(this);
//Prevent the default form action
//return false;
e.preventDefault();
//Hide the form
$(this).fadeOut(function(){
//Display the "loading" message
$("#loading").fadeIn(function(){
//Post the form to the send script
$.ajax({
type: 'POST',
url: thisForm.attr("action"),
data: thisForm.serialize(),
//Wait for a successful response
success: function(data){
//Hide the "loading" message
$("#loading").fadeOut(function(){
//Display the "success" message
$("#success").text(data).fadeIn();
});
}
});
});
});
})
Please help!
That's because your JS is missing a closing });. Please check this demo to confirm that the default action is indeed prevented and the ajax does kick in. However, I was expecting a POST but instead I am seeing an OPTIONS request.
NOTE: Giving an element a name or id attribute value of submit is bad practice. You cannot for example use JavaScript to submit the form via default form submission -- this.submit() or $('form')[0].submit() without getting the error ...submit() is not a function .....
$(function() {
$('form').submit(function(e) {
var thisForm = $(this);
//Prevent the default form action
//return false;
e.preventDefault();
//Hide the form
$(this).fadeOut(function() {
//Display the "loading" message
$("#loading").fadeIn(function() {
//Post the form to the send script
$.ajax({
type: 'POST',
url: thisForm.attr("action"),
data: thisForm.serialize(),
//Wait for a successful response
success: function(data) {
//Hide the "loading" message
$("#loading").fadeOut(function() {
//Display the "success" message
$("#success").text(data).fadeIn();
});
}
});
});
});
});
}); // <==== MISSING THIS
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form method="post" action='mail/mail.php'>
<label>Name</label>
<input name="name" id="name" placeholder="Name.." required="true" class="input-field">
<label>Mail</label>
<input type="email" name="email" placeholder="Mail.." required="true" class="input-field">
<label>Msg</label>
<textarea name="message" id="message" class="textarea-field" required="true"></textarea>
<input type="submit" id="submit" name="submit" value="Send">
</form>
<div id="loading">
Sender melding...
</div>
<div id="success">
</div>
Since you are submitting via AJAX anyway, you may find it easier to change your input type to button, and bind to click instead of form submit, to avoid the default submit behaviour you are trying to circumvent.

Categories