I have created a login page in Reactjs and I have a login_check code in PHP. Now I have to check if the user exists in the database and if exists I want to create a token otherwise no. I used jquery to post the data when the user enters his/her details. But every time it gives a sorry message in the console don't know whether the data is getting posted to PHP or not. Here's my code.
Sigin.js
import React, { Component } from 'react';
import { Redirect } from 'react-router-dom'
import axios from 'axios'
import $ from 'jquery'
class Signin extends Component {
constructor(props)
{
super(props);
const token = localStorage.getItem("token")
let loggedIn = true
if(token == null)
{
loggedIn = false
}
this.state = {
email: '',
password: '',
loggedIn
}
this.onChange = this.onChange.bind(this)
this.submitForm = this.submitForm.bind(this)
}
onChange(e){
this.setState({
[e.target.name] : e.target.value
})
}
submitForm(e){
e.preventDefault();
// const { email, password } = this.state
// if(email === "admin@123" && password === "admin")
// {
// localStorage.setItem("token", "loggedIn")
// this.setState({
// loggedIn: true
// })
// console.log("Logged In!")
// }
// else
// {
// alert("Invalid email or password!");
// console.log("Invalid email or password!")
// }
$.post("http://localhost/php-react-rest-api-crud/login_check.php", function(data){
if(data === "1")
{
localStorage.setItem("token", "loggedIn")
console.log("success!");
}
else if(data === "0")
{
console.log("sorry!");
}
})
}
render() {
if(this.state.loggedIn)
{
return <Redirect to = "/admin" />
}
return (
<div>
<h1>Login</h1>
<form onSubmit={this.submitForm}>
<input type="email" name="email" placeholder="Enter email" value={this.state.email} onChange={this.onChange}/>
<input type="password" name="password" placeholder="Enter Password" value={this.state.password} onChange={this.onChange}/>
<br />
<input type="submit"/>
</form>
</div>
);
}
}
export default Signin;
login_check.php
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Origin, Content-Type, Authorization, X-Auth-Token');
header("Access-Control-Allow-Methods: GET, POST");
$conn = mysqli_connect("localhost", "root", "", "farmer_portal");
if(!$conn)
{
die('Connection error'.mysqli_connect_errno());
}
if((!isset($_POST['email'])) && (!isset($_POST['password'])))
{
echo "0";
exit();
}
$myemail = $_POST['email'];
$mypassword= $_POST['password'];
$email = "SELECT * FROM signup WHERE email='$myemail' ";
$pass = "SELECT * FROM signup WHERE password='$mypassword' ";
$myemail = stripslashes($email);
$mypassword = stripslashes($password);
$res_e = mysqli_query($conn,$myemail);
$res_p = mysqli_query($conn,$mypassword);
if(mysqli_num_rows($res_p) > 0 && mysqli_num_rows($res_e) > 0)
{
echo "1";
}
else
{
echo "0";
}
?>