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
Related
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);
I'm new to using PHP. I'm implementing an email subscription form that is wrapped in a google captcha function. I'm using ajax to call the server-side code. The issue I'm having is the success() method inside the ajax is not being invoked when the function executes correctly.
Some details: the 3rd party email subscription returns a json object with a single key-value pair, {message: "you've been added"} or {message:"error,try again"}
The function has run 'successfully if we hit the else clasue in the php file. when this happens, it runs the error() callback for some reason? even though i have a status 200
I suspect im not returning valid json or something? Thanks in advance!
Here is my JS
$(".subscribe-form").submit(function (e) {
e.preventDefault();
var form = $(this);
var formData = form.serialize();
var formAction = form.attr("action");
var formMethod = form.attr("method");
var formResponse = $("#form-response");
grecaptcha.ready(function () {
grecaptcha
.execute("6Lcgdq4UAAAAAFjthnpc_WQ4leumC1UmlyLk0OwR", {
action: "submit",
})
.then(function (token) {
var recaptchaResponse = document.getElementById("recaptchaResponse");
recaptchaResponse.value = token;
$.ajax({
url: "/wp-content/themes/hello-elementor/submit.php",
type: "POST",
data: formData,
dataType: "json",
success: function (data) {
console.log(data);
if (data.error) {
formResponse.html(data.error);
} else {
formResponse.html(data.success);
}
},
error: function (data) {
console.log(data);
formResponse.html("Error, please try again");
},
});
});
});
});
Here is my sumbit.php - I've removed the secret for obvious reasons.
<?php
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$ttrurl = "https://3rdpartysubsciptionservice/addEmailDetails.aspx?first_name=$fname&last_name=$lname&email=$email";
$url = "https://www.google.com/recaptcha/api/siteverify";
$data = [
'secret' => "secret_code",
'response' => $_POST['recaptcha_response'],
'remoteip' => $_SERVER['REMOTE_ADDR']
];
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
$res = json_decode($response, true);
// Take action based on the score returned
if ($res['success'] == false && $res['score'] <= 0.5) {
// Score less than 0.5 indicates suspicious activity. Return an error
$error = "Something went wrong. Please try again later";
$output = array("error" => $error, "success" => "");
http_response_code(400);
echo json_encode($output);
} else {
// This is a human. Insert the message into database OR send a mail
$curl = curl_init();
curl_setopt_array($curl, array(CURLOPT_URL => $ttrurl));
$ttrres = curl_exec($curl);
curl_close($curl);
$message = json_decode($ttrres, true);
$output = array("error" => "", "success" => json_encode($message));
http_response_code(200);
echo json_encode($output);
}
?>
please note that you set dataType: "json" in your ajax and your response does not seem to be json.
use this code on top of your php code:
header('Content-Type: application/json; charset=utf-8');
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);?>
I'm try to implement the paypal express checkout.
So I implement the button and write the result in my database. Nothing exceptional, it's the script they gave.
<script>
paypal.Buttons({
createOrder: function(data, actions) {
return actions.order.create({
purchase_units: [{
amount: {
value: '0.01'
}
}]
});
},
onApprove: function(data, actions) {
return actions.order.capture().then(function(details) {
// Call your server to save the transaction
return fetch('recordDatabase.php', {
method: 'post',
mode: "same-origin",
credentials: "same-origin",
headers: {"Content-Type": "application/json"},
body: JSON.stringify({
orderID: data.orderID,
time: details.create_time,
status: details.status,
nom: details.payer.name.given_name,
prenom: details.payer.name.surname,
pays: details.payer.address.country_code,
valeur:details.purchase_units[0].amount.value
})
})
});
}
}).render('#paypal-button-container');
</script>
The php to record in the database:
<?php
$link = connect();
$date = date('Y-m-d H:i:s');
//Receive the RAW post data.
$contentType = isset($_SERVER["CONTENT_TYPE"]) ?trim($_SERVER["CONTENT_TYPE"]) : '';
if ($contentType === "application/json") {
//Receive the RAW post data.
$content = trim(file_get_contents("php://input"));
$decoded = json_decode($content, true);
//If json_decode failed, the JSON is invalid.
if(! is_array($decoded)) {
//echo "error";
} else {
$name = $decoded['nom'];
$time = $decoded['time'];
$id = $decoded['orderID'];
$stat = $decoded['status'];
$pays = $decoded['pays'];
$val = $decoded['valeur'];
$secQuery = "INSERT INTO myDatabase(PSEUDO,PASSWORD,CONNECTION,INSCRIPTION,ANNIVERSAIRE,MAIL,IDPAYPAL,STATPAYPAL,NOMPAYER,PAYS,VALEUR) VALUES ('essai','123456',0,'$date','$time','email#mail','$id','$stat','$name','$pays','$val') ";
if (mysqli_query($link,$secQuery)) {
//echo "ok";
} else {
//echo "error";
}
}
} else {
//echo "error";
}
So, the record in my database works fine, but my question is:
How can I retrieve the echo error or ok in the javascript to confirm the user that everything is fine, or if an error happen.
I tried another solution, to redirect the user from the php and add to the php:
header("Location: confirmation web page"); or
echo "<script>window.location = 'confirmation web page'</script>";
but both solution doesn't work. No redirection happen
Correct if i'm wrong, recordDatabase.php is your php file that is storing the transactions.
So, the return fetch('recordDatabase.php', { is returning the response from this file, your echo 'ok';,echo 'error';, the fetch is asyncronous, so it'will return a promise.
Add header('Content-Type: application/json'); to your php file so it returns a json response.
Also change your echo to echo '{"status":"ok"}'; and echo '{"status":"error"}';
Now modify your fetch function,
return fetch('recordDatabase.php', {
//same info here
})
.then((response) => response.json())
.then((responseData) => {
if(responseData.status == "ok"){
alert("it worked");
}else{
alert("it didn't work");
}
})
return fetch('codes/paypalapi.php', {
method: 'post',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify({
orderID: data.orderID
})
});
it will work perfectly
i had the same situation
I have just solved your case , just try this code and see how it works
Paypal Script API
<script>
paypal.Buttons({
createOrder: function(data, actions) {
return actions.order.create({
purchase_units: [{
amount: {
value: '0.01'
}
}]
});
},
onApprove: function(data, actions) {
return actions.order.capture().then(function(details) {
alert('Transaction completed by ' + details.payer.name.given_name+' ApplicationId <?php echo $id; ?> :payerID'+data.payerID);
// Call your server to save the transaction
return fetch('payments.php', {
method: 'post',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify({
orderID: data.orderID,
time: details.create_time,
status: details.status,
nom: details.payer.name.given_name,
prenom: details.payer.name.surname,
pays: details.payer.address.country_code,
valeur:details.purchase_units[0].amount.value
})
}).then(data => data.ok && data.json()).then(response => {
alert(response.status);
});
});
}
}).render('#paypal-button-container');
</script>
PHP script (payments.php)
<?php
header('Content-Type: application/json');
$date = date('Y-m-d H:i:s');
//Receive the RAW post data.
$contentType = isset($_SERVER["CONTENT_TYPE"]) ?trim($_SERVER["CONTENT_TYPE"]) : '';
if ($contentType === "application/json") {
//Receive the RAW post data.
$content = trim(file_get_contents("php://input"));
$decoded = json_decode($content, true);
//If json_decode failed, the JSON is invalid.
if(! is_array($decoded)) {
//echo "error";
} else {
$name = $decoded['nom'];
$time = $decoded['time'];
$id = $decoded['orderID'];
$stat = $decoded['status'];
$pays = $decoded['pays'];
$val = $decoded['valeur'];
echo '{"status":"ok"}';
}
} else {
echo '{"status":"error"}';
}
?>
The app.js controller which handles contact form looks as follows:
app.controller('ContactController', function ($scope, $http) {
$scope.result = 'hidden'
$scope.resultMessage;
$scope.formData; //formData is an object holding the name, email, subject, and message
$scope.submitButtonDisabled = false;
$scope.submitted = false; //used so that form errors are shown only after the form has been submitted
$scope.submit = function(contactform) {
$scope.submitted = true;
$scope.submitButtonDisabled = true;
if (contactform.$valid) {
$http({
method : 'POST',
url : 'contact-form.php',
data : $.param($scope.formData), //param method from jQuery
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } //set the headers so angular passing info as form data (not request payload)
}).success(function(data){
console.log(data);
if (data.success) { //success comes from the return json object
$scope.submitButtonDisabled = true;
$scope.resultMessage = data.message;
$scope.result='bg-success';
} else {
$scope.submitButtonDisabled = false;
$scope.resultMessage = data.message;
$scope.result='bg-danger';
}
});
} else {
$scope.submitButtonDisabled = false;
$scope.resultMessage = 'Failed :( Please fill out all the fields.';
$scope.result='bg-danger';
}
}
});
Unfortunately, it keeps returning the "500 (Internal Server Error)". It seems that file "contact-form.php" is unable to be found. I suppose it's something with the path which cannot be detected properly.I double checked and the "contact-form.php" is in main directory, so I guess it's something with angular paths.
But maybe the issue lays elsewhere. Perhaps it's worth to paste the contact-form.php code as well.
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
require_once 'phpmailer/PHPMailerAutoload.php';
if (isset($_POST['inputName']) && isset($_POST['inputEmail']) && isset($_POST['inputSubject']) && isset($_POST['inputMessage'])) {
//check if any of the inputs are empty
if (empty($_POST['inputName']) || empty($_POST['inputEmail']) || empty($_POST['inputSubject']) || empty($_POST['inputMessage'])) {
$data = array('success' => false, 'message' => 'Please fill out the form completely.');
echo json_encode($data);
exit;
}
//create an instance of PHPMailer
$mail = new PHPMailer();
$mail->From = $_POST['inputEmail'];
$mail->FromName = $_POST['inputName'];
$mail->AddAddress('test#gmail.com'); //recipient
$mail->Subject = $_POST['inputSubject'];
$mail->Body = "Name: " . $_POST['inputName'] . "\r\n\r\nMessage: " . stripslashes($_POST['inputMessage']);
if (isset($_POST['ref'])) {
$mail->Body .= "\r\n\r\nRef: " . $_POST['ref'];
}
if(!$mail->send()) {
$data = array('success' => false, 'message' => 'Message could not be sent. Mailer Error: ' . $mail->ErrorInfo);
echo json_encode($data);
exit;
}
$data = array('success' => true, 'message' => 'Thanks! We have received your message.');
echo json_encode($data);
} else {
$data = array('success' => false, 'message' => 'Please fill out the form completely.');
echo json_encode($data);
}
Thanks in advance!