React Native Login - javascript

I Create login form for React Native App with mysql database
it seems that it doesn't see the query in my api keep showing the invalid message 'Invalid Username or Password Please Try Again' while the data is correct
I didn't figure out where is the problem
please anyone help me on this
login.js
// Creating Login Activity.
export default class LoginActivity extends Component {
// Setting up Login Activity title.
static navigationOptions =
{
title: 'LoginActivity',
};
constructor(props) {
super(props)
this.state = {
UserEmail: '',
UserPassword: ''
}
}
UserLoginFunction = () =>{
const { UserEmail } = this.state ;
const { UserPassword } = this.state ;
fetch('http://URL', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: UserEmail,
password: UserPassword
})
}).then((response) => response.json())
.then((responseJson) => {
// If server response message same as Data Matched
if(responseJson === 'Data Matched')
{
//Then open Profile activity and send user email to profile activity.
this.props.navigation.navigate('Second', { Email: UserEmail });
}
else{
Alert.alert(responseJson);
}
}).catch((error) => {
console.error(error);
});
}
this the api I tried different ones but didn't know where is the error exactly
API
<?php
// Importing DBConfig.php file.
include 'DBConfig.php';
// Creating connection.
$con = mysqli_connect($HostName,$HostUser,$HostPass,$DatabaseName);
// Getting the received JSON into $json variable.
$json = file_get_contents('php://input');
// decoding the received JSON and store into $obj variable.
$obj = json_decode($json,true);
// Populate User email from JSON $obj array and store into $email.
$email = $obj['email'];
// Populate Password from JSON $obj array and store into $password.
$password = $obj['password'];
//Applying User Login query with email and password match.
$Sql_Query = "select * from customers where email = '$email' and password = '$password' ";
// Executing SQL Query.
$check = mysqli_fetch_array(mysqli_query($con,$Sql_Query));
if(isset($check)){
$SuccessLoginMsg = 'Data Matched';
// Converting the message into JSON format.
$SuccessLoginJson = json_encode($SuccessLoginMsg);
// Echo the message.
echo $SuccessLoginJson ;
}
else{
// If the record inserted successfully then show the message.
$InvalidMSG = 'Invalid Username or Password Please Try Again' ;
// Converting the message into JSON format.
$InvalidMSGJSon = json_encode($InvalidMSG);
// Echo the message.
echo $InvalidMSGJSon ;
}
mysqli_close($con);?>

Related

Send image to backend as a Blob from Javascript to PHP using Fetch

id is a input where you can upload 1 image.
Basically I'd like for the image to be sent to back-end and be inserted into the DB.
Everything is working except getting the image to backend as a blob and uploading it.
Javascript Code:
const data = {
first_name: first_name.value,
last_name: last_name.value,
email: email.value,
company: company.value,
occupation: occupation.value,
students: students.value,
id: id.value
}
fetch('../scripts/partners_application', {
method: 'POST', headers: {'Content-Type': 'application/json',},
body: JSON.stringify(data)
}).then((response) => response.json()).then((data) => {
if (data["success"]){
error_message.style = "color:green;"
error_message.innerHTML = "<i class='fa-solid fa-check'></i> Successfully sent, we will be in touch with you soon."
}
}).catch((error) => {
console.error('Error:', error);
error_message.style = "color:red"
error_message.textContent = "Error occured, please try again later or contact us."
});
PHP Side:
$first_name = $data["first_name"];
$last_name = $data["last_name"];
$email = $data["email"];
$company = $data["company"];
$occupation = $data["occupation"];
$id = $data["id"];
$students = $data["students"];
$sql = "INSERT INTO partner_applications (first_name,last_name,email,company,occupation,id,students,date_created) VALUES(?,?,?,?,?,?,?,?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("sssssbss", $first_name, $last_name, $email,$company,$occupation,$id,$students,date("Y/m/d/H:i:s"));
$stmt->execute();
$response = array("success"=>true,"id"=>$id);
echo json_encode($response);

Why does my post request for fileupload work on Postman but not in the browser?

My React.js project and Laravel project are separated.
I login as an authenticated user in Postman using this endpoint (http://127.0.0.1:8000/api/auth/login)
I then upload a file using this (http://127.0.0.1:8000/api/auth/wall-of-fame)
All works fine - user's logged in and that logged in user can successfully upload a file to the db along with their user_id, email, and file_path.
The only thing that's very very weird about this working's that I'm not using an access token to successfully upload the aforementioned data to the db in Postman.
However, when I try the above 2 steps on the browser - I get a 200 when checking the Network tab but nothing's being stored in the db. I'm using an access token because how else can I recognize an authenticated on the client side?
Since this process works in Postman, my inclination's that something's off with the frontend and my possibly my Axios call. What am I doing wrong?
Here's my frontend code:
import React, {Component} from 'react';
import axios from 'axios';
class Upload extends Component {
constructor(props) {
super(props);
this.state = {
selectedFile: null,
id: null,
email: ''
};
this.onFormSubmit = this.onFormSubmit.bind(this);
this.onChange = this.onChange.bind(this);
this.fileUpload = this.fileUpload.bind(this);
}
componentDidMount() {
console.log("Inside componentDidMount()");
let id = localStorage.getItem("id");
let email = localStorage.getItem("email");
this.setState({
id: id,
email: email
})
console.log(id);
console.log(email);
}
onFormSubmit(e) {
e.preventDefault();
this.fileUpload(this.state.selectedFile);
}
onChange(e) {
this.setState({ selectedFile: e.target.files }, () => this.state.selectedFile);
}
fileUpload(file) {
const formData = new FormData();
const accessToken = localStorage.getItem("access_token").slice(13,-8);
console.log(accessToken);
console.log(this.state.id); // returns correct currently logged in userid
console.log(this.state.email); // returns correct currently logged in user email address
formData.append('file',file);
const headers = {
'Authorization' : 'Bearer ' + accessToken,
'Content-Type': 'multipart/form-data'
}
axios.post('http://127.0.0.1:8000/api/auth/wall-of-fame', formData, {headers})
.then(response => {
console.log(response);
}).catch(error => {
console.log(error);
});
}
render() {
return (
<form encType='multipart/form-data' id="login-form" className="form" onSubmit={this.onFormSubmit}>
<input type="file" name="file" onChange={this.onChange}/>
<button type="submit" >Upload</button>
</form>
);
}
}
export default Upload;
Here's backend controller code:
<?php
namespace App\Http\Controllers;
use App\Photo;
use App\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
class FileUploadController extends Controller {
public function store(Request $request) {
$user = Auth::user();
// dd($user);
if($user) {
$user_id = Auth::user()->id;
$email = Auth::user()->email;
$filePath = $request->file('file')->getClientOriginalName();
$data = [
'file_path' => $filePath,
'user_id' => $user_id,
'email' => $email
];
DB::table('db.photos')->insert($data);
return "inserted successfully";
}
return "failed";
}
}

POST request parameters are not detected by PHP

I am trying to submit some data with fetch to a php backend, but no request arrives on the backend.
The following is triggered on a change event.
JS
const submitVote = async (value) => {
const vote = { vote: value };
console.log('vote:', vote);
let postVote = await fetch('Backend/postHandler.php', {
method: 'POST',
headers: { 'Content-Type': 'application/json;charset=utf-8' },
body: JSON.stringify(vote)
});
let result = await postVote.text();
console.log('result:',result);
};
Logs vote: Object { vote: "yes" } to the console.
On the backend
PHP
<?php
namespace WebPoll\Backend;
if(isset( $_POST['vote'] )) {
$a = ["vote" => $_POST['vote']];
$myJSON = json_encode($a);
echo $myJSON;
} else {
print_r($_POST);
}
Logs result: array() to the JS console.
What is wrong here? Thanks.

Having issues with posting data using fetch in react

I am trying to fetch some data from a test API posting some data to it, but I get an error for response.json().
I get no error when fetching data without posting anything from another API.
My JavaScript:
fetch('https://cuteweb.ir/translatochka/requests.php', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
requestKey: 'checkLogged'
})
})
.then(response => response.json())
.then(parsed => console.log(parsed))
.catch(error => console.log(error))
and here is my API code in PHP:
$requestKey = isset($_POST['requestKey'])? $_POST['requestKey']: false;
if($requestKey){
switch ($requestKey) {
case 'checkLogged':
$_SESSION['username'] = "sinaw";
$sql = "SELECT DISTINCT * FROM tbl_users where
username='$_SESSION[username]'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
$row = $result->fetch_assoc();
$row['valid'] = true;
echo json_encode($row);
}
break;
My API code works correctly as I have tested it with jQuery $.ajax method.
This is the error I get:
SyntaxError: Unexpected end of JSON input

Simple mail send with fetch js and php

I'm trying to send message to my email using fetch() and php.
handle event
handleSubmit = (e) => {
e.preventDefault();
const data = { name: this.state.name, phone: this.state.phone };
fetch('/mail.php', {
method: 'POST',
body: data
}).then((response) => {
if (response.ok) {
this.setState({ success: true })
}
})
}
mail.php code
<?php
if ($_POST) {
$to = "mymail#gmail.com";
$subject = 'Subj';
$data = json_decode(file_get_contents('php://input'), true);
$message = 'Name: '.$data['name'].' Phone: '.$data['phone'];
$success = mail($to, $subject, $message);
if ($success) {
echo "Success!";
}
else {
echo "Fail";
}
}
?>
Using this because I was using it before with ajax() and it works.
I'm running my app at server, calling handler and getting "ok", but actually I don't get message on my email. I'm newbie, sorry if it's wrong way to achieve sending message to mail. I can't event know what data is getting php and where I am wrong..
Now it's works.
Just added JSON.stringify() in handler.
const data = JSON.stringify({ name: this.state.name, phone: this.state.phone });
And if (isset($_POST)) in mail.php

Categories

Resources