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' }
});
Related
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)
});
1.here is my php code
<?php
session_start();
include_once('connection.php');
include_once('function.php');
if(isset($_POST['username']) && isset($_POST['password'])) {
$username = trim( $_POST['username'] );
$password = trim( $_POST['password'] );
if( empty($username) || empty($password)) {
$res = ['error' => true, 'message' => 'All fields are required.'];
echo json_encode($res);
}else {
$user = login($conn, $username, $password);
if(count($user) > 0) {
$_SESSION['id'] = $user['id'];
$_SESSION['name'] = $user['name'];
$_SESSION['username'] = $user['username'];
$res = ['error' => false, 'message' => 'User login successfully.'];
echo json_encode($res);
}else {
$res = ['error' => true, 'message' => 'Username or password is incorrect.'];
echo json_encode($res);
}
}
}
2.here is my html and script code
<?php
include_once('inc/connection.php');
?>
<!DOCTYPE html>
<html>
<head>
<title>login</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
username: <input type="text" name="uesr" id='uesrname' /><br />
password: <input type="password" name="pass" id="password" /><br />
<button type="submit" name="submit" id="login">Login</button>
<script type="text/javascript">
$(document).on('click','#login',function(){
var username = $('#username').val();
var password =$('#password').val();
if( username == '' || password == ''){
//alert('all fields are required');
}else{
$.ajax({
url:'inc/ajax.login.php',
method:'POST',
data:{
username:username,
password:password
},
success:function($res){
console.log($res);
}
});
}
});
</script>
</body> </html>
List item
Use dataType and remove $ from success fucntion and try this
$.ajax({
url:'inc/ajax.login.php',
method:'POST',
dataType: 'json',
data:{
username:username,
password:password
},
success:function(res){
console.log(res);
}
});
Add die(); after you echo your json_encode.
Change your ajax codes to:
$.ajax({
url:'inc/ajax.login.php',
method:'POST',
dataType: 'json',
data:{
username:username,
password:password
},
success:function(res){
console.log(res);
}
});
IF You Don't use dataType: 'json', you can access your "res" by:
var res = JSON.parse(res);
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);
}
});
});
});
This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 9 years ago.
I am using wordpress as my base and made a custom login form.
ajax:
(function ( $ ) {
jQuery(document).ready(function() {
$("#login_form").submit(function(event){
//check the username exists or not from ajax
jQuery.ajax({
type: 'POST',
url: my_ajax.ajaxurl,
data: $('#login_form').serialize(),
cache: false,
//dataType: 'json',
success: function(result) {
var result=trim(result);
if( result == 'success' ){
window.location='/my-dashboard';
} else {
$('#message').html(result);
}
console.log(result);
}
});
return false;
});
});
function trim(str){
var str=str.replace(/^\s+|\s+$/,'');
return str;
}
}( jQuery ));
login form:
<p id="message" style="color:red;"></p>
<form method="post" action="" id="login_form">
<div align="center">
<div >
Email : <input name="email" type="text" id="email" value="" />
</div>
<div style="margin-top:5px" >
Password :
<input name="password" type="password" id="password" value="" />
</div>
<div class="buttondiv">
<input type="hidden" name="action" value="my_ajax_callback" />
<input type="hidden" name="func" value="check_login" />
<input name="submit" type="submit" id="submit" value="Login" style="margin-left:-10px; height:23px" /> <span id="msgbox" style="display:none"></span>
</div>
</div>
</form>
functions.php
// Ajax
add_action( 'wp_ajax_nopriv_my_ajax_callback', 'my_ajax_callback' );
add_action( 'wp_ajax_my_ajax_callback', 'my_ajax_callback' );
// Your Login function
function check_login( $params ){
require_once('lib/hash.php');
$session = new SC_Session;
// now you can use $session here
$message=array();
if(isset($_POST['email']) && !empty($_POST['email'])){
mysqli_real_escape_string($mysqli, $params['email']);
}else{
$message[]='Please enter email';
}
if(isset($_POST['password']) && !empty($_POST['password'])){
$password= mysqli_real_escape_string($mysqli, $params['password']);
}else{
$message[]='Please enter password';
}
$countError=count($message);
if($countError > 0){
for($i=0;$i<$countError;$i++){
echo ucwords($message[$i]).'<br/><br/>';
}
} else {
$hc=$mysqli->query("SELECT password FROM %table% email='".$email."' AND active=1");
while($hp = $hc->fetch_object()) {
$stored_hash = $hp->password;
}
$hasherd = new PasswordHash(8, false);
$check = $hasherd->CheckPassword($password, $stored_hash);
if($check) {
//now validating the username and password
$result=$mysqli->query("SELECT id, first_name, last_name, zip, email, password FROM %table% WHERE email='".$email."' AND active=1");
while($row = $result->fetch_object()) {
//if username exists
if($result->num_rows > 0)
{
$date = date('Y-m-d h:i:s');
$update_sql = $mysqli->query("UPDATE %table% SET last_login='".$date."'");
$firstname = $row->first_name;
$lastname = $row->last_name;
$zip = $row->zip;
$user_id = $row->id;
$sex = $row->sex;
$session->set_userdata( 'user_id', $user_id );
$session->set_userdata( 'email', $email );
$session->set_userdata( 'firstname', $firstname );
$session->set_userdata( 'lastname', $lastname );
$session->set_userdata( 'zip', $zip );
$session->set_userdata( 'sex', $sex );
}
}
echo ucwords('success');
//return $params;
} else{
echo ucwords('please enter correct user details');
}
}
}
/**
* Ajax Submit
*/
function my_ajax_callback() {
$response = call_user_func($_POST['func'], $_POST);
header( "Content-Type: application/json" );
echo json_encode($response);
exit;
}
The login currently works great, but whenever a error is thrown from $message it displays along with the header warnings.
Warning: Cannot modify header information - headers already sent by (output started at /%wordpresslocation%/wp-content/themes/%theme%/functions.php:77) in /%wordpresslocation%/wp-content/themes/%theme%/functions.php on line 86
null
ANSWER
I feel like an idiot, figured it out, I kept mixing php with javascript as I am proficient in php.
(function ( $ ) {
jQuery(document).ready(function() {
$('#message').slideUp();
$("#login_form").submit(function(event){
$('#message').slideUp();
//check the username exists or not from ajax
jQuery.ajax({
type: 'POST',
url: my_ajax.ajaxurl,
data: $('#login_form').serialize(),
dataType: 'json',
success: function(params) {
if( params == 'success' ){
$('#message').html(params).fadeIn();
document.location='/my-dashboard';
} else {
$('#message').html(params).fadeIn();
}
}
});
return false;
});
});
}( jQuery ));
and changed
echo ucwords('success');
//return $params;
} else{
echo ucwords('please enter correct user details');
}
to this
$params = 'success';
return $params;
}else{
$params = 'fail';
return $params;
and sent back the params
function check_login( $params ){
Thats because an error was printed (echo ucwords('please enter correct user details');)
Then, you try to set a header. That's not possible, headers always have to be set before anything else (that's how http works)
You will have to rewrite the parts that print text before the header is send. Also it doesn't send valid json so it wont work anyway