AJAX not receiving POST variables - php

I've read at least 20 of these similar questions and can't figure out what's wrong with my code.
I've got a login form as shown below:
<div class="login-form">
<form class="login-form-container" action="./" method="post" autocomplete="off">
<input id="login-user" type="text" placeholder=" Username"/>
<input id="login-pass" type="password" placeholder=" Password"/>
<div class="login-button-container">
<input id="login-button" type="submit" value="Log in"/>
</div>
</form>
</div>
My login.js script is as below:
$(document).ready(function(){
$("#login-button").click(function(e){
var username = $("#login-user").val();
var password = $("#login-pass").val();
$.ajax({url: "../includes/index.php", //.js file is in a diff directory
data: {'login':true,'name':username,'pwd':password},
type: "POST",
success: function(html) {
if (html=='true') {
//window.location="dashboard.php";
alert('success');
}
else {
alert('failure');
}
}
});
return false;
});
});
This is supposed to get sent back to 'index.php', which has included a separate php file that handles the login information. The reason for this is so I can update the page with the user's successful login without refreshing.
My other php file is simply checking for the post data:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
var_dump($_POST);
if (isset($_POST['login']) && $_POST['login']) {
} else if (isset($_POST['reg']) && $_POST['reg']) { //this is for registration, which will be used once this login is working
} else {
echo 'Neither login/reg were set';
}
The var dump shows:
array(0) { }
So the data is not being received. However, it clearly reaches the php page. I don't know what's wrong, any suggestions?
Edit: I figured I would add, that adding an alert at the top of login.js with the username/password does print the entered values. So the login.js is being reached, and the data is accessible there. But it doesn't go beyond that.
Edit2: Here is my updated HTML and login.js code:
index.php:
<form class="login-form-container" action="./" method="post" autocomplete="off">
<input id="login-user" type="text" placeholder=" Username"/>
<input id="login-pass" type="password" placeholder=" Password"/>
<div class="login-button-container">
<input id="login-button" type="button" value="Log in"/>
</div>
</form>
login.js
$(document).ready(function(){
alert(1);
$("#login-button").click(function(e){
alert(0);
//e.preventDefault();
var username = $("#login-user").val();
var password = $("#login-pass").val();
$.ajax({url: "../includes/index.php",
data: {'login':true,'name':username,'pwd':password},
type: "POST",
success: function(html) {
if (html=='true') {
//window.location="dashboard.php";
alert('success');
}
else {
alert('failure');
}
}
});
return false;
});
});

The solution was to change my
$("#login-button").click(function(e){
to
$(document).on("submit",".login-form-container",function(e) {
which will handle the form submit, and this includes pressing the button as well as hitting enter (ideal situation).
Now the data is being sent successfully and I can handle the actual login/registration SQL, so thank you to #Ashokkumar M. Prajapati for helping to come to the conclusion that the .js script was not actually firing upon submit (not that the rest of you didn't help!)

please replace type: "POST" with method: "POST"
you mentioned it wrong in jquery ajax function.
Default is "GET" in case you don't specify it. So, if you had checked both $_POST & $_GET then you would have found your data in $_GET.
try var_dump($_REQUEST) if it don't show up anything then your client is not sending data to server.
also, check net panel of you browser developer console. so, you will know what data are passed to server.

Related

Custom Html Wordpress Login/Register Page

I have a custom login/register and forgot password html template pages I
recently
purchased. I want to only work through these pages instead of the
wp-login/register pages. I modified the login page a bit and I can
login perfectly if I enter the correct information into the form.
My problem persist when I enter a blank form or incorrect information into the form. The page gets redirected to the standard wp-login.php.
Is there a way to not have the page redirect instead show some text maybe stating "the information you entered is incorrect or empty try again" ?
This is the custom code i have implemented now below.
<form name="loginform" id="loginform" action="https://example.com/wp-login.php" method="post">
</form>
<input type="submit" name="wp-submit" id="wp-submit" value="Log In" class="button button-fill color-black text-thiny">
FYI My template/html files are located in my root publichtml folder instead of wp-content
The correct way to set a login form in wordpress is:
<form method="post" action="<?php echo wp_login_url('URL_TO_REDIRECT_AFTER_LOGGED'); ?>">
<input type="text" name="log">
<input type="password" name="pwd">
<input type="submit" name="wp-submit" value="Login" >
</form>
The form action is the URL when you log sucessfully. Is important to keep the inputs ´name´ fields because these will get wordpress as login data
Change wp-login.php to echo some sort of response that can be used to verify, then control what happens yourself (redirect/error msg) with an ajax call
function myCallBack(response) {
if(response == "success") {
//Handle login redirect
} else {
//Handle error message to user
}
}
$('#wp-submit').on('click', function(event) {
event.preventDefault();
var form = $('#loginform');
var serializedData = form.serialize();
$.ajax({
url: "/wp-login.php",
type: "post",
data: serializedData,
success: myCallBack
});
}

ajax in html, get result from php

I have html:
<body>
<div class="po-logo">
<img src="img/logos/lw.png" alt="logo watchbees"/>
</div>
<form>
<div class="mui-textfield mui-textfield--float-label reg-window">
<input id="username" name="username" type="text"/>
<label>Username</label>
</div>
<div class="mui-textfield mui-textfield--float-label reg-window">
<input id="password" name="password" type="password"/>
<label>Password</label>
</div>
<div class="mui-textfield mui-textfield--float-label reg-window">
<button id="login" value="submit" onclick="return result" class="mui-btn mui-btn--raised reg-win-button">Sign in</button>
</div>
</form>
Jquery in html:
$("#login").click(function(){
var username=$("#username").val();
var password=$("#password").val();
if(($.trim(username).length > 0) & ($.trim(password).length > 0))
{
$.ajax({
type: "POST",
url: "http://127.0.0.1/app/login.php",
data: {username: username, password: password},
beforeSend: function(){ $("#login").html('Prihlasovanie...');},
success: function(data){
if(data == "success")
{
localStorage.login="true";
localStorage.username=username;
window.location.href = "profil.html";
}
else if (data = "failed")
{
alert("Problem s prihlasením, skúste znovu.");
$("#login").html('Prihlásiť sa');
}
}
});
}return false;
});
And php file on localserver, login.php:
if (isset($_POST['username'], $_POST['password'])){
$username=mysql_real_escape_string(htmlspecialchars(trim($_POST['username'])));
$password=mysql_real_escape_string(htmlspecialchars(trim($_POST['password'])));
$login = mysql_num_rows(mysql_query("SELECT * FROM `login` WHERE `username`='$username' AND `password`='$password'"));
if($login != 0){
echo "success";
}
else{
echo "failed";
}
}
But something is wrong, ajax doesn't send my back any data. It only changes #login to "connecting..." but nothing happens. Inscribing information is correct and they are uploaded to the database. Most likely php doesn't send back any data or ajax in html doesn't correct processing data from php. I don't where is problem. Profil.html is in the same folder as index.html. But login.php is on local server.
HTML: index.html; PHP: login.php on local server on my latop; Server: 127.0.0.1, database name db_login.
Any help or pointers greatly appreciated.
First - you have to check is ajax request pointed correctly to your php file. Open inspector in Chrome, switch to tan network then Emanuel filter xhr. After click on #login you should see new request there. Click on it, switch to response tab and paste its content here Please
Your issue is below lines:
in JS:
data: {username: username, password: password},
in PHP:
if(isset($_POST['login'])){
Reason
From JS side, you are passing 2 params in the POST request: username and password, while in PHP, you are checking for $_POST['login']. You should instead be checking for $_POST['username'] and $_POST['password'] in PHP.
Also, you are using mysql_real_escape_string() which is deprecated since PHP 5.5. And, you are injecting the username and password, which are both user inputs, directly into the mysql query leading to serious security issues relating to SQL Injection. Use PHP-MySQLi or PDO API and prepared statements.
OK, but why first If takes true ? Author, Please give us request headers of that xhr from inspector

ajax form submit -> receive respone from php

I've been reading multiple threads about similar cases but even now I'm still unable to do it correctly.
What I want to do
Basically, i.e. I have form which allows user to change his login (simply query to database).
PHP script looks like that:
if(isset($_POST['login'])) {
$doEdit = $user->editData("login", $_POST['login']);
if($doEdit) {
$result = displayInfobox('success', 'Good!');
} else {
$result = displayInfobox('warning', 'Bad!');
}
} else {
$error = 'Bad!';
echo $error;
}
displayInfobox is just a div with class i.e. success and content - Good!.
Right now I would like to send this form by AJAX and display $result without reloading page.
HTML:
<form id="changeLogin" method="post" class="form-inline" action="usercp.php?action=editLogin">
<label for="login">Login:</label><br />
<div class="form-group ">
<input type="text" class="form-control" name="login" id="login" required>
<input type="submit" value="Zmień" class="btn btn-primary">
</div>
</form>
And finnally - my jquery/ajax:
$("#changeLogin").submit(function(e) {
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax({
url: formURL,
type: "POST",
data: postData,
success: function(result) {
alert(result);
},
error: function(response) {}
});
e.preventDefault();
});
$("#changeLogin").submit();
If I leave "success" blank, it works -> form is submitted by ajax, login changed, but I do not see the result message. Otherwise whole page get reloaded.
Also, when I hit F5 form is being submited once again (even in Ajax).
I cant add comments because i do not have enough reputation but...
You should delete the last line with $("#changeLogin").submit();
And then in your php script file you should echo the result so you can get this result in ajax request. After that in your success method you have to read the result and (for example) append it somewhere to show the success or error box
I think you can use a normal button instead of submit button,just onclick can be an ajax request, the form should not be submitted,good luck.

Ajax return false to form

Hi I'm looking to check my database when a user signs up to my website to make sure that the username they chose doesn't already exist and if it does let them know. My code below isn't working though the returns in the ajax don't seem to be returned to my form no matter what i do and the form always submits. Why is this happening? Thank you for any help
HTML
<form name="signup" action="Test1.php" onsubmit="return checkUser();" method="get">
Username: <input type="text" name="user" />
<input type="submit" value="Submit" />
</form>
Javascript
<script type="text/javascript" src="jquery-1.7.1.min.js"/></script>
<script type="text/javascript">
function checkUser(){
var userV = document.signup.user.value;
$.ajax({
url: "Test.php",
type: "POST",
data: {user:userV},
success: function (response) {
if(response=="0"){
//Username already exists notify user
return false;
}else{
return true;
}
}
});
}
</script>
Test.php
<?PHP
$user = $_POST['user'];
if($user=="test"){
die("0");
}else{
die("1")
}
?>
Test1.php
<?PHP
echo "Form submitted";
?>
You put the return value inside the success callback of your ajax call, whose execution is delayed till server answers.
onsubmit="return checkUser();" expects a true or false value in checkUser() function:
function checkUser(){
if( stuff )
return true;
else
return false;
}
Anyway this is an overall bad approach because it relies on intrusive javascript. A better solution would be moving all client side logic out of markup:
HTML
<form name="signup" action="Test1.php" method="get">
<label for="_user">Username:</label><input type="text" name="user" id="_user"/>
<input type="submit" value="Submit" />
</form>
JS
<script>
// wrapping the code in a $(function(){ ... }); call delays its execution till document is loaded
$(function(){
$('form[name="signup"]').on('submit', function(event){
// this prevents browser from actually following form url
event.preventDefault();
// a reference to the form to get used inside ajax callback
var form = this;
$.ajax({
url: $(form).attr('action'),
type: "POST",
data: {user:$(form.user).val()},
success: function (response) {
if(response=="0"){
alert('User exists!');
}else{
alert('User does not exist!');
}
}
});
});
});
</script>
Where the alerts would be a proper message to the user, or a more sophisticate validation - this is just for example's sake.
You return false in the callback, thats too "late", as it will be called when the request is done. Think about adding an explicit e.preventDefault() or return false to your function. Currently, it will return undefined, as you have defined the return statement in the "inner" function.
Of course you will then need to manually navigate to the target page.
Or set the async parameter of the $.ajax() call explictly to false.

Jquery login form resubmit on incorrect username or passowrd

Need some help with a login form please.
I've set up a login form through ajax, but it's not working when the username/password are incorrect.
The php script works perfectly when not used through ajax. It does what it's supposed to.
When submitting it through an ajax call, if the details are incorrect a new form pops up and asks for you to try again. That's good, but I can't resubmit the form. Clicking on the Submit link doesn't work.
Here's the code:
As an aside, the ajax doesn't use "submit()" to load the ajax. There is a separate link outside the form that needs to be on a "click()".
<script>
$(document).ready(function(){
$("#login_submit").click(function() {
$("#form2").hide();
$('#finish').html('Attempting Login');
var username = $("input#username").val();
var password = $("input#password").val();
$.ajax({
url: 'auth.php',
type: "POST",
data: "username="+username+"&password="+password+"",
success: function(data) {
$('#finish').html(data);
}
});
});
});
$(document).ajaxStart(function(){
$('#loading').show();
}).ajaxStop(function(){
$('#loading').hide();
});
</script>
<div id="form2">
<form method="post" id="login">
<input type="text" name="username" id="username"/><br />
<input type="text" name="password" id="password"/><br />
</form>
<span id="login_submit">Submit</span>
</div>
<div id="loading">
Loading...<img src="loading/loading6.gif" width="105" height="16" alt="loading" />
</div>
<div id="finish">
</div>
So as I said, it loads the form to resubmit, but clicking on "Submit" doesn't resend the information.
Any tips for getting this to resubmit?
data: "username="+username+"&password="+password+"",
Try as:
data: "username="+username+"&password="+password,
Answered my own question, sorry guys.
I changed the ajax to check for certain data being returned in the success callback, and changed the form based on that data, instead of replacing the form completely.
I'll post the changes in a bit

Categories