I have a website in reactJS and I want to let my user to register in my site, so i have the code:
import React from 'react'
import axios from 'axios'
import './Style/button.css'
class Register extends React.Component {
constructor(props) {
super(props);
this.state = {
email: '',
password: '',
confirmPassword: ''
}
}
handleFormSubmit(event) {
event.preventDefault();
let formData = new FormData();
formData.append('email', this.state.email)
formData.append('password', this.state.password)
console.log(formData);
axios({
method: 'post',
url: './api/contact/contact.php',
data: formData,
config: { headers: { 'Content-Type': 'multipart/form-data' } }
})
.then(function (response) {
//handle success
console.log(response)
})
.catch(function (response) {
//handle error
console.log(response)
});
}
render() {
return (
<form className="formulaire">
<fieldset>
<legend> Register : </legend>
<p>Mail adress :</p>
<input type="text" placeholder="Mail" name="email" value={this.state.email} onChange={e => this.setState({ email: e.target.value })}></input>
<br />
<p>Choose a password :</p>
<input type="password" placeholder="password" name="password" value={this.state.password} onChange={e => this.setState({ password: e.target.value })}></input>
<br />
<p>Confirm your password :</p>
<input type="password" placeholder=" confirm password" name="confirmPassword" value={this.state.confirmPassword} onChange={e => this.setState({ confirmPassword: e.target.value })}></input>
<br /><br /><br /><br />
<input className="button" type="submit" onClick={e => this.handleFormSubmit(e)} value="Sign up" />
</fieldset>
</form>
);
}
}
export default Register;
When i want to send the information with axios to my php file :
<?php
$host = "localhost";
$user = "root";
$password = "azertyuiop3104";
$dbname = "reactdb";
$id = '';
$con = mysqli_connect($host, $user, $password, $dbname);
$method = $_SERVER['REQUEST_METHOD'];
$request = explode('/', trim($_SERVER['PATH_INFO'], '/'));
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
switch ($method) {
case 'GET':
break;
case 'POST':
$email = $_POST["email"];
$password = $_POST["password"];
$sql = "insert into user (username, password) values ('$email', '$password')";
break;
}
// run SQL statement
$result = mysqli_query($con, $sql);
// die if SQL statement failed
if (!$result) {
http_response_code(404);
die(mysqli_error($con));
}
if ($method == 'POST') {
echo json_encode($result);
} else {
echo mysqli_affected_rows($con);
}
$con->close();
My request fail :
my file register.js (first code) is in a src/ directory and my contact.php (second code) is in src/api/contact/ directory
I don't know how to fix that, if any one can help me ?
Also, make sure the port that backend is hosted is 3000.
axios({
method: 'post',
url: 'http://localhost:3000/api/contact/contact.php', // <---------------
data: formData,
config: { headers: { 'Content-Type': 'multipart/form-data' } }
})
.then(function (response) {
//handle success
console.log(response)
})
.catch(function (response) {
//handle error
console.log(response)
});
Related
Help please deal with CAPTCHA. At me all is normal it is drawn, through Ajax the entered code is sent to file insert.php where at me the form handler. But the check does not work there. What do not enter in the input field, everything is considered correct
My form and ajax
<form action="/data/insert.php" method="POST" id="guest-form" name="reg">
<input id="username" type="text" name="name" placeholder="Username">
<input id="email" type="text" name="email" placeholder="E-mail">
<textarea id="message" type="text" name="text" placeholder="Your message"></textarea>
<img src="data/captcha.php" alt="Картинка" /><br />
<input id ="captcha" type="text" name="captcha" /><br />
<input id="submit" class="btn btn-default" type="button" value="Submit">
</form>
Ajax
$(document).ready(function() {
$('#submit').click(function() {
var username = $('#username').val();
var email = $('#email').val();
var message = $('#message').val();
var captcha = $('#captcha').val();
if(username || email || message || captcha === ''){
alert('Please input data in all fields');
}
else{
$.ajax({
type: "POST",
cache: false,
url: '/data/insert.php',
data: {username: username, email: email, message: message, captcha: captcha},
success: function(data) {
}
});
}
});
});
The php handler
require_once 'db.php';
require_once 'captcha.php';
session_start();
if (isset($_SESSION["captcha"]) && $_SESSION["captcha"]===$_POST["captcha"]){ echo "Текст введен верно"; }
else {
echo "Текст введен не верно";
}
unset($_SESSION["captcha"]);
if (isset($_POST['username']) && isset($_POST['email']) && isset($_POST['message'])){
$username = $_POST['username'];
$email = $_POST['email'];
$message = $_POST['message'];
$db_host = "localhost";
$db_user = "alekspvn"; // Логин БД
$db_password = "123"; // Пароль БД
$db_table = "book"; // Имя Таблицы БД
$connect_db=mysql_connect(HOST, MYSQL_USER, MYSQL_PASS)
or die("No connection with SQL");
mysql_select_db("guests_db",$connect_db);
mysql_query("SET NAMES 'utf8'",$connect_db);
$result = mysql_query ("INSERT INTO ".$db_table." (username,email,message) VALUES ('$username','$email','$message')");
if ($result = 'true'){
echo "Информация занесена в базу данных";
}else{
echo "Информация не занесена в базу данных";
}
}
?>
i am trying to send data to a php file but its not working.
Here is my code:
App.js:
.controller('sign_up', function ($scope, $http) {
$scope.login = function () {
var request = $http({
method: "post",
url: "js/login.php",
data: {
email: $scope.email,
password: $scope.password
},
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
/* Successful HTTP post request or not */
request.success(function (data) {
if(data == '1'){
$scope.responseMessage = "Successfully Logged In";
}
else {
$scope.responseMessage = "Username or Password is incorrect";
}
});
}
});
index.html:
<div ng-controller='sign_up'>
<input class="form-control" type="text" ng-model="email" name="email"
placeholder="Enter Your Email">
<br>
<input class="form-control" type="password" ng-model="password"
name="password" placeholder="Enter Your Password"><br>
<button class="btn btn-success" ng-click="login()">Login</button><br>
<span>{{responseMessage}}</span>
</div>
login.php:
<?php
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$email=$_POST['email']
$password=$_POST['password']
$email = $request->email;
$password = $request->password;
echo json_encode($email);
echo "email=".$email;
if($email == "two" && $password== "one"){
echo "1";
}
else {
echo "0";
}
?>
use $request = json_decode($postdata,TRUE);
<?php
$postdata = file_get_contents("php://input");
$request = json_decode($postdata,TRUE);
$email = $request->email;
$password = $request->password;
if($email == "two" && $password== "one"){
echo "1";
}
else {
echo "0";
}
?>
also change the content type to json
var request = $http({
method: "post",
url: "js/login.php",
data: {
email: $scope.email,
password: $scope.password
},
headers: { 'Content-Type': 'application/json' }
});
I have problem, I can't check username and password, can you help me?
login.php:
<form class="login-form" method="post" name="loginform" action="">
<div class="title-section">
<h1><span>Login</span></h1>
</div>
<p>Welcome! Login in to your account</p>
<label for="user_login">Username or email address<span>*</span>
</label>
<input type="text" name="log" id="user_login">
<label for="user_pass">Password<span>*</span>
</label>
<input name="pwd" id="user_pass" type="password">
<div id="error"></div>
<button type="submit" name="submit-login" id="submit-login"> <i class="fa fa-arrow-circle-right"></i> Login </button>
</form>
model.php;
<?php
ob_start();
session_start();
error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
?>
<?php
global $pdo;
session_start();
if(isset($_POST['submit-login'])) {
$user_email = trim($_POST['log']);
$user_password = trim($_POST['pwd']);
try {
global $pdo;
$stmt = $pdo->prepare("SELECT * FROM user WHERE username=:email");
$stmt->execute(array(":email"=>$user_email));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$count = $stmt->rowCount();
if($row['user_password']==$password){
echo "ok"; // log in
echo $_SESSION['user_session'] = $row['id_user'];
}
else {
echo "email or password does not exist."; // wrong details
}
}
catch(PDOException $e){
echo $e->getMessage();
}
}
?>
ajax.js
$(document).ready(function(){
$("#submit-login").click(function(){
username=$("#user_login").val();
password=$("#user_pass").val();
$.ajax({
type: "POST",
url: "admin/module/admin/model/acc_model.php",
data: "name="+username+"&pwd="+password,
success: function(html){
if(html=='ok') {
window.location="profile.php";
}
else {
alert('Please, Error');
}
},
beforeSend:function() {
$("#error").html("<img src='http://www.chinesecio.com/templates/base/images/loading.gif' /> Loading...")
}
});
return false;
});
});
You should pass the data like this
$(document).ready(function(){
$("#submit-login").click(function(){
username=$("#user_login").val();
password=$("#user_pass").val();
$.ajax({
type: "POST",
url: "admin/module/admin/model/acc_model.php",
data: {
name : username,
pwd : password
},
success: function(html){
if(html=='ok') {
window.location="profile.php";
}
else {
alert('Please, Error');
}
},
beforeSend:function()
{
$("#error").html("<img src='http://www.chinesecio.com/templates/base/images/loading.gif' /> Loading...")
}
});
return false;
});
});
Also use parameter like below :
$user_email = trim($_POST['name']);
$user_password = trim($_POST['pwd']);
I think that when you are sending data from your ajax request you are using different variable names and in your model.php you are using your form elements name. Please check into that
data : {"name":username, "password ":password}
i am trying to get the user details into database and data is stored..i want a success message to fade in i have tried out some code but sadly its not working...plzz help me out of this..beg u pardon if am wrong..
here gose my register.php code
<?php
require_once 'DB_Functions.php';
$db = new DB_Functions();
// json response array
$response = array("error" => false);
if (!empty($_POST['fname']) && !empty($_POST['lname']) && !empty($_POST['email']) && !empty($_POST['password']) && !empty($_POST['mobile'])){
// receiving the post params
$fname = trim($_POST['fname']);
$lname = trim($_POST['lname']);
$email = trim($_POST['email']);
$password = $_POST['password'];
$mobile = trim($_POST['mobile']);
// validate your email address
if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
// valid email address
if ($db->isUserExisted($email)) {
// user already existed
$response["error"] = true;
$response["error_msg"] = "User already existed with " . $email;
echo json_encode($response);
} else {
// create a new user
$user = $db->storeUser($fname, $lname, $email, $password, $mobile);
if ($user) {
// user stored successfully
$response["error"] = false;
$response["uid"] = $user["id"];
$response["user"]["fname"] = $user["fname"];
$response["user"]["lname"] = $user["lname"];
$response["user"]["email"] = $user["email"];
$response["user"]["created_at"] = $user["created_at"];
$response["user"]["updated_at"] = $user["updated_at"];
echo json_encode($response);
} else {
// user failed to store
$response["error"] = true;
$response["error_msg"] = "Unknown error occurred in registration!";
echo json_encode($response);
}
}
} else {
// invalid email address
$response["error"] = true;
$response["error_msg"] = "invalid email address";
echo json_encode($response);
}
} else {
$response["error"] = true;
$response["error_msg"] = "Required parameters are missing!";
echo json_encode($response);
}
?>
and here gose the .html file with jquery..
<html>
<head>
<title>jQuery Test</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src = "register.js"></script>
</head>
<body>
<!--html body-->
<form name = "register" id = "register" method = "POST">
<label>First name:</label>
<input type = text name = "fname" id = "fname" required>
<label>Last name:</label>
<input type = "text" name = "lname" id = "lname" required>
<label>E-mail:</label>
<input type = "email" name = "email" id = "email" required>
<label>Password</label>
<input type = "password" name = "password" id = "password" required>
<label>Mobile no:</label>
<input type = "number" name = "mobile" id = "mobile" required>
<input type="submit" value="Insert" name="submit" id = "submit">
</form>
<div id = "result" align = "right"></div>
</body>
</html>
here gose me /.js/ file
$(document).ready(function(){
$("#submit").click(function(e){
e.preventDefault();
$.ajax({
url: "register.php",
type: "POST",
data: {
fname: $("#fname").val(),
lname: $("#lname").val(),
email: $("#email").val(),
password: $("#password").val(),
mobile: $("#mobile").val()
},
dataType: "JSON",
success: function (json) {
$("#result").html(json.user.email); // like that you can display anything inside #result div
$("#result").fadeOut(1500);
},
error: function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
}
});
});
});
There's no need to use JSON.stringify(jsonStr) because jQuery has already parsed the response object for you. jQuery will look at the Content-Type of the response and, if it's application/json, it will parse it, and provide the parsed result to your success handler.
Your jQuery should be like this:
$(document).ready(function(){
$("#submit").click(function(e){
e.preventDefault();
$.ajax({
url: "register.php",
type: "POST",
data: {
fname: $("#fname").val(),
lname: $("#lname").val(),
email: $("#email").val(),
password: $("#password").val(),
mobile: $("#mobile").val()
},
dataType: "JSON",
success: function (json){
if(json.error){
$("#result").html(json.error_msg); // display error message
}else{
$("#result").html(json.user.email); // like that you can display anything inside #result div
}
$("#result").fadeOut(1500);
},
error: function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
}
});
});
});
Hopefully someone can help me here, I am tired of banging my head on the desk. I am not sure why the json response isn't showing up on the div below the form. I can see the response in my firebug debugger(Firefox debugger), but nothing shows up in div.
I've the main register.php that contains the form and javascript and calls another register.php file with the php code that calls the registration function. I can create new account and data files to the database without any problem, but I am unable to get the response back in my div. Please help!
register.php
<body>
<div class="logo"></div>
<div class="form">
<form id="register" method="post">
<input type="text" name="email" id="email" placeholder="Email Address" /><br/><br/>
<input type="text" name="username" id="username" placeholder="Username" />
<input type="password" name="password" id="password" placeholder="Password" />
<input type="submit" id="register" value="Register" />
</form>
</div>
<div class="small">
I already have an account<br/>
</div>
<div id="message"></div>
<script type="text/javascript">
$(document).ready(function(){
var myForm = $('#register');
myForm.validate({
errorClass: "errormessage",
onkeyup: false,
errorClass: 'error',
validClass: 'valid',
rules: {
email: { required: true, email: true, minlength: 3, maxlength: 100 },
username: { required: true, minlength: 3, maxlength: 30 },
password: { required: true, minlength: 3, maxlength: 100 }
},
errorPlacement: function(error, element)
{
var elem = $(element),
corners = ['right center', 'left center'],
flipIt = elem.parents('span.right').length > 0;
if(!error.is(':empty')) {
elem.filter(':not(.valid)').qtip({
overwrite: false,
content: error,
position: {
my: corners[ flipIt ? 0 : 1 ],
at: corners[ flipIt ? 1 : 0 ],
viewport: $(window)
},
show: {
event: false,
ready: true
},
hide: false,
style: {
classes: 'ui-tooltip-red'
}
})
.qtip('option', 'content.text', error);
}
else { elem.qtip('destroy'); }
},
success: $.noop,
})
});
$("#register").submit(function(event) {
if($("#register").valid()) {
event.preventDefault();
var $form = $( this ),
mail = $form.find('input[name="email"]').val(),
user = $form.find('input[name="username"]').val(),
pass = $().crypt({method:"sha1",source:$().crypt({method:"sha1",source:$form.find('input[name="password"]').val()})});
$.post("inc/action.php?a=register", {email: mail, username: user, password: pass},
function(data) {
$("#message").html('<p> code: ' + data.error + '</p>');
$("#message").append('<p> message: ' + data.message + '</p>');
}, "json"
);
}
else
{
$("[id^=ui-tooltip-]").effect("pulsate", {times: 3}, 300);
return false;
}
});
</script>
</body>
register.php
<?php
if(isset($_POST['email'])) { $email = $_POST['email']; } else { echo 1; exit(); }
if(isset($_POST['username'])) { $username = $_POST['username']; } else { echo 1; exit(); }
if(isset($_POST['password'])) { $password = $_POST['password']; } else { echo 1; exit(); }
$register = $auth->register($email, $username, $password);
$return = array();
switch($register['code'])
{
case 0:
$return['error'] = 1;
$return['message'] = "You are temporarily locked out of the system. Please try again in 30 minutes.";
break;
case 1:
$return['error'] = 1;
$return['message'] = "Username / Password is invalid";
break;
case 2:
$return['error'] = 1;
$return['message'] = "Email is already in use";
break;
case 3:
$return['error'] = 1;
$return['message'] = "Username is already in use";
break;
case 4:
$return['error'] = 0;
$return['message'] = "Account created ! Activation email sent to " . $register['email'];
break;
default:
$return['error'] = 1;
$return['message'] = "System error encountered";
break;
}
$return = json_encode($return);
echo $return;
Add header('Content-Type: application/json') before returning the json-encoded data.
in json.php
<?php
$data['error']=1;
$data['msg']="error";
header('Content-Type: application/json');
echo json_encode($data);
?>
in index.php
<script type="text/javascript">
$.ajax({
url:'json.php',
success:function(data){
$('body').html(data.msg);
}
});
</script>