Ajax: Why is the post request fired twice? - javascript

I have noticed my request is fired twice, but I dont understand why.
I have a simple form:
<form method="POST" class="mb-4" autocomplete="off" action="/recipe/add" novalidate id="form">
<div class="form-group">
<label for="title">Rezeptname</label>
<input required type="text" name="title" id="title" class="form-control form-control-sm needs-validation" value="">
<div class="invalid-feedback">Ein Name wird für das Rezept benötigt!</div>
</div>
<div class="form-group">
<label for="cookingTime">Zubereitungsdauer in Minuten</label>
<input type="number" name="cookingTime" id="cookingTime" class="form-control form-control-sm" value="">
</div>
<div class="form-group">
<label for="servings">Portionen</label>
<input type="number" name="servings" id="servings" class="form-control form-control-sm" value="">
</div>
<label for="ingredients">Zutaten</label>
<button class="btn btn-outline-secondary btn-sm ml-2" onclick="createInputRow()"><i class="fas fa-plus"></i></button>
<div class="mb-4" name="ingredients">
<table class="table">
<tbody id="tbody">
</tbody>
</table>
</div>
<button type="submit" class="btn btn-primary btn-sm" id="submit">Speichern</button>
Zurück
</form>
on document load, I add the event listener for the button
$(document).ready(() => {
$("#submit").unbind("click").bind("click", event => {
onSubmit(event)
})
})
in the onSubmit method, the request is sent out:
$.ajax({
type: "POST",
url: "/recipe/add",
data: {recipe: recipeData},
success: (res) => {
console.log(JSON.parse(res))
}
});
In the network scan I could see that the request is fired twice.
This leads to getting an error on my server.
When setting a breakpoint in the front end, it is only triggered once, though. The backend recieves two requests like in the network scan.
I already tried the $("#submit").unbind().bind() as mentioned in other sources but that doesnt fix the problem.

In the case that you want to use your <form> tag for other purposes (including redirect) -- You should remove the type=submit off the submit button, OR use preventDefault() to prevent the default form action. Also note that hitting the "Enter" key may also submit the form if in an text field. You can also use preventDefault() to prevent the form from being submitted during this action as well.

Related

PHP :unable to check if a form is submitted

I am using a form in php file inside a modal window like this
<div class="modal-body">
<form method="post" action="m.php">
<div class="form-group">
<lable>Name</lable>
<input type="text" class="form-control" required="required">
</div>
<div class="form-group">
<lable>Email</lable>
<input type="text" class="form-control" required>
</div>
<div class="form-group">
<lable>Details</lable>
<input type="text" class="form-control" required>
</div>
<div class="form-group">
<lable>Message</lable>
<textarea name="" id="" class="form-control"></textarea>
</div>
<div class="form-group">
Submit
</div>
</form>
</div>
file name is m.php now when i press the submit button it doesn't detect form submission
<?php
if( ($_SERVER['REQUEST_METHOD'] == 'POST')){
die("form submitted");
}
?>
i tried $_POST['submit'] as well kindly help me whats wrong with it
This is because you dont press a submit button, you press a link called submit. Try replacing it with <input type="submit" value="Submit" />.
Also, your check wether your form has been submitted uses a dangerous method. If you have multiple forms to be handled in your code, it will catch them all. A better approach would be:
if( isset($_POST['nameOfSubmitbutton']) ){}
// because you can now easily do:
if( isset($_POST['completelyDifferentButton']) ){}
If you want to keep the anchor (I advice against it), you can use javascript to fake the submit for you:
document.getElementById('yourAnchor').onclick = function(){
document.getElementById('yourForm').submit();
}
// Or if you have jQuery:
$('#yourAnchor').on('click', function(e){
e.preventDefault();
$(this).closest('form').submit();
});
The submit button you are using is pointing towards the same url, can you try something like?
<input class="btn btn-default" type="submit" value="Submit">
and then try to see if the form is submitted from PHP.
And i also would recommend that you use some framework for this to handle sql injections and/or other exploits.
Wrong use of form submit.
<div class="form-group">
Submit
</div>
You should use it like:-
<div class="form-group">
<input type="submit" class="btn btn-default" name="submit" style="background: #eee; width:100px;display: block;margin-left:auto;" value="Submit"/>
</div>
Hopefully this will solve the issue.

Jquery does not select the form element given an ID

I'm trying to submit a form with jquery, but it does not acknowledge that I submitted it when I click the "submit" button.
My html is as follows:
<form id="singleParam" role="form">
<div class="form-group">
<label for="sample_size">Number of samples needed</label>
<input name="choices[sample_size]" type="number" class="form-control" id="sample_size" placeholder="Enter desired number of samples">
</div>
<div class="form-group">
<label for="mode">Mode of the distribution (value most likely to be sampled)</label>
<input name="choices[mode]" type="number" class="form-control" id="mode" placeholder="Enter the likeliest value for your parameter">
</div>
<div class="form-group">
<label for="confidence">Confidence interval factor</label>
<input name="choices[confidence]" type="number" class="form-control" id="confidence" placeholder="Enter desired confidence interval factor">
</div>
<div class="form-group">
<input type="button" class="btn btn-primary btn-lg" id="submit" name="submit">
</div>
</form>
and JS is:
$('#singleParam').on('submit', function () {
alert('Form submitted!');
console.log('Form submitted!');
return false;
});
The alert() or console.log() in the loop do not work, meaning that jquery did not run the code on submit. What am I doing wrong? It might be worth mentioning that I am using bootstrap.
Change the button type from type="button" to type="submit"
EDIT:-
Make sure you are calling all your event handlers once the DOM is fully loaded by adding all the code inside dom ready event like:-
$(document).ready(function() {
// code here
});

Two AJAX form submissions in a single JS file, only one is working

In the HTML, the forms look identical, just the form ID is changed. I use this JS file to submit the forms using AJAX:
$("#change-password").submit(function(e) {
var url = "http://domain/actions";
$.ajax({
type: "POST",
url: url,
data: $("#change-password").serialize(),
success: function(data) {
$("div.change-password-response").html(data);
}
});
e.preventDefault();
});
$("#change-email").submit(function(e) {
var url = "http://domain/actions";
$.ajax({
type: "POST",
url: url,
data: $("#change-email").serialize(),
success: function(data) {
$("div.change-email-response").html(data);
}
});
e.preventDefault();
});
HTML Part
<div class="col-md-6 col-sm-6 add_bottom_30">
<h4>Schimbare parola</h4>
<form id="change-password" method="post">
<div class="form-group">
<label>Parola veche</label>
<input class="form-control" name="old_password" id="old_password" type="password" autocomplete="off">
</div>
<div class="form-group">
<label>Parola noua</label>
<input class="form-control" name="new_password" id="new_password" type="password" autocomplete="off">
</div>
<div class="form-group">
<label>Confirma parola noua</label>
<input class="form-control" name="confirm_new_password" id="confirm_new_password" type="password" autocomplete="off">
</div>
<input type="hidden" name="action" value="change-password">
<button type="submit" class="btn_1 green">Actualizeaza parola</button>
<div class="change-password-response form-response"></div>
</form>
</div>
<div class="col-md-6 col-sm-6 add_bottom_30">
<h4>Schimbare adresa email</h4>
<form id="change-email" method="post">
<div class="form-group">
<label>Email vechi</label>
<input class="form-control" name="old_email" id="old_email" type="text" autocomplete="off">
</div>
<div class="form-group">
<label>Email nou</label>
<input class="form-control" name="new_email" id="new_email" type="text" autocomplete="off">
</div>
<div class="form-group">
<label>Confirma email nou</label>
<input class="form-control" name="confirm_new_email" id="confirm_new_email" type="password" autocomplete="off">
</div>
<input type="hidden" name="action" value="change-email">
<button type="submit" class="btn_1 green">Actualizeaza Email</button>
<div class="change-email-response form-response"></div>
</form>
</div>
Now, my problem is that Form 1 is working, Form 2 is not triggering the AJAX and works as normal form. What am I doing wrong?
Check if #change-email has other binded events.
In Firebug, inspect #change-email element and go to Event tab.
In Chrome, inspect that element and go to Event Listeners tab.
You will see all binded events and corresponded callback functions.
If it will not help, try to submit a form manually from Console
Inspect a form, then run
$($0).submit();
If it will work, looks like you have some events on you button.

ajax form not submitting handler expecting submit name attribute

I'm having a little problem getting a form to submit via ajax. I think it's one of two problems:
leads.py (which I am able to view, but do not have the ability to modify) is expecting a submit input name of name="submitButtonName" and because I am using e.preventDefault(); to disable normal form submitting the form is not being handled by the handler when submitted.
It could be possibly that the data being serialized is wrong, when i output it to console it looks like this which appears to be duplicated:
first_name=Frank&last_name=TheTank&email_addr=frank%40thetank.com&remarks=&first_name=Frank&last_name=TheTank&email_addr=frank%40thetank.com
any suggestions?
here is the full script:
<!-- Defines element markup -->
<dom-module id="landing-modal">
<template>
<div id="landing-modal" class="modal hide fade" tabindex="-1" role="dialog">
<div class="modal-body">
<p class=lead>
To view this listing, please provide us with some basic contact information...
</p>
<form class="form-horizontal lead-form" method="post" action="/leads/buy">
<div class="control-group">
<label class="control-label">Required Information</label>
</div>
<div class="control-group">
<label class="control-label">First Name</label>
<div class="controls">
<input type="text" name="first_name" value="" required="" class="style-scope lead-form">
</div>
</div>
<div class="control-group">
<label class="control-label">Last Name</label>
<div class="controls">
<input type="text" name="last_name" value="" required="" class="style-scope lead-form">
</div>
</div>
<div class="control-group">
<label class="control-label">Email</label>
<div class="controls">
<input type="email" name="email_addr" value="" required="" class="style-scope lead-form">
</div>
</div>
<div class="control-group">
<div class="controls">
<input style="display:none;" type="text" name="remarks" value="" />
<input type="reset" value="Reset" name="reset" class="btn">
<input class="btn btn-primary" type="submit" name="submitButtonName" value="Submit" />
</div>
</div>
</form>
</div>
</div>
</template>
<script>
$(document).on('submit', '.lead-form', function(e) {
$.ajax({
url: $('.lead-form').attr('action'), //gets the action url
type: $('.lead-form').attr('method'), //gets the form method post
data: $('.lead-form').serialize(), //creates the form submit date eg. FirstName=Mickey&LastName=Mouse
success: function(html) {
console.log($('.lead-form').serialize());
}
});
e.preventDefault(); //prevents the submit input from being submitted normally
});
Polymer({
is: 'landing-modal',
created: function() {},
ready: function() {},
attached: function() {},
detached: function() {},
attributeChanged: function(name, type) {}
});
</script>
</dom-module>
edit::
I tried to add
<input type="hidden" name="submitButtonName" />
<input class="btn btn-primary" type="submit" name="submit" value="Submit" />
which results in a 500 error in console
server side code:
if "submitButtonName" in kwargs:
errors = []
if not kwargs['first_name']:
errors.append("Please enter your first name.")
if not kwargs['last_name']:
errors.append("Please enter your last name.")
if not kwargs['email_addr']:
errors.append("Please enter your email address.")
if errors:
error_msg = "<ul>" + "".join([
"<li>"+x for x in errors
]) + "</ul>"
result['error_msg'] = error_msg
else:
save = True
if save:
# 'remarks' is an invisible field that can only get filled in by
# spam bots, so if there's a value in it, ignore the submission.
if kwargs['remarks']:
import sys
sys.stderr.write("Ignoring spam submission: %r\n" % ([mode,kwargs],))
else:
self.save_form(mode, kwargs)
raise cherrypy.InternalRedirect("/leads/thankyou/"+mode)
result.update(self.form.render(values))
if mode=="C":
result.update(self.cmaform.render(values))
if mode=="E":
result.update(self.contactform.render(values))
return result

Post data to PHP using AJAX

I am trying to test PHP post data using AJAX. From page test I want to post on to the same page and check if PHP receives post data, if data is posted just to see if redirection is successful, so that I can write authentication code and assign session before page redirects.
When I click on the login button, I just checking isset post data and if data exists then redirect. I am not sure why this is not working. Any help is appreciated.
<script>
$(document).ready(function(){
$('#login').click(function(){
$.ajax({
type: 'POST',
url: 'http://domain.com/backend/test',
data: { username: "John", password: "Boston" }
});
return false;
});
});
</script>
<?php
if(isset($_POST['username']) && isset($_POST['password'])) {
redirectto("http://domain.com/backend/test2");
// redirecto is a function equivalent to header location
}
?>
<form autocomplete="off" class="ui fluid form segment" method="post">
<div class="ui fluid form segment">
<div class="two fields">
<div class="field">
<label>Email/Username</label>
<input placeholder="Email/Username" name="username" id="username" type="text">
</div>
<div class="field">
<label>Password</label>
<input placeholder="Password" name="password" id="password" type="password">
</div>
</div>
<input type="submit" class="ui fluid submit button" name="dosubmit" value="Submit" id="login" />
</div>
</form>
Change
<input type="submit" class="ui fluid submit button" name="dosubmit" value="Submit" id="login" />
to
<input type="button" class="ui fluid submit button" name="dosubmit" value="Submit" id="login" />
Even if you triggered the click event of #login button, its a submit type and it will trigger the submit event first. Changing the button type should help.
In the JS, instead of using a click event, use submit.
I mean, instead of
$('#login').click(function(){
use
$('#login').submit(function(){
Also, you may add an action property to the form:
<form autocomplete="off" class="ui fluid form segment" method="post" action="#">

Categories

Resources