Html5 login button not responding when submit button is clicked - javascript

Html5 login button not responding when submit button is clicked. The below was built with remember me features but the button does nothing when clicked. Any help will be appreciated and below is the efforts so far. Thanks
<script src="jquery-1.9.1.js"></script>
<script>
$(function() {
if (localStorage.chkbx && localStorage.chkbx != '') {
$('#remember_me').attr('checked', 'checked');
$('#username').val(localStorage.usrname);
$('#pass').val(localStorage.pass);
} else {
$('#remember_me').removeAttr('checked');
$('#username').val('');
$('#pass').val('');
}
$('#remember_me').click(function() {
if ($('#remember_me').is(':checked')) {
// save username and password
localStorage.usrname = $('#username').val();
localStorage.pass = $('#pass').val();
localStorage.chkbx = $('#remember_me').val();
} else {
localStorage.usrname = '';
localStorage.pass = '';
localStorage.chkbx = '';
var userdata= "username="+username+"&pass="+pass+"&remember_me="+remember_me;
$("#loader").show();
$("#loader").fadeIn(400).html('<img src="loader.gif" align="absmiddle"> <span class="loading">Checking your details please be patient</span>');
$.ajax({
type:"post",
data:userdata,
url:"signin.php",
cache:false,
success:function(msg){
$("#loader").hide();
$('.error').fadeIn(200).html(msg);
}
});
}
});
});
</script>
<div class="container">
<form class="form-signin">
<h2 class="form-signin-heading">Please sign in</h2>
<input type="text" class="input-block-level" placeholder="username" id='username'>
<input type="password" class="input-block-level" placeholder="Password" id="pass">
<label class="checkbox">
<input type="checkbox" value="remember-me" id="remember_me"> Remember me
</label>
<button class="btn btn-large btn-primary" type="submit">Sign in</button>
</form>
</div>
<?php
require("db_pdo.php");
$username=strip_tags($_POST["username"]);
$pass=strip_tags($_POST["pass"]);
$remember_me=strip_tags($_POST["remember_me"]);
$statement = $db->prepare('
SELECT * FROM members
WHERE username = :username
AND password = :password AND remember_me = :remember_me
');
$statement->execute(array(
':usernameu' => $username,
':password' => $pass,
':remember_me' => 'remember_me'));
if ($row = $statement->fetch()) {
$user=$pid=htmlentities($row['fullname'], ENT_QUOTES, "UTF-8");
echo "Welcome Mr/Mrs <b>".$user."</b> <font color=pink>you are signed in successfully. <br>Redirecting in 2 seconds</font> <img src=loader.gif>";
echo '<script>
window.setTimeout(function() {
window.location.href = "welcome.html";
}, 2000);
</script>';
}else{
echo '<font color=red size=2><b>Either of your details is wrong. You are trying to use login accounts that belongs to another
person</b></font>';
}
?>

Related

How can I rewrite the HTML page to have the exact same fields?

I'm trying to make a new look for my website, but it looks like it doesn't want to login and I don't understand why.. Here's the original page:
<body class="jumbotron vertical-center" onload="redirect();">
<div class="container login-container">
<div class="row">
<div class="col-md-4 login-form mx-auto">
<h3>Login</h3>
<h6>Don't have an account? Register</h6>
<form>
<div class="error-message" id="errorMessage"></div>
<div class="form-group">
<input id="enterID" type="text" class="form-control" placeholder="Your User ID *" value="" required/>
</div>
<div class="form-group">
<input id="password" type="password" class="form-control" placeholder="Your Password *" value="" required/>
</div>
<div class="form-group">
<input class="btn btn-block btn-primary" value="Login" onclick="login();" readonly />
</div>
<div class="form-group">
Trouble logging in?
</div>
</form>
</div>
</div>
</div>
</body>
And here's the edited page:
<!-- To keep it in the center of page-->
<img class="wave" src="img/wave.png">
<div class="container_main">
<div class="img">
<img src="img/bg.svg">
</div>
<div class="login-content">
<form>
<img src="img/avatar.svg">
<h2 class="title">Quiz Website</h2>
<div class="input-div one">
<div class="i">
<i class="fas fa-user"></i>
</div>
<div class="div">
<input type="text" class="input" id="enterID" placeholder="Username">
</div>
</div>
<div class="input-div pass">
<div class="i">
<i class="fas fa-lock"></i>
</div>
<div class="div form-group">
<input id="password" type="password" class="form-control" placeholder="Password" value="" required/>
</div>
</div>
Don't have an account?
<div class="form-group">
Trouble logging in?
</div>
<input type="submit" class="btn" value="Login" onclick="login();" readonly >
<div class="error-message" id="errorMessage"></div>
</form>
</div>
</div>
</html>
What am I doing wrong? I don't want to use the body class jumbotron vertical-center cause it's making my website to look very awful.. I always get ,,XHR loading failed" and I don't understand why..
My checklogin.js file:
function login() {
var enterID = document.getElementById("enterID").value;
var password = document.getElementById("password").value;
if ((password != "") && (enterID != "")) {
var info = "?enterID=" + enterID + "&password=" + password;
$.ajax
({
type: "GET",
url: "php/login.php" + info,
success: function (respond) {
if (respond == "admin") {
window.location.href = "page/admin-system-management.php";
} else if (respond == "student") {
window.location.href = "page/student-dashboard.php";
} else if (respond == "teacher") {
window.location.href = "page/teacher-dashboard.php";
} else {
document.getElementById("errorMessage").innerText = respond;
}
}
});
}
else {
document.getElementById("errorMessage").innerText = "Please fill in all the fields.";
}
}
function redirect() {
$.ajax
({
type: "GET",
url: "php/redirect.php",
success: function (respond) {
if (respond != "not logged.") {
if (respond == "admin") {
window.location.href = "page/admin-system-management.php";
} else if (respond == "student") {
window.location.href = "page/student-dashboard.php";
} else if (respond == "teacher") {
window.location.href = "page/teacher-dashboard.php";
}
}
}
});
}
And my login.php file:
<?php
include "mysql-connect.php";
//get Info from login.html
$ID = $_GET['enterID'];
$PW = $_GET['password'];
$stmt = $connect->prepare("SELECT PW, userType, nickName FROM users WHERE ID = ?");
$stmt->bind_param("s",$ID);
$valid = $stmt->execute();
if (!$valid){
die("Could not successfully run query.". $connect->connect_error);
}
$result = $stmt->get_result();
if ($result->num_rows==0){
//display message of no such student/teacher/admin
echo "Failed to find an account with the input ID.";
} else {
$row = $result->fetch_assoc();
if (password_verify($PW, $row['PW'])) {
$type = $row['userType'];
$nick = $row['nickName'];
//var_dump($row['PW']);
//save data
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
$_SESSION["type"]=$type;
$_SESSION["userID"]=$ID;
$_SESSION["nickName"]=$nick;
//login success - Request.responseText to checklogin.js
echo $type;
} else {
//display message of password error
echo "The input password does not match the account password.";
}
}
$connect->close();
?>
And here's the redirect.php:
<?php
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
if (isset($_SESSION["type"])){
if ($_SESSION["type"] != $_SESSION["pageType"]){
$alert_message = "You cannot access this page using your account!";
$link = "../login.html";
echo "<script type='text/javascript'>alert('$alert_message'); window.setTimeout(function(){ if ('".$_SESSION["type"]."'=='admin'){ window.location.href = '../page/admin-system-management.php';} else if ('".$_SESSION["type"]."'=='student'){ window.location.href = '../page/student-dashboard.php';} else if ('".$_SESSION["type"]."'=='teacher'){ window.location.href = '../page/teacher-dashboard.php';} }, 0);</script>";
}
} else {
$alert_message = "Your login period has expired! Please login again!";
$link = "../login.html";
echo "<script type='text/javascript'>alert('$alert_message'); window.setTimeout(function(){ window.location.href = '$link'; }, 0);</script>";
}
?>

Undefined array key pageType when login, even if it's added to a page

I'm trying to log in and then redirect to a custom page, based on user type. My problem is that when I'm pressing the login button, on the console I get that that I have a Undefined array key pageType, and I don't understand why... If I'm for example on teacher page, I set $_SESSION['pageType'] = 'teacher';
This my login.html page:
<img class="wave" src="img/wave.png">
<div class="container_main" onsubmit="redirect();">
<div class="img">
<img src="img/bg.svg">
</div>
<div class="login-content">
<form onsubmit="redirect();">
<img src="img/avatar.svg">
<h2 class="title">Quiz Website</h2>
<div class="input-div one">
<div class="i">
<i class="fas fa-user"></i>
</div>
<div class="div">
<input type="text" class="input" id="enterID" placeholder="Username">
</div>
</div>
<div class="input-div pass">
<div class="i">
<i class="fas fa-lock"></i>
</div>
<div class="div form-group">
<input id="password" type="password" class="form-control" placeholder="Password" value="" required/>
</div>
</div>
Don't have an account?
<div class="form-group">
Trouble logging in?
</div>
<input type="submit" class="btn" value="Login" onclick="login();" readonly >
<div class="error-message" id="errorMessage"></div>
</form>
</div>
</div>
</html>
This is checklogin.js:
function login() {
var enterID = document.getElementById("enterID").value;
var password = document.getElementById("password").value;
if ((password != "") && (enterID != "")) {
var info = "?enterID=" + enterID + "&password=" + password;
$.ajax
({
type: "GET",
async: true,
url: "php/login.php" + info,
success: function (respond) {
if (respond == "admin") {
window.location.href = "page/admin-system-management.php";
} else if (respond == "student") {
window.location.href = "page/student-dashboard.php";
} else if (respond == "teacher") {
window.location.href = "page/teacher-dashboard.php";
} else {
document.getElementById("errorMessage").innerText = respond;
}
}
});
}
else {
document.getElementById("errorMessage").innerText = "Please fill in all the fields.";
}
}
function redirect() {
$.ajax
({
type: "GET",
async: true,
url: "php/redirect.php",
success: function (respond) {
if (respond != "not logged.") {
if (respond == "admin") {
window.location.href = "page/admin-system-management.php";
} else if (respond == "student") {
window.location.href = "page/student-dashboard.php";
} else if (respond == "teacher") {
window.location.href = "page/teacher-dashboard.php";
}
}
console.log(respond)
}
});
}
And this is my redirect.php file:
<?php
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
if (isset($_SESSION["type"])){
if ($_SESSION["type"] != $_SESSION["pageType"]){
$alert_message = "You cannot access this page using your account!";
$link = "../login.html";
echo "<script type='text/javascript'>alert('$alert_message'); window.setTimeout(function(){ if ('".$_SESSION["type"]."'=='admin'){ window.location.href = '../page/admin-system-management.php';} else if ('".$_SESSION["type"]."'=='student'){ window.location.href = '../page/student-dashboard.php';} else if ('".$_SESSION["type"]."'=='teacher'){ window.location.href = '../page/teacher-dashboard.php';} }, 0);</script>";
}
} else {
$alert_message = "Your login period has expired! Please login again!";
$link = "../login.html";
echo "<script type='text/javascript'>alert('$alert_message'); window.setTimeout(function(){ window.location.href = '$link'; }, 0);</script>";
}
?>
What I suspect is that the redirect() function it's not even loaded, so that's why I think I'm getting this error... Sometimes I'm seeing ,,XHR failed loading: GET"
I modified a code in order to have another login.html page, this is my old login.html code:
<body class="jumbotron vertical-center" onload="redirect();">
<div class="container login-container">
<div class="row">
<div class="col-md-4 login-form mx-auto">
<h3>Login</h3>
<h6>Don't have an account? Register</h6>
<form>
<div class="error-message" id="errorMessage"></div>
<div class="form-group">
<input id="enterID" type="text" class="form-control" placeholder="Your User ID *" value="" required/>
</div>
<div class="form-group">
<input id="password" type="password" class="form-control" placeholder="Your Password *" value="" required/>
</div>
<div class="form-group">
<input class="btn btn-block btn-primary" value="Login" onclick="login();" readonly />
</div>
<div class="form-group">
Trouble logging in?
</div>
</form>
</div>
</div>
</div>
</body>
Inside redirect() function add this line at the start.
This will stop the forms default action of redirecting/refreshing the page
event.preventDefault();
Then your redirect function / respond variable should work
If you return this from php it will be ignored by javascript
echo "<script type='text/javascript'>code here\</script>";
To make your redirect.php easier to debug output the data as a json encoded array instead of a string that way you can view/test more data.
inside redirect.php try add this code straight after the session_start() line just as a first test
$data = [
'session' => $_SESSION,
'response' => 'place your response here',
];
echo json_encode($data);
exit;
Ok here is the update i think you need.
redirect.php
<?php
if(!session_id()) {
session_start();
}
// you can change this line to this once you have debugged your code - $data = [];
$data = ['session' => $_SESSION];
// place code here to get the user type from the database
// then use $_SESSION['type'] = '{database response}';
if(!isset($_SESSION['type']))
{
$_SESSION['type'] = null;
}
switch($_SESSION['type']) {
case 'admin':
header('Location: /page/admin-system-management.php'); // this is the php way to redirect
break;
case 'student':
header('Location: /page/student-dashboard.php');
break;
case 'teacher':
header('Location: /page/teacher-dashboard.php');
break;
default:
$data['alert_message'] = 'Your login period has expired! Please login again!';
}
echo json_encode($data);
exit;
?>
Javascript redirect function
function redirect() {
$.ajax
({
type: "GET",
async: true,
url: "php/redirect.php",
success: function (response) {
console.log(response);
if(response.alert_message) {
alert(response.alert_message);
}
}
});
}

Ajax submitting form without refreshing page [duplicate]

This question already has answers here:
jQuery AJAX submit form
(20 answers)
Closed last year.
Can anyone tell me why this bit of code isn't working?
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$('form').bind('submit', function () {
$.ajax({
type: 'post',
url: 'post.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted');
}
});
return false;
});
});
</script>
</head>
<body>
<form>
<input name="time" value="00:00:00.00"><br>
<input name="date" value="0000-00-00"><br>
<input name="submit" type="button" value="Submit">
</form>
</body>
</html>
When I push submit nothing happens. In the receiving php file I'm using $_POST['time'] and $_POST['date'] to put the data in a mysql query but it's just not getting the data. Any suggestions? I'm assuming it's something to do with the submit button but I can't figure it out
The form is submitting after the ajax request.
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'post.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted');
}
});
});
});
</script>
</head>
<body>
<form>
<input name="time" value="00:00:00.00"><br>
<input name="date" value="0000-00-00"><br>
<input name="submit" type="submit" value="Submit">
</form>
</body>
</html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$('form').bind('click', function (event) {
// using this page stop being refreshing
event.preventDefault();
$.ajax({
type: 'POST',
url: 'post.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted');
}
});
});
});
</script>
</head>
<body>
<form>
<input name="time" value="00:00:00.00"><br>
<input name="date" value="0000-00-00"><br>
<input name="submit" type="submit" value="Submit">
</form>
</body>
</html>
PHP
<?php
if(isset($_POST["date"]) || isset($_POST["time"])) {
$time="";
$date="";
if(isset($_POST['time'])){$time=$_POST['time']}
if(isset($_POST['date'])){$date=$_POST['date']}
echo $time."<br>";
echo $date;
}
?>
JS Code
$("#submit").click(function() {
//get input field values
var name = $('#name').val();
var email = $('#email').val();
var message = $('#comment').val();
var flag = true;
/********validate all our form fields***********/
/* Name field validation */
if(name==""){
$('#name').css('border-color','red');
flag = false;
}
/* email field validation */
if(email==""){
$('#email').css('border-color','red');
flag = false;
}
/* message field validation */
if(message=="") {
$('#comment').css('border-color','red');
flag = false;
}
/********Validation end here ****/
/* If all are ok then we send ajax request to email_send.php *******/
if(flag)
{
$.ajax({
type: 'post',
url: "email_send.php",
dataType: 'json',
data: 'username='+name+'&useremail='+email+'&message='+message,
beforeSend: function() {
$('#submit').attr('disabled', true);
$('#submit').after('<span class="wait"> <img src="image/loading.gif" alt="" /></span>');
},
complete: function() {
$('#submit').attr('disabled', false);
$('.wait').remove();
},
success: function(data)
{
if(data.type == 'error')
{
output = '<div class="error">'+data.text+'</div>';
}else{
output = '<div class="success">'+data.text+'</div>';
$('input[type=text]').val('');
$('#contactform textarea').val('');
}
$("#result").hide().html(output).slideDown();
}
});
}
});
//reset previously set border colors and hide all message on .keyup()
$("#contactform input, #contactform textarea").keyup(function() {
$("#contactform input, #contactform textarea").css('border-color','');
$("#result").slideUp();
});
HTML Form
<div class="cover">
<div id="result"></div>
<div id="contactform">
<p class="contact"><label for="name">Name</label></p>
<input id="name" name="name" placeholder="Yourname" type="text">
<p class="contact"><label for="email">Email</label></p>
<input id="email" name="email" placeholder="admin#admin.com" type="text">
<p class="contact"><label for="comment">Your Message</label></p>
<textarea name="comment" id="comment" tabindex="4"></textarea> <br>
<input name="submit" id="submit" tabindex="5" value="Send Mail" type="submit" style="width:200px;">
</div>
PHP Code
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
//check if its an ajax request, exit if not
if (!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
//exit script outputting json data
$output = json_encode(
array(
'type' => 'error',
'text' => 'Request must come from Ajax'
));
die($output);
}
//check $_POST vars are set, exit if any missing
if (!isset($_POST["username"]) || !isset($_POST["useremail"]) || !isset($_POST["message"])) {
$output = json_encode(array('type' => 'error', 'text' => 'Input fields are empty!'));
die($output);
}
//Sanitize input data using PHP filter_var().
$username = filter_var(trim($_POST["username"]), FILTER_SANITIZE_STRING);
$useremail = filter_var(trim($_POST["useremail"]), FILTER_SANITIZE_EMAIL);
$message = filter_var(trim($_POST["message"]), FILTER_SANITIZE_STRING);
//additional php validation
if (strlen($username) < 4) { // If length is less than 4 it will throw an HTTP error.
$output = json_encode(array('type' => 'error', 'text' => 'Name is too short!'));
die($output);
}
if (!filter_var($useremail, FILTER_VALIDATE_EMAIL)) { //email validation
$output = json_encode(array('type' => 'error', 'text' => 'Please enter a valid email!'));
die($output);
}
if (strlen($message) < 5) { //check emtpy message
$output = json_encode(array('type' => 'error', 'text' => 'Too short message!'));
die($output);
}
$to = "info#wearecoders.net"; //Replace with recipient email address
//proceed with PHP email.
$headers = 'From: ' . $useremail . '' . "\r\n" .
'Reply-To: ' . $useremail . '' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$sentMail = #mail($to, $subject, $message . ' -' . $username, $headers);
//$sentMail = true;
if (!$sentMail) {
$output = json_encode(array('type' => 'error', 'text' => 'Could not send mail! Please contact administrator.'));
die($output);
} else {
$output = json_encode(array('type' => 'message', 'text' => 'Hi ' . $username . ' Thank you for your email'));
die($output);
}
This page has a simpler example
http://wearecoders.net/submit-form-without-page-refresh-with-php-and-ajax/
Here is a nice plugin for jQuery that submits forms via ajax:
http://malsup.com/jquery/form/
its as simple as:
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
$(document).ready(function() {
$('#myForm').ajaxForm(function() {
alert('form was submitted');
});
});
</script>
It uses the forms action for the post location.
Not that you can't achieve this with your own code but this plugin has worked very nicely for me!
JS Code
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/ libs/jquery/1.3.0/jquery.min.js">
</script>
<script type="text/javascript" >
$(function() {
$(".submit").click(function() {
var time = $("#time").val();
var date = $("#date").val();
var dataString = 'time='+ time + '&date=' + date;
if(time=='' || date=='')
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "post.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
</script>
HTML Form
<form>
<input id="time" value="00:00:00.00"><br>
<input id="date" value="0000-00-00"><br>
<input name="submit" type="button" value="Submit">
</form>
<span class="error" style="display:none"> Please Enter Valid Data</span>
<span class="success" style="display:none"> Form Submitted Success</span>
</div>
PHP Code
<?php
if($_POST)
{
$date=$_POST['date'];
$time=$_POST['time'];
mysql_query("SQL insert statement.......");
}else { }
?>
Taken From Here
type="button"
should be
type="submit"
In event handling, pass the object of event to the function and then add statement i.e.
event.preventDefault();
This will pass data to webpage without refreshing it.
$(document).ready(function(){
$('#userForm').on('submit', function(e){
e.preventDefault();
//I had an issue that the forms were submitted in geometrical progression after the next submit.
// This solved the problem.
e.stopImmediatePropagation();
// show that something is loading
$('#response').html("<b>Loading data...</b>");
// Call ajax for pass data to other place
$.ajax({
type: 'POST',
url: 'somephpfile.php',
data: $(this).serialize() // getting filed value in serialize form
})
.done(function(data){ // if getting done then call.
// show the response
$('#response').html(data);
})
.fail(function() { // if fail then getting message
// just in case posting your form failed
alert( "Posting failed." );
});
// to prevent refreshing the whole page page
return false;
});
<div class="container">
<div class="row">
<div class="col-md-3 col-sm-6 col-xs-12"></div>enter code here
<div class="col-md-6 col-sm-6 col-xs-12">
<div class="msg"></div>
<form method="post" class="frm" id="form1" onsubmit="">
<div class="form-group">
<input type="text" class="form-control" name="fname" id="fname" placeholder="enter your first neme" required>
<!--><span class="sp"><?php// echo $f_err;?></span><!-->
</div>
<div class="form-group">
<input type="text" class="form-control" name="lname" id="lname" placeholder="enter your last neme" required>
<!--><span class="sp"><?php// echo $l_err;?></span><!-->
</div>
<div class="form-group">
<input type="text" class="form-control" name="email" id="email" placeholder="enter your email Address" required>
<!--><span class="sp"><?php// echo $e_err;?></span><!-->
</div>
<div class="form-group">
<input type="number" class="form-control" name="mno" id="mno" placeholder="enter your mobile number" required>
<!--><span class="sp"><?php //echo $m_err;?></span><!-->
</div>
<div class="form-group">
<input type="password" class="form-control" name="pass" id="pass" pattern="(?=.*[a-z])(?=.*[A-Z]).{4,8}" placeholder="enter your Password" required>
<!--><span class="sp"><?php //echo $p_err;?></span><!-->
</div>
<div class="radio">
<input type="radio" value="male" name="gender" id="gender" checked>male<br>
<input type="radio" value="female" name="gender" id="gender">female<br>
<input type="radio" value="other" name="gender" id="gender">other<br>
<!--><span class="sp"> <?php //echo $r_err;?></span><!-->
</div>
<div class="checkbox">
<input type="checkbox" name="check" id="check" checked>I Agree Turms&Condition<br>
<!--><span class="sp"> <?php //echo $c_err;?></span><!-->
</div>
<input type="submit" class="btn btn-warning" name="submit" id="submit">
</form>enter code here
</div>
<div class="col-md-3 col-sm-6 col-xs-12"></div>
</div>
</div>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" >
$(function () {
$(".submit").click(function (event) {
var time = $("#time").val();
var date = $("#date").val();
var dataString = 'time=' + time + '&date=' + date;
console.log(dataString);
if (time == '' || date == '')
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
} else
{
$.ajax({
type: "POST",
url: "post.php",
data: dataString,
success: function (data) {
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
$("#data").html(data);
}
});
}
event.preventDefault();
});
});
</script>
<form action="post.php" method="POST">
<input id="time" value=""><br>
<input id="date" value=""><br>
<input name="submit" type="button" value="Submit" class="submit">
</form>
<div id="data"></div>
<span class="error" style="display:none"> Please Enter Valid Data</span>
<span class="success" style="display:none"> Form Submitted Success</span>
<?php
print_r($_POST);
if ($_POST['date']) {
$date = $_POST['date'];
$time = $_POST['time'];
echo '<h1>' . $date . '---' . $time . '</h1>';
}
else {
}
?>

I can see the posted data in the url but nothing happen

its been 2 days that im stuck with this error i can see the data that i post but the next page do not load
when i submit i get http://localhost:8000/android/www/login1.html?username=**********&password=****************&action=SignIn
thanks for ur help.
<script type="text/javascript">
$(document).ready(function() {
$('button[type=submit]').submit(function () {
var username = $('input[name=username]').val();
var password = $('input[name=password]').val();
$.ajax({
type: "POST",
url: "http://localhost/server1/login1.php",
data: $('#login').serialize(),
dataType: 'json',
success:function(json){
if(json.status === 'success') {
alert('Tout est bon');
window.location.href="TestPorteur.html";
}
else{
window.location.href="ResetPassword.html";
}
}
/* */
});
return false;
});
});
</script>
<div class="login-bottom" id="login">
<form id="form" >
<div class="text">
<input type="text" placeholder="Numéro Téléphone" id="username" name="username" />
<span class="men"></span>
<div class="clear"> </div>
</div>
<div class="text">
<input type="password" placeholder="Password..." id="password" name="password" />
<span class="pass"></span>
<div class="clear"> </div>
</div>
<div class="remember">
<div class="remember-top">
Mot de passe oublié?
</span>
</div>
<div class="send">
<button type="submit" id="action" name="action" value="SignIn">Sign In</button>
</div>
<div class="clear"> </div>
</div>
</form>
</div>
<?php
header('Access-Control-Allow-Origin: *');
include('conn.php');
if(isset($_POST["username"])&& isset($_POST["password"])){
$password = $_POST['password'];
$username = $_POST['username'];
echo"Veuillez remplir les champs";
}
$sql7="select * from utilisateur WHERE username='$username'";
$result=mysqli_query($conn, $sql7);
while($result1 = mysqli_fetch_array($result)){
$var=$result['password'];}
if($password!='$var'){
$status="passworderrone";
echo json_encode(['status' => $status]);
}
if($password=='$var'){
$vari='11';
function getRemoteIp(){
if( !ini_get('register_globals') ) {
return $_SERVER['REMOTE_ADDR'];
} else {
return #$REMOTE_ADDR;
}
return "";
}
$ip = getRemoteIp();
$sql2="select * from session WHERE username='$username'";
$usrname=mysqli_query($conn, $sql2);
while($result = mysqli_fetch_array($usrname)){
$vari=$result['username'];
}
if('$vari'==$username){
$status= "dejainscris";
echo json_encode(['status' => $status]);
$sql3 = "INSERT INTO session (username, tps_connx, tcpip)
VALUES ('$username',NOW(),'$ip')";
$res3=mysqli_query($conn, $sql3);
}
else {$status="premiereinscription";
echo json_encode(['status' => $status]);
}
}
?>
There are two things you can do to fix this.
Remove type=submit from button and in JS instead of catching submit event, you should catch click event.
<button id="action" name="action" value="SignIn">Sign In</button>
and in JS you should look for click event.
$('button#action').click(function () {
The reason for this type=submit directly submit the form. So first that needs to be checked, then look for click event and do your thing.
Second way to do this is that instead of catching submit event on button, look for submit event on form because it is meant for forms.
so your JS should
$('#form').submit(function (e) {
e.preventDefault();
...

Ajax form submit without page refresh

I simply want to submit my form to the same page with ajax without page refresh. So my below code submits the form but $_POST values are not picked ... Am I submitting it properly. I don't get any error but I think my form is not submitting.
html form
<form action="" id="fixeddonation" name="fixeddonation" method="post">
<input type="hidden" class="donerProject" name="donerProject" value="test">
<input type="hidden" class="donersubProject" id="donersubProject" name="donersubProject" value="general">
<input type="hidden" class="donerLocations" id="donerLocations" name="donerLocations" value="general">
<input type="hidden" class="donationpagetype" name="donationpagetype" value="general">
<input type="hidden" class="projectadded" id="projectadded" name="projectadded" value="1">
<input type="hidden" value="302" id="pageid" name="pageid">
<div class="classsetrepet generalfixshow fullrow row fixed-page">
<div class="col-6 text-right">
<div class="prize">Fixed Amount £</div>
</div>
<div class="col-6">
<input type="text" id="oneoffamt" name="oneoffamt" class="oneoffamt validatenumber">
<span class="amt_error"></span>
</div>
</div>
<br>
<div class="row">
<div class="col-6"></div>
<div class="col-6">
<input type="submit" id="submit_gen_one" class="btn-block" value="submit" name="submit_gen_one">
</div>
</div>
</form>
Ajax code
jQuery('#fixeddonation').on('submit', function (e) {
e.preventDefault();
jQuery.ajax({
type: 'post',
url: 'wp-admin/admin-ajax.php',
data: jQuery('#fixeddonation').serialize(),
success: function (data) {
alert(data);
alert('form was submitted');
jQuery('#collapse2').addClass('in').removeAttr('aria-expanded').removeAttr('style'); jQuery('#collapse1').removeClass('in').removeAttr('aria-expanded').removeAttr('style');
}
});
return false;
});
Add a correct value to the action tag of your form and try this:
<script>
$(document).ready(function() {
var form = $('#fixeddonation');
form.submit(function(ev) {
ev.preventDefault();
var formData = form.serialize();
$.ajax({
method: 'POST',
url: form.attr('action'),
data: formData
}) .done(function(data) {
alert(data);
});
});
}); // end .ready()
</script>
Don't need return false as you already called preventDefault() first thing
First create Template
<?php
/* Template Name: Test */
get_header();
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<div id="primary" class="content-area">
<main id="main" class="site-main">
<p class="register-message" style="display:none"></p>
<form action="#" method="POST" name="testregister" class="register-form">
<fieldset>
<label><i class="fa fa-file-text-o"></i> Register Form</label>
<input type="text" name="firstname" placeholder="Username" id="firstname">
<p id="firstname-error" style="display:none">Firstname Must Be Enter</p>
<input type="email" name="email" placeholder="Email address" id="email">
<p id="email-error" style="display:none">Email Must Be Enter</p>
<input type="submit" class="button" id="test" value="Register" >
</fieldset>
</form>
<script type="text/javascript">
jQuery('#test').on('click',function(e){
e.preventDefault();
var firstname = jQuery('#firstname').val();
var email = jQuery('#email').val();
if (firstname == "") {
jQuery('#firstname-error').show();
return false;
} else {
jQuery('#firstname-error').hide();
}
if (email == "") { jQuery('#email-error').show(); return false; }
else { jQuery('#email-error').hide(); }
jQuery.ajax({
type:"POST",
url:"<?php echo admin_url('admin-ajax.php'); ?>",
data: {
action: "test",
firstname : firstname,
email : email
},
success: function(results){
console.log(results);
jQuery('.register-message').text(results).show();
},
error: function(results) {
}
});
});
</script>
</main><!-- #main -->
</div><!-- #primary -->
after that create a function (function.php in wordpress)
add_action('wp_ajax_test', 'test', 0);
add_action('wp_ajax_nopriv_test', 'test');
function test() {
$firstname = stripcslashes($_POST['firstname']);
$email = stripcslashes($_POST['email']);
global $wpdb;
$q = $wpdb->prepare("SELECT * FROM wp_test WHERE email='".$email."' ");
$res = $wpdb->get_results($q);
if(count($res)>0)
{
echo "Email Allready Register ";
}
else
{
$user_data = array(
'firstname' => $firstname,
'email' => $email
);
$tablename = $wpdb->prefix.'test'; // if use wordpress
$user_id= $wpdb->insert( $tablename,$user_data );
echo 'we have Created an account for you';
die;
}
}

Categories

Resources