When the login button is pressed the form data is posted to the slim route url using ajax post method which is supposed to pass the data so that it can be retrieved by the framework,the data is passes to the check login function which checks that credentials entered and if it matches whats stored in the db returns true, and this response redirects to the homepage (projects.php). When i click the button nothing happens, the web application responds to debug output right up to the ajax post statement but from then on all other test output doesnt show up.
Slim index.php
<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
require 'vendor/autoload.php';
include 'lib.php';
$config = [
'settings' => [
'displayErrorDetails' => true,
]
];
// Create app
$app = new \Slim\App($config);
// Get container
$container = $app->getContainer();
// Register component on container
$container['view'] = function ($container) {
return new \Slim\Views\PhpRenderer('templates/');
};
$app->get('/', function (Request $request, Response $response) {
return $this->view->render($response, "/login.php");
});
$app->get('/guest', function (Request $request, Response $response) {
return $this->view->render($response, "/projects.php");
});
$app->get('/projects', function (Request $request, Response $response) {
return $this->view->render($response, "/projects.php");
});
$app->post("/login", function(Request $request, Response $response)use($app){
$post = $request->getParsedBody();
$email = $post['email'];
$password = $post['password'];
$res = checkLogin($email, $password);
if ($res===true){
$response = $response->withStatus(201);
$response = $response->withJson(array("status"=> true));
} else{
$response = $response->withJson(400);
}
return $response;
});
// Run app
$app->run();
lib.php :
<?php
if(!session_id()) session_start();//If session is not started start session
function getDBConnection(){
try{
$db = new mysqli("localhost","web_project","admin","web_project");
if ($db == null && $db->connect_errno > 0)return null;
return $db;
}catch(Exception $e){ }
return null;
}
function checkLogin($email, $password){
$password = sha1($password);
$sql = "SELECT * FROM `user` where `email`='$email'";
echo($email);
$db = getDBConnection();
print_r($db);
if($db != NULL){
$res = $db->query($sql);
if ($res && $row = $res->fetch_assoc()){
if($row['password'] == $password){
$_SESSION["user"] = $row['fname'];
$_SESSION["id"] = $row['uid'];
return true;
}
}
$db->close();
}
return false;
}
main.js:
"use strict";
$(document).ready(function() {
$('#loginform').bootstrapValidator({
container: '#messages',
feedbackIcons: {
valid: 'glyphicon glyphicon-ok has-success',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
email: {
validators: {
notEmpty: {
message: 'Email is required and cannot be empty'
},
emailAddress: {
message: 'The email address is not valid'
}
}
},
password: {
validators: {
notEmpty: {
message: 'Password is required and cannot be empty'
}
}
}
}
});
$( "#btn-guest" ).click(function() {
window.location.href = 'index.php/guest';
});
$( "#btn-login" ).click(function() {
login();
});
});
function login(){
//var email = document.forms["logForm"]["email"].value;
// var password = document.forms["logForm"]["password"].value;
var email = $("#email").val();
var password = $("#password").val();
var data= {
"email" : email,
"password": password
};
console.log(data);
$.post("index.php/login", data, function(response){
console.log("Response: "+response);
var obj = JSON.parse(response);
console.log(obj.status);
if(obj.status == true){
window.location.href = "index.php/projects";
}else{
window.location.href = "/";
}
return false;
});
}
html page with form:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Login</title>
<!-- Bootstrap core CSS -->
<link href="bower_components/bootstrap/dist/css/bootstrap.css" rel="stylesheet">
<link href="css/ie10-viewport-bug-workaround.css" rel="stylesheet">
<link href="css/main.css" rel="stylesheet">
<script src="bower_components/sweetalert/dist/sweetalert.min.js"></script>
<link rel="stylesheet" type="text/css" href="bower_components/sweetalert/dist/sweetalert.css">
</head>
<body id="login_page">
<div id="header">
</div>
<?php if(isset($_SESSION["user"])){unset($_SESSION['user']);} ?>
<div class="container">
<div id="loginbox" style="margin-top:100px;" class="mainbox col-md-6 col-md-offset-3 col-sm-8 col-sm-offset-2">
<div class="panel panel-default" id="panel-default">
<div class="panel-heading" id="panel-heading">
<div class="panel-title">Sign In</div>
<div style="float:right; font-size: 80%; position: relative; top:-10px">Forgot password?</div>
</div>
<div style="padding-top:30px" class="panel-body" >
<div style="display:none" id="login-alert" class="alert alert-danger col-sm-12"></div>
<form id="loginform" enctype="multipart/form-data" name="logForm" class="form-horizontal" role="form" method="POST">
<div style="margin-bottom: 25px" class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input id="email" type="text" class="form-control" name="email" value="" placeholder="Email" >
</div>
<div style="margin-bottom: 25px" class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>
<input id="password" type="password" class="form-control" name="password" placeholder="Password">
</div>
<!-- #messages is where the messages are placed inside -->
<div class="form-group">
<div class="col-md-9 col-md-offset-3">
<div id="messages"></div>
</div>
</div>
<div style="margin-top:10px" class="form-group">
<!-- Button -->
<div class="col-sm-12 controls">
<button type="button" id="btn-login" class="btn btn-info" value="Login">Login</button>
</div>
</div>
<div style="margin-top:10px" class="form-group">
<!-- Button -->
<div class="col-sm-12 controls">
<button type="button" id="btn-guest" class="btn btn-info" value="SignUp">Sign in as Guest</button>
</div>
</div>
<footer class="navbar navbar-fixed-bottom" id="footer">
</footer>
<script src="js/ie10-viewport-bug-workaround.js"></script>
<script src="bower_components/jquery/dist/jquery.js"></script>
<script src="bower_components/bootstrap/dist/js/bootstrap.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery.bootstrapvalidator/0.5.3/js/bootstrapValidator.js"></script>
<script src="js/main.js"></script>
</body>
</html>
Related
I would like to write a communicate during registration, when user already exists. With this code it redirects me on another page. I would like to see this communicate under form. I tried like this but it still redirects me on another page. I also would like to do by function 'response', but it didn't work.
register3.php
<html>
<?php
if (isset($_POST["register"])) {
$connection = new mysqli("localhost", "root", "root", "users");
$email = $connection->real_escape_string($_POST["email"]);
$password = sha1($connection->real_escape_string($_POST["password"]));
$imie = $connection->real_escape_string($_POST["imie"]);
$nazwisko = $connection->real_escape_string($_POST["nazwisko"]);
$data2 = $connection->query("SELECT * FROM user WHERE email='$email'");
if($data2->num_rows >0) {
exit('<font color="red">This user already exists</font>');
} else
$data = $connection->query("INSERT INTO user
(email, password, imie, nazwisko)
VALUES ('$email', '$password', '$imie', '$nazwisko')");
if (($data === false) && ($email != "" || $password != "")) {
echo '<script>alert("Wypełnij poprawnie pola!")</script>';
} else {
echo '<script>alert("Zostałeś zarejestrowany, zaloguj się.")</script>';
}
}
?>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="UTF-16">
<link rel="stylesheet" href="style_reg.css">
<title>Strona o nalewkach - Login </title>
</head>
<body>
<nav class="navbar">
<div class="content">
<div class="logo" >Nalewki z tradycją</div>
<ul class="menu-list">
<div class="icon cancel-btn">
<i class="fas fa-times"></i>
</div>
<li>Home</li>
<li>Przepisy na nalewki</li>
<li>Logowanie</li>
<li>Galeria</li>
<li>Kontakt</li>
</ul>
<div class="icon menu-btn">
<i class="fas fa-bars"></i>
</div>
</div>
</nav>
<div class="limiter">
<div class="container-login100">
<div class="wrap-login100 p-l-55 p-r-55 p-t-65 p-b-50">
<form class="login100-form validate-form" method="POST" action="register3.php">
<span class="login100-form-title p-b-33">
Zarejestruj się do świata nalewek
</span>
<div class="wrap-input100 validate-input" data-validate = "Valid email is required: ex#abc.xyz">
<input class="input100" type="text" name="email" placeholder="Email">
<span class="focus-input100-1"></span>
<span class="focus-input100-2"></span>
</div>
<div class="wrap-input100 rs1 validate-input" data-validate="Password is required">
<input class="input100" type="password" name="password" placeholder="Haslo">
<span class="focus-input100-1"></span>
<span class="focus-input100-2"></span>
</div>
<div class="wrap-input100 rs1 validate-input" data-validate="Password is required">
<input class="input100" type="text" name="imie" placeholder="Imie">
<span class="focus-input100-1"></span>
<span class="focus-input100-2"></span>
</div>
<div class="wrap-input100 rs1 validate-input" data-validate="Password is required">
<input class="input100" type="text" name="nazwisko" placeholder="nazwisko">
<span class="focus-input100-1"></span>
<span class="focus-input100-2"></span>
</div>
<div class="container-login100-form-btn m-t-20">
<input type="submit" class="login100-form-btn" value="Zarejestruj" name="register">
</div>
<p id="response"></p>
</div>
</form>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#login").on('click', function () {
var email = $("#email").val();
var password = $("#password").val();
if (email == "" || password == "")
alert('Wypelnij poprawnie formularz');
else {
$.ajax({
url: 'register3.php',
method: 'POST',
data: {
login: 1,
emailPHP: email,
passwordPHP: password,
imiePHP: imie,
nazwiskoPHP: nazwisko
},
success: function(response) {
$("#response").html(response);
if (response.indexOf('success') >=0)
alert('Wypelnij poprawnie formularz');
},
dataType: 'text'
}
);
}
});
});
</script>
</body>
</html>
You use jQuery but you never import it, put this in hour head section
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
In your javascript you have this
$("#login").on('click', function () {
but I don't see any element with id login. To prevent form submition just jsut replace the above line with this
$("form").on('submit', function (e) {
e.preventDefault();
Give each of your form inputs an id, they don't have them now, so as to be able to do that
var email = $("#email").val();
var password = $("#password").val();
var imie = $("#imie").val();
var nazwisko = $("#nazwisko").val();
Prepare separate php file for your ajax call, can't use same register3.php for that, because php file has to be executed to give you a response, you cannot do that on register3.php without page reload.
In that other php file, for example email-check.php, check if user exists and if not register and return response ok
$.ajax({
url: 'email-check.php',
method: 'POST',
data: {
login: 1,
emailPHP: email,
passwordPHP: password,
imiePHP: imie,
nazwiskoPHP: nazwisko
},
success: function(response) {
if (response == 'ok') {
//new user registered succesfully
//log user in or redirect to login page
} else {
//user already exists
$("#response").html('This email address is taken');
},
});
After inserting data into the database through jQuery/ajax, while fetching values from database without refresh the page how to display the database values using codeigniter?
This is my code:
Script:
<script>
$(document).ready(function(){
$("#personal-info").submit(function(e){
e.preventDefault();
var suppid = $("#suppid").val();
var proid = $("#proid").val();
var custid = $("#custid").val();
var message = $("#message").val();
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>index.php/Profile_cntrl/buyer_communication",
data: {suppid:suppid,proid:proid,custid:custid,message:message},
success:function(data)
{
alert('SUCCESS!!');
},
error:function()
{
alert('fail');
}
});
});
});
</script>
Controller:
public function buyer_communication() {
$result1 = $this->Profile_model->fetch_Data($product_id);
$Userid = $this->session->userdata('id');
$result3 = $this->session->userdata('tt');
$data4 = array(
'message' => $this->input->post('message'),
'supplier_id' => $this->input->post('suppid'),
'product_id' => $this->input->post('proid'),
'Customer_id' => $this->input->post('custid'),
'From' => $result3,
);
$this->Profile_model->buyer_insert($data4);
redirect('welcome/buyermessageview?id=' . $product_id);
}
Model:
function buyer_insert($data4) {
$this->db->insert('communication', $data4);
return ($this->db->affected_rows() != 1) ? false : true;
}
Form:
<form class="form-horizontal" method="POST" id="personal-info" role="form" action="#">
<div class="panel-footer">
<div class="input-group">
<input type ="hidden" name="suppid" id="suppid" value="<?php echo $row->supplier_id; ?>" class="form-control" />
<input type ="hidden" name="proid" id="proid" value="<?php echo $row->product_id; ?>" class="form-control" />
<input type ="hidden" name="custid" id="custid" value="<?php echo $row->Customer_id; ?>" class="form-control" />
<input id="message" name="message" type="text" class="form-control input-sm chat_input" placeholder="Write your message here..." />
<span class="input-group-btn">
<button class="btn btn-primary btn-sm" id="submit-p" name="submit-p">Send</button>
<!--<input type="submit" name="submit-p" id="submit-p" value="send" class="btn btn-primary btn-sm" >-->
</span>
</div>
</div>
</form>
#Maruthi Prasad here is the code.. [IN CODE IGNITER]
HTML view code with jquery script
views\profile_view.php
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-6">
<div id="load_data">
</div>
<form method="post" id="personal-info">
<input id="message" name="message" type="text" class="form-control input-sm chat_input" placeholder="Write your message here..." />
<button type="submit" class="btn btn-primary btn-sm" id="submit-p" name="submit-p">Send</button>
</form>
</div>
</div>
</div>
<script>
$(document).ready(function(){
loaddata();
data_submit();
});
function loaddata(){
$.getJSON('<?php echo base_url();?>'+'index.php/Profile_cntrl/get_data',function(data){
for(var i in data){
var show = '<div>';
show += '<h5 style="background:#ccc;padding:10px;border-radius:10px;">'+data[i].message+'</h5>';
show += '</div>';
$("#load_data").append(show);
}
});
}
function data_submit(){
$("#personal-info").submit(function(e){
e.preventDefault();
var formdata = $(this).serialize();
$.ajax({
type:'POST',
url:'<?php echo base_url();?>'+'index.php/Profile_cntrl/insert_data',
data:formdata,
success:function(data){
var res = JSON.parse(data);
if(res.Status == 'true'){
//console.log(res.report);
$("#load_data").empty();
loaddata()
}else{
alert(res.report);
}
}
});
});
}
</script>
</body>
</html>
CONTROLLER CODE:
controllers\Profile_cntrl.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
header('Access-Control-Allow-Origin: *');
class Profile_cntrl extends CI_Controller {
function __construct(){
parent::__construct();
$this->load->model('profile_model');
$this->load->helper(array('url','html','form'));
}
public function index()
{
$this->load->view('profile_view');
}
public function get_data(){
$query = $this->profile_model->buyer_communication();
echo json_encode($query);
}
public function insert_data(){
$arr = array(
'message'=>$this->input->post('message')
);
$sql = $this->profile_model->buyer_insert($arr);
$op = "data insert id :".$this->db->insert_id();
if($sql == true){
$reponse = array(
'Status'=>'true',
'report'=>$op
);
echo json_encode($reponse);
}
else
{
$op = "Failed to insert data";
$reponse = array(
'Status'=>'false',
'report'=>$op
);
echo json_encode($reponse);
}
}
}
?>
Model code:
models\Profile_model.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Profile_model extends CI_model {
public function buyer_communication(){
$sql = $this->db->get('communication');
$sql = $sql->result_array();
return $sql;
}
public function buyer_insert($arr){
return $query = $this->db->insert('communication',$arr);
}
}
?>
Feel free to ask questions
I've tried to added remote method to check display name if is has already exists.
Email validation can check and display messages if email has already exists but Display name validation it does not work. What's wrong with my code?
My code
register.php
<?php require_once 'config.php'; ?>
<?php
if(!empty($_POST)){
try {
$user_obj = new Cl_User();
$data = $user_obj->registration( $_POST );
if($data)$success = USER_REGISTRATION_SUCCESS;
} catch (Exception $e) {
$error = $e->getMessage();
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Smart Registration Form</title>
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/font-awesome.min.css" rel="stylesheet">
<link href="css/login.css" rel="stylesheet">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="js/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="login-form">
<?php require_once 'templates/message.php';?>
<h1 class="text-center">Smart Tutorials</h1>
<div class="form-header">
<i class="fa fa-user"></i>
</div>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" class="form-register" role="form" id="register-form">
<div>
<input name="name" id="name" type="text" class="form-control" placeholder="Dispaly Name">
<span class="help-block"></span>
</div>
<div>
<input name="email" id="email" type="email" class="form-control" placeholder="Email address" >
<span class="help-block"></span>
</div>
<div>
<input name="password" id="password" type="password" class="form-control" placeholder="Password">
<span class="help-block"></span>
</div>
<div>
<input name="confirm_password" id="confirm_password" type="password" class="form-control" placeholder="Confirm Password">
<span class="help-block"></span>
</div>
<button class="btn btn-block bt-login" type="submit" id="submit_btn" data-loading-text="Signing Up....">Sign Up</button>
</form>
<div class="form-footer">
<div class="row">
<div class="col-xs-6 col-sm-6 col-md-6">
<i class="fa fa-lock"></i>
Forgot password?
</div>
<div class="col-xs-6 col-sm-6 col-md-6">
<i class="fa fa-check"></i>
Sign In
</div>
</div>
</div>
</div>
</div>
<!-- /container -->
<script src="js/jquery.validate.min.js"></script>
<script src="js/register.js"></script>
</body>
</html>
register.js
$(document).ready(function(){
$("#register-form").validate({
submitHandler : function(form) {
$('#submit_btn').attr('disabled','disabled');
$('#submit_btn').button('loading');
form.submit();
},
rules : {
name : {
required : true,
name: true,
remote: {
url: "check-name.php",
type: "post",
data: {
name: function() {
return $( "#name" ).val();
}
}
}
},
email : {
required : true,
email: true,
remote: {
url: "check-email.php",
type: "post",
data: {
email: function() {
return $( "#email" ).val();
}
}
}
},
password : {
required : true
},
confirm_password : {
required : true,
equalTo: "#password"
}
},
messages : {
name : {
required : "Please enter name",
remote : "Diaplay name already exists"
},
email : {
required : "Please enter email",
remote : "Email already exists"
},
password : {
required : "Please enter password"
},
confirm_password : {
required : "Please enter confirm password",
equalTo: "Password and confirm password doesn't match"
}
},
errorPlacement : function(error, element) {
$(element).closest('div').find('.help-block').html(error.html());
},
highlight : function(element) {
$(element).closest('div').removeClass('has-success').addClass('has-error');
},
unhighlight: function(element, errorClass, validClass) {
$(element).closest('div').removeClass('has-error').addClass('has-success');
$(element).closest('div').find('.help-block').html('');
}
});
});
check-name.php
<?php
require_once 'config.php';
$db = new Cl_DBclass();
if( isset( $_POST['name'] ) && !empty($_POST['name'])){
$name = $_POST['name'];
$query = " SELECT count(name) cnt FROM users where name = '$name' ";
$result = mysqli_query($db->con, $query);
$data = mysqli_fetch_assoc($result);
if($data['cnt'] > 0){
echo 'false';
}else{
echo 'true';
}
exit;
}
?>
EDIT
check-email.php
<?php
require_once 'config.php';
$db = new Cl_DBclass();
if( isset( $_POST['password'] ) && !empty($_POST['password'])){
$password =md5( trim( $_POST['password'] ) );
$email = $_POST['email'];
if( !empty( $email) && !empty($password) ){
$query = " SELECT count(email) cnt FROM users where password = '$password' and email = '$email' ";
$result = mysqli_query($db->con, $query);
$data = mysqli_fetch_assoc($result);
if($data['cnt'] == 1){
echo 'true';
}else{
echo 'false';
}
}else{
echo 'false';
}
exit;
}
if( isset( $_POST['email'] ) && !empty($_POST['email'])){
$email = $_POST['email'];
$query = " SELECT count(email) cnt FROM users where email = '$email' ";
$result = mysqli_query($db->con, $query);
$data = mysqli_fetch_assoc($result);
if($data['cnt'] > 0){
echo 'false';
}else{
echo 'true';
}
exit;
}
?>
I am trying to call a function with arguments from another class. The class with the function I need to call is auth.class.php (it's pretty long so I've shorten to the relevant class). I've a index.php file with jQuery form that when post calls reg.php and sends data their. I want to call the register function in auth.class.php file from the reg.php
I am not sure what I am doing wrong, I think the ajax might be the problem but any help will be appreciated.
auth.class.php
<?php
class Auth {
public function register($email, $username, $password, $repeatpassword)
{
$return = array();
$return['code'] = 400;
if ($this->isBlocked()) {
$return['code'] = 0;
return $return;
} else {
$validateEmail = $this->validateEmail($email);
$validateUsername = $this->validateUsername($username);
$validatePassword = $this->validatePassword($password);
if ($validateEmail['error'] == 1) {
$return['message'] = $validateEmail['message'];
return $return;
} elseif ($validateUsername['error'] == 1) {
$return['message'] = $validateUsername['message'];
return $return;
} elseif ($validatePassword['error'] == 1) {
$return['message'] = $validatePassword['message'];
return $return;
} elseif($password !== $repeatpassword) {
$return['message'] = "password_nomatch";
return $return;
} else {
if (!$this->isEmailTaken($email)) {
if (!$this->isUsernameTaken($username)) {
$addUser = $this->addUser($email, $username, $password);
if($addUser['error'] == 0) {
$return['code'] = 200;
$return['message'] = "register_success";
return $return;
} else {
$return['message'] = $addUser['message'];
return $return;
}
} else {
$this->addAttempt();
$this->addNewLog("", "REGISTER_FAIL_USERNAME", "User attempted to register new account with the username : {$username} -> Username already in use");
$return['message'] = "username_taken";
return $return;
}
} else {
$this->addAttempt();
$this->addNewLog("", "REGISTER_FAIL_EMAIL", "User attempted to register new account with the email : {$email} -> Email already in use");
$return['message'] = "email_taken";
return $return;
}
}
}
}
}
This is my html file index.php I am using jQuery mobile with ajax
<!DOCTYPE html>
<html>
<head>
<title>
Submit a form via AJAX
</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0a4/jquery.mobile-1.0a4.min.css" />
<script src="http://code.jquery.com/jquery-1.5.2.min.js">
</script>
<script src="http://code.jquery.com/mobile/1.0a4/jquery.mobile-1.0a4.min.js">
</script>
</head>
<body>
<script>
function onSuccess(data, status)
{
data = $.trim(data);
$("#notification").text(data);
}
function onError(data, status)
{
// handle an error
}
$(document).ready(function()
{
$("#submit").click(function()
{
var formData = $("#Register").serialize();
$.ajax(
{
type: "POST",
url: "reg.php",
cache: false,
data: formData,
success: onSuccess,
error: onError
});
return false;
});
});
</script>
<!-- call ajax page -->
<div data-role="page" id="callAjaxPage">
<div data-role="header">
<h1>
Call Ajax
</h1>
</div>
<div data-role="content">
<form id="Register">
<div data-role="fieldcontain">
<label for="Email">
eMail
</label>
<input type="email" name="email" id="email" value="" />
<br />
<label for="UserName">
User Name
</label>
<input type="text" name="username" id="username" value="" />
<br />
<label for="Password">
Password
</label>
<input type="password" name="password" id="password" value="" />
<br />
<label for="Confirmpassword">
Confirm Password
</label>
<input type="password" name="repeatpassword" id="repeatpassword" value="" />
<h3 id="notification">
</h3>
<button data-theme="b" id="submit" type="submit">
Submit
</button>
</div>
</form>
</div>
<div data-role="footer">
<h1>
GiantFlyingSaucer
</h1>
</div>
</div>
</body>
</html>
This is my the php file that's placing the call the auth.class.php function.
<?php
include_once "password.php";
require_once "auth.class.php";
$mail = $_POST[email];
$usn = $_POST[username];
$pswd = $_POST[password];
$cpswd = $_POST[repeatpassword];
$register = new Auth();
$register ->register($mail, $usn, $pswd, $cpswd);
echo $return;
?>
Make index.php all the code is here and ajax function also here and make calls.php which is call by ajax function and calls.php file call your class.auth.php file.
you didn't assign the value returned by your function to anything.
Try this:
$return= $register ->register($mail, $usn, $pswd, $cpswd);
echo $return;
Here's the updated code that fixed the problem. I wasn't passing the data as an array serializeArray and also made some changes in the reg.php class as well.
New index.php file
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery Mobile: Theme Download</title>
<link rel="stylesheet" href="themes/Carelincs.min.css" />
<link rel="stylesheet" href="themes/jquery.mobile.icons.min.css" />
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.3/jquery.mobile.structure-1.4.3.min.css" />
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.3/jquery.mobile-1.4.3.min.js"></script>
</head>
<body>
<script>
$(document).ready(function()
{
$("#submit").click(function()
{
var formData = $("#register").serializeArray();
$.ajax(
{
type: "POST",
url: "../pages/register.php",
cache: false,
data: formData,
success: onSuccess,
});
return false;
});
});
function onSuccess(data, status)
{
data = $.trim(data);
$("#message").text(data);
}
function onError(data, status)
{
//Handle error
}
</script>
<div data-role="page" data-theme="a">
<div data-role="header" data-position="inline">
<h1>Header</h1>
</div>
<div data-role="content" data-theme="a">
<form action="" method="POST" id="register">
<label for="email">Email:</label>
<input type="email" name="email" placeholder="eMail"/>
<br />
<label for="username">Username:</label>
<input type="text" name="username" placeholder="User Name"/>
<br />
<label for="password">Password:</label>
<input type="password" name="password" placeholder="Password"/>
<br />
<label for="confirm password">Confirm Password</label>
<input type="password" name="repeatpassword" placeholder="Confirm Password"/>
<br />
<button type="submit" id="submit">Submit</button>
</form>
<p id="message"></p>
</div>
</div>
</body>
</html>
new reg.php file I also added information to connect to database.
<?php
require_once("../auth/config.class.php");
require_once("../auth/auth.class.php");
$config = new Config;
$dbh = new PDO("mysql:host=" . $config-> dbhost . ";dbname=" . $config->dbname, $config->dbuser, $config->dbpass);
$auth = new Auth($dbh, $config);
$email = $_POST["email"];
$username = $_POST["username"];
$password = $_POST["password"];
$repeatpassword = $_POST["repeatpassword"];
$register = $auth->register($email, $username, $password, $repeatpassword );
// Temporary just to see what's going on :
var_dump($register);
?>
I'm trying to create a login system for my jQuery mobile app but it's not doing anything after the login button is clicked. Right now I'm not using a db connection.
index.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<link href="jquery.mobile-1.1.0/jquery.mobile.theme-1.0.min.css" rel="stylesheet" type="text/css">
<link href="jquery.mobile-1.1.0/jquery.mobile.structure-1.1.0.min.css" rel="stylesheet" type="text/css">
<script src="jquery.mobile-1.1.0/jquery-1.7.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#loginform').submit(function(){
$('#output').html('Connecting...');
var postTo = 'http://www.hedonsoft.com/game/login.php';
$.post(postTo,{userLbl: $('[name=username]').val(), passwordLbl: $('[name=password]').val()}, function (data){
if(data.message){
$('#output').html(data.message);
}else{
$('#output').html("Could not connect");
}
}, 'json');
return false;
});
});
</script>
<script src="jquery.mobile-1.1.0/jquery.mobile-1.1.0.min.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="custom.css" />
</head>
<body>
<div data-role="page" id="mc_main">
<div data-role="header" id="header">
<h1>Main Menu</h1>
</div>
<div data-role="content">
<div data-role="collapsible" id="logindiv"><h2>Login</h2>
<form id="loginform" method="post">
<div data-role="fieldcontain">
<label for="user">Username:</label>
<input type="text" name="user" id="user" value="" />
</div>
<div data-role="fieldcontain">
<label for="pass">Password:</label>
<input name="pass" type="password" id="pass" value="">
</div>
<input type="submit" value="Login" data-icon="check" data-theme="a"/>
</form>
<div id="output"></div>
</div>
</div>
</body>
</html>
login.php
<?php
if(isset($_POST['username'] and isset($_POST['password'])) {
// do logic for logining in (usually query your db)
if ($_POST['username'] == 'test' and $_POST['password'] == 'test') {
$data['success'] = true;
$data['message'] = 'Login succesful';
} else {
$data['success'] = false;
$data['message'] = 'Login failed';
}
// return json
echo json_encode($data);
}
?>
I get 'Connecting...' in #output but that's it.
The login.php code has a syntax error on line 2. It should read:
if(isset($_POST['userLbl']) && isset($_POST['passwordLbl']))
Your input name for the user field is "user".
Change your javascript to look like this
$.post(postTo,{userLbl:$('[name=user]').val(), ...
Then your login.php should looke like this:
<?php
if(isset($_POST['userLbl'] and isset($_POST['passwordLbl'])) {
// do logic for logining in (usually query your db)
if ($_POST['userLbl'] == 'test' and $_POST['passwordLbl'] == 'test') {
$data['success'] = true;
$data['message'] = 'Login succesful';
} else {
$data['success'] = false;
$data['message'] = 'Login failed';
}
// return json
echo json_encode($data);
}
?>
Your server is returning an error 500. That's why it doesn't work!
You can check my fiddle if you want: http://jsfiddle.net/ooflorent/7cYae/