I am trying to make a simple login with ajax. The problem i have is that i do not get any response from my request. When I try to use
myurl.com/login.php is_ajax=1&username=test&password=test
I get a succes message back.
$(document).ready(function(){
$("#submit").click(function(){
var form_data = {
usernm: $("#username").val(),
passwd: $("#password").val(),
is_ajax: 1
};
$.ajax({
type:"POST",
url: "myurl.php" ,
data: form_data,
succes: function (response)
{
if (response == 'succes'){
window.location="myurl.html";
}
else{
alert("wrong username password combination")
}
}
});
return false;
});
});
my php:
$is_ajax = $_REQUEST['is_ajax'];
if(isset($is_ajax) && $is_ajax)
{
$uName = $_REQUEST ['username'];
$pWord = $_REQUEST ['password'];
if($uName == 'test' && $pWord == 'test'){
echo 'succes';
}
else{
echo 'false';
}
}
you should use
$uName = $_REQUEST ['usernm'];
$pWord = $_REQUEST ['passwd'];
INSTEAD of
$uName = $_REQUEST ['username'];
$pWord = $_REQUEST ['password'];
in your php file and change succes to success
Replace succes with success
$.ajax({
type:"POST",
url: "myurl.php" ,
data: form_data,
success: function (response){
if (response == 'success'){
window.location="myurl.html";
}else{
alert("wrong username password combination");
}
}
});
also change the data attribute names
var form_data = {
username: $("#username").val(),
password: $("#password").val(),
is_ajax: 1
};
If you are doing it with $.ajax, then your datatype is wrong. It must be application/x-www-form-urlencoded.
So please change your JS part to this:
$(document).ready(function(){
$("#submit").click(function(){
var form_data = {
usernm: $("#username").val(),
passwd: $("#password").val(),
is_ajax: 1
};
$.ajax({
type:"application/x-www-form-urlencoded",
url: "myurl.php" ,
data: form_data,
success: function (response)
{
if (response == 'success'){
window.location="myurl.html";
}
else{
alert("wrong username password combination")
}
}
});
return false;
});
});
Or, if you are not sure about the correct MIME type, then just use this jQuery command:
$(document).ready(function(){
$("#submit").click(function(){
var form_data = {
usernm: $("#username").val(),
passwd: $("#password").val(),
is_ajax: 1
};
$.post("myurl.php",
form_data,
function (response)
{
if (response == 'success'){
window.location="myurl.html";
}
else{
alert("wrong username password combination")
}
});
return false;
});
});
And please change also the following lines of your PHP code
$uName = $_REQUEST ['username'];
$pWord = $_REQUEST ['password'];
To this:
$uName = $_REQUEST ['usernm'];
$pWord = $_REQUEST ['passwd'];
Because these are the correct keys, wich you send to your php server file. Also, thereĀ“s no need for defining an "is_ajax" key, because every XMLHttpRequest has set the "X_REQUESTED_WITH" header to "XMLHttpRequest". So, you can request it in your php server part e. g. with:
if (strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest')
{
// it was an ajax XHR request!
}
Related
php ajax auto login works well in form action, but is it possible to execute without form action?
$email = 'xxx#gmail.com';
$password = 'password';
<script>
var user = <?php $email; ?>;
var pass = <?php $password; ?>;
console.log(email=' + user + ', password=' + pass);
$.ajax({
url: 'http://www.example.com/login',
type: 'POST',
data: JSON.stringify({ email: user, password: pass }),
success: function(data, status) {
// do something after login
console.log('success');
},
error: function() {
console.log('error');
}
});
return false;
</script>
You should use GET method instead.
$email = 'xxx#gmail.com';
$password = 'password';
<script>
var user = <?php $email; ?>;
var pass = <?php $password; ?>;
$.ajax({
url: 'http://www.example.com/login',
type: 'GET', //send it through get method
data: {
email: user,
password: pass
},
success: function(response) {
//Do Something
},
error: function(xhr) {
//Do Something to handle error
}
});
</script>
Then check in your login page if email and password parameters have been set by GET or POST methods.
<?php
if (isset($_GET['email']) && isset($_GET['password']) || isset($_POST['email']) && isset($_POST['password'])){
// check your database and take actions.
}else{
// do nothing and show the post from again.
}
?>
Following code may work on page load if the username and password is auto-filled.
I hope this may help you.
<script>
$(document).ready(function(){
var user = $('[name="username"]').val();
var pass = $('[name="password"]').val();
if(user !== '' && pass!== ''){
$.ajax({
url: 'http://www.YourUrl.com/login',
type: 'POST',
data: {
email: user,
password: pass
},
success: function(response) {
//When successfully logged in
},
error: function() {
//If error on server side script
}
});
}
});
As here we have created POST request, you need to handle is by $_POST server side.
I'm to trying make a login using AJAX. AJAX function post data to PHP file but when I try to retrieve data from POST in PHP it's empty.
This is my AJAX posting code:
function validateUser() {
var userR = $("#fldUser").val();
var passwordR = $("#fldPassword").val();
if (userR.length < 1) {
$("#divStatusText").html("<p class=\"text-danger\"> <b>A user is required.</b></p>");
} else if (passwordR.length < 1) {
$("#divStatusText").html("<p class=\"text-danger\"><b>A password is required.</b></p>");
} else {
// alert(userR + passwordR)
$.ajax({
type: 'POST',
// url: '/_Controlador/_GSystemLogIn.php/',
url: '/_Controlador/_GSystemLogIn.php',
// data:'user=' + userR +'&password=' + passwordR,
data: {
'user': userR,
'password': passwordR
},
dataType: 'JSON',
beforeSend: function(xhr) {
alert("En before send: " + userR + passwordR);
},
success: function(data) {
alert(data);
if (data.message === "Success") {
// location.href = "main.php";
} else {
$("#divStatusText").html("<p class=\"text-danger\"><b>User or password is incorrect.</b></p>");
$("#fldUser").val("");
$("#fldPassword").val("");
}
},
error: function(data) {
alert("Error in AJAX call.");
}
});
}
}
PHP code retrieving data:
var_dump($_POST);
$user = $_POST['user'];
$password = $_POST['password'];
echo( "PHP user received: ". $user);
echo( "PHP pass received: ".$password);
Alert in AJAX beforeSend prints data correctly but var_dump($_POST) prints:
array(0) { }
I've also tried different ways to send data and URL. I'll really appreciate your help. Thank you!
You have to decode the data first.
Just do -
$_POST = json_decode(file_get_contents('php://input'), true);
Here's the full explanation - https://stackoverflow.com/a/39508364/5400741
In your ajax request,
type: 'POST' has to be method: 'POST'
Look at here
My question is simple, I'm using AJAX and i want to redirect the user to another page if the user fill up the registration form properly, however if the user failed to match his/her password. i want to show an error message.
here is my PHP code:
if (isset($_POST['password']) && isset($_POST['retype_password']))
{
$password = $_POST['password'];
$retype_password = $_POST['retype_password'];
if(!empty($password) && !empty($retype_password))
{
if($password == $retype_password)
{
header("Location: anotherpage.php");
exit();
}
else
{
echo 'password does not match';
}
}
}
here is my ajax:
var frm = $('#frm_register');
frm.submit(function (e)
{
e.preventDefault();
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
$('#error').text(data);
}
});
return false;
});
The problem here is that it doesn't redirect to another page unless i refresh the page.
You can simply use javascript to redirect to the page like below:
if (isset($_POST['password']) && isset($_POST['retype_password']))
{
$password = $_POST['password'];
$retype_password = $_POST['retype_password'];
if(!empty($password) && !empty($retype_password))
{
if($password == $retype_password)
{
echo true;
}
else
{
echo 'password does not match';
}
}
}
And for redirecting, you can use:
var frm = $('#frm_register');
frm.submit(function (e)
{
e.preventDefault();
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
if(data === true) {
window.location = 'Your url path here';
} else {
$('#error').text(data);
}
}
});
return false;
});
Instead of header("Location: anotherpage.php"); just do echo '1' and in your AJAX call, if data['responseText'] == '1' than just do a document.location.href = 'anotherpage.php'
JavaScript does not work with header() as it is browser-based language whereas PHP communicates directly with the Server. The best solution would probably be to return an error flag and message json_encode()'d.
If you return 0 (error) then display a message.
If you return 1 (success) redirect with JavaScript to a URL passed by php. That way you will be able to easily change the new URL should anything change in the website.
JavaScript
var frm = $('#frm_register');
frm.submit(function (e)
{
e.preventDefault();
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
dataType: 'json',
data: frm.serialize(),
success: function (data) {
if (data.r == 0){
$('#error').text(data.m);
}
if (data.r == 1){
document.location.href = data.m;
}
}
});
return false;
});
PHP
if (isset($_POST['password']) && isset($_POST['retype_password']))
{
$password = $_POST['password'];
$retype_password = $_POST['retype_password'];
if(!empty($password) && !empty($retype_password))
{
if($password == $retype_password)
{
echo json_encode(array(
'r' => 1,
'm' => 'anotherpage.php'
));
exit();
}
else
{
echo json_encode(array(
'r' => 0,
'm' => 'Passwords do not match'
));
exit();
}
}
}
var frm = $('#frm_register');
frm.submit(function (e)
{
e.preventDefault();
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
if(data) {
winlow.location = data;
}
}
});
return false;
});
In your action page just echo the link where you wanna redirect if you want
I have an error where I can't proceed my login_process.php using ajax. I have stored all my files as a one folder. If I run my HTML log in page, the error is appeared. Below is my code. It is just a simple code. Before this, I have applied the similar code as below (except for login_process.php because I've put a few functions) as my homework. But when I've try to make it again, as i said, the browser, either in Chrome or Firefox, displays an error as I wrote in ajax below.
index.html(ajax part)
$(document).ready(function(){
$("#subBTN").click(function(){
var username = $("#username").val();
var password = $("#password").val();
var status = $("#statusAlert");
if(username === "" && password === ""){
status.html("<span>Username and password are both required!</span>");
}
else if(username === ""){
status.html("<span>What is your username?</span>");
}
else if(password === ""){
status.html("<span>What is your password?</span>");
}
else{
$.ajax({
url:'login_process.php',
type: 'post',
data: {"?admin_name=": username, "&admin_pass=": password},
dataType: 'html',
success: function(data){
//alert(data);
if(data.success){
status.html("<span>"+ data +"</span>");
}
else{
status.html("<span>error</span>");
return false;
}
}
});
}
});
});
login_process.php
<?php
session_start();
if($_POST):
$username = $_POST["username"];
$password = $_POST["password"];
if($username):
echo "Hi " . $username;
endif;
endif;
?>
You got a error in jQuery ajax call in passing data
You use :
data: {'admin_name':username, 'admin_pass': password},
instead of
data: {"?admin_name=": username, "&admin_pass=": password},
Or access in php code data to use:
$_POST['admin_name'] AND S_POST['admin_pass']
You should change this line of code
if(data.success){
status.html("<span>"+ data +"</span>");
}
else{
status.html("<span>error</span>");
return false;
}
To
if(data.Length > 0){
status.html("<span>"+ data +"</span>");
}
else{
status.html("<span>error</span>");
return false;
}
Ok so I'm trying to create a login form for an iOS application using Phonegap. In order to have users sign in, I need to work around the SOP. I've tried a number of tutorials and examples, and I can't get any of them to work. This is what I have right now, I could use some pointers:
<script type="text/javascript">
$(document).ready(function() {
$("#login").click(function() {
var action = $("#form1").attr('action');
var form_data = {
username: $("#username").val(),
password: $("#password").val(),
is_ajax: 1
};
$.ajax({
type: "POST",
url: action,
data: form_data,
success: function(response)
{
if(response == 'success')
$("#form1").slideUp('slow', function() {
$("#message").html("You have logged in successfully!");
});
else
$("#message").html("Invalid username and/or password.");
}
});
return false;
});
});
</script>
------------ on doLogin.php -----
<?php
$is_ajax = $_REQUEST['is_ajax'];
if(isset($is_ajax) && $is_ajax)
{
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
if($username == 'demo' && $password == 'demo')
{
echo "success";
}
}
?>
First thought: your code is less error prone when using curly braces for your conditionals
if(response == 'success')
$("#form1").slideUp('slow', function() {
$("#message").html("You have logged in successfully!");
});
else
$("#message").html("Invalid username and/or password.");
could be
if(response == 'success') {
$("#form1").slideUp('slow', function() {
$("#message").html("You have logged in successfully!");
});
} else {
$("#message").html("Invalid username and/or password.");
}
A user here explains why this helps: https://stackoverflow.com/a/2125078/680578