Post data to PHP using AJAX - javascript

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="#">

Related

Ajax: Why is the post request fired twice?

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.

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.

why submit on key enter not working

I have a login form where if the input sn on focus and then you press enter it will prompt errors asking you to fill out the fields. But if you fill out both fields, no error comes out and even when you enter the correct credentials and then press enter. nothing happens. the form just gets reset. It works fine if I click the button though.
I am using semantic ui as front-end framework and using its form validation for the errors. Is it because of semantic?
here the link for semantic ui form validation's documentation
Here is my form
<form id="login" class="ui large form" method="post" action="">
<div class="ui stacked secondary segment">
<div class="field">
<div class="ui left icon input">
<i class="user icon"></i>
<input type="text" name="username" placeholder="Nama Pengguna">
</div>
</div>
<div class="field">
<div class="ui left icon input">
<i class="lock icon"></i>
<input type="password" name="password" placeholder="Kata laluan">
</div>
</div>
<input type="submit" name="btn-login" value="Log-masuk" class="ui fluid large teal submit button">
</div>
<div class="ui error message"></div>
</form>
and the javascript for it is
$(document).ready(function() {
$('.ui.form').form({
fields: {
username: {
identifier: 'username',
rules: [{
type: 'empty',
prompt: 'Sila masukkan Nama Pengguna'
}]
},
password: {
identifier: 'password',
rules: [{
type: 'empty',
prompt: 'Sila masukkan Kata Laluan'
}]
}
}
});
});
The problem here is that the form has 2 options.
When you hit enter the form submits and when you click the button, your Javascript runs.
You dont want it to submit, you want to trigger the attached JavaScript so
remove the form method and the form action
This is a rule in general, you let the form submit handle the submission, or you let the JavaScript handle it.
As you can see from the semantic ui docs the form doesnt have a method or action
<div class="ui horizontal divider">or</div>
<form class="ui form segment">
<div class="two fields">
<div class="field">
<label>Username</label>
<input placeholder="Username" name="username" type="text">
</div>
<div class="field">
<label>Password</label>
<input type="password" name="password">
</div>
</div>
<div class="inline field">
<div class="ui checkbox">
<input type="checkbox" name="terms">
<label>I agree to the terms and conditions</label>
</div>
</div>
<div class="ui blue submit button">Submit</div>
<div class="ui error message"></div>
</form>
I had the same problem. I prefer to use the default submit button in a form, and not add extra javascript to get a form submit working.
I also had this code:
<div class="ui fluid large blue submit button">
<p>Register</p>
</div>
But when you replace this with this:
<button type="submit" class="blue fluid large ui button">Register</button>
You have the same layout, and the default submit button is working.
of course you still need the form action and method:
<form action="/register/process-form" method="POST" class="ui large form">
by the way, i use jade template rendering, in jade above codes are:
form.ui.large.form(action="/register/process-form" method="POST")
div.ui.stacked.segment
div.field
div.ui.left.icon.input
i.user.icon
input(type="text" name="email" placeholder="E-mail adres")
div.ui.fluid.large.blue.submit.button
p Register
button.blue.fluid.large.ui.button(type="submit") Register
Note: i showed both buttons in the jade code to show the difference, you need to use the bottom one.

AJAX Login form not working

I have the following ajax script and form to login to my website:
<div class="shadowbar"><form id="login" method="post" action="/doLogin">
<div id="alert"></div>
<fieldset>
<legend>Log In</legend>
<div class="input-group">
<span class="input-group-addon">E-Mail</span>
<input type="email" class="form-control" name="email" value="" /><br />
</div>
<div class="input-group">
<span class="input-group-addon">Password</span>
<input type="password" class="form-control" name="password" />
</div>
</fieldset>
<input type="submit" class="btn btn-primary" value="Log In" name="submit" />
</form></div>
<script>
$.ajax({
type: "post",
url: "/doLogin",
data: $('#login').serialize(),
success: function(result) {
if(result == " success"){
window.location = "/index.php";
}else if(result == " failure"){
$("#alert").html("<div class='alert alert-warning'>Either your username or password are incorrect, or you've not activated your account.</div>");
//$("#alert").show();
}
}
});
but it doesn't preform the ajax, and brings me to the result page, which is not what I want. Is there any specific reason that the AJAX is not working? I'm kind of new to JavaScript so sorry if this is obvious.
You are running the Ajax function as soon as the script loads, and not doing anything to prevent the form from submitting normally when the form submits.
You need to move the JS you have already into a function. Then bind that function as a submit handler on the form. Then prevent the default behaviour of the submit event.
$('#login').on("submit", function(event) {
event.preventDefault();
$.ajax({
type: "post",
url: this.action,
data: $(this).serialize(),
success: function(result) {
if (result == " success") {
window.location = "/index.php";
} else if (result == " failure") {
$("#alert").html("<div class='alert alert-warning'>Either your username or password are incorrect, or you've not activated your account.</div>");
//$("#alert").show();
}
}
});
});
<form action="/doLogin" method="post" id='#login'>
<fieldset>
<legend>Log In</legend>
<div class="input-group">
<label for="email" class="input-group-addon">E-Mail</label>
<input type="email" class="form-control" name="email" id="email" value="" />
<br />
</div>
<div class="input-group">
<label class="input-group-addon" for="password">Password</label>
<input type="password" class="form-control" name="password" id="password" />
</div>
</fieldset>
<input type="submit" class="btn btn-primary" value="Log In" name="submit" />
</form>
</div>
That said - when you successfully login, you just redirect to another page. You are almost certainly better off not using Ajax at all for this.
The following link may be helpful if you are new to ajax
http://webdevelopingcat.com/jquery-php-beginner-tutorial-ajax/
login should be the form id but you did not post your form opening tag
<form id = "login">
and in your ajax code you should handle the submit event of the form like this:
$("#login").submit(function({ // your logic should be here
}))

AJAX/PHP Mulitple form POST submit

I am attempting to submit the form data to another page to be processed and am currently need receiving any data. Below are the forms in question. Default form is the login for requesting username/password. One submit button.
<div id="form_wrapper" class="form_wrapper">
<form class="register">
<h3>Register</h3>
<div>
<label>Username:</label>
<input type="text" name="regname"/>
<span class="error">This is an error</span>
</div>
<div>
<label>Password:</label>
<input type="password" name="regpass" />
<span class="error">This is an error</span>
</div>
<div class="bottom">
<div class="remember"><input type="checkbox" /><span>Keep me logged in</span></div>
<input type="submit" value="Register"></input>
You have an account already? Log in here
<div class="clear"></div>
</div>
</form>
<form class="login active">
<h3>Login</h3>
<div>
<label>Username:</label>
<input type="text" name="username"/>
<span class="error">This is an error</span>
</div>
<div>
<label>Password: Forgot your password?</label>
<input type="password" name="password" />
<span class="error">This is an error</span>
</div>
<div class="bottom">
<div class="remember"><input type="checkbox" /><span>Keep me logged in</span></div>
<input type="submit" value="Login"></input>
You don't have an account yet? Register here
<div class="clear"></div>
</div>
</form>
<form class="forgot_password">
<h3>Forgot Password</h3>
<div>
<label>Username or Email:</label>
<input type="text" name="forgotuser" />
<span class="error">This is an error</span>
</div>
<div class="bottom">
<input type="submit" value="Send reminder"></input>
Suddenly remebered? Log in here
You don't have an account? Register here
<div class="clear"></div>
</div>
</form>
</div>
I would like to submit what ever the current form data is
$form_wrapper.find('input[type="submit"]')
.click(function(e){
e.preventDefault();
$.ajax({
url: 'locallogin.php',
type: 'POST',
data: $(this).serialize(),
success: function (results) {
alert(results);
}
});
});
locallogin.php
<?php
print_r($_POST);
?>
Right now the only response is an empty Array. Any ideas?
There are two issues - one as indicated in the comments - you need to use $_POST.
Another lies in,
data: $(this).serialize(),
$(this) is pointing to the button, so you are posting the serialized button. Try as follows :
data: $(".register").serialize(),
As mentioned previously, fix the $(this) and make it $("#form_wrapper") also fix the $POST to $_POST. Your JS should look like this.
$('#form_wrapper').find('input[type="submit"]')
.click(function(e){
e.preventDefault();
$.ajax({
url: 'locallogin.php',
type: 'POST',
data: $(this).closest('form').serialize()+'&buttonName='+$(this).val(),
success: function (results) {
alert(results);
}
});
});
AFTER THE QUESTION ABOUT THE BUTTON NAME.
Added code to the data line of the ajax call.
First, you're serializing $(this) in the click even of an input element. You might want to use data: $(this).closest('form').serialize(). Second, it's print_r($_POST) (you're missing the underscore).

Categories

Resources