javascript retreive fetch response from a php - javascript

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"}';
}
?>

Related

AJAX error function invoked instead of success

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');

How do I fetch data from my back-end (localhost) that's being sent through Fetch API? (PHP, Fetch, React Native, POST request)

fetch("http://10.0.2.2:80/NewAdmin/scripts/main/transactions", {
method:'post',
headers:{
"Accept":"application/json",
"Content-type":"application/json"
},
// (var) payload looks like this {Header: "Sending", . . .}
body:JSON.stringify(payload)
})
.then(res => res.json())
.then(resp => console.log(resp))
.catch(err => console.log(err));
My PHP code
<?php
$json = json_decode(file_get_contents('php://input'), true);
echo $json;
if($json["Header"] == "Sending"){
echo json_encode('!WTF');
}else{
echo json_encode('WTF!');
}
?>
It returns 'WTF!'—no pun intended. What am I missing?
Try this example, it should return 'action test' OR Error,
JS Code:
fetch(ConfigApp.URL + 'transactions.php', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
action: 'action test',
p: 'addSession',
}),
})
.then(response => response.json())
.then(responseJson => {
console.warn(responseJson)
})
.catch(function(error) {
console.warn(Strings.no_result + error.message);
});
PHP transactionsv.php:
<?php
//Make sure that it is a POST request.
if(strcasecmp($_SERVER['REQUEST_METHOD'], 'POST') != 0){
throw new Exception('Request method must be POST!');
}
//Make sure that the content type of the POST request has been set to application/json
$contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';
if(strcasecmp($contentType, 'application/json') != 0){
throw new Exception('Content type must be: application/json');
}
//Receive the RAW post data.
$content = trim(file_get_contents("php://input"));
//Attempt to decode the i ncoming RAW post data from JSON.
$decoded = json_decode($content, true);
if(!is_array($decoded)){
$json_string = json_encode(false);
print ($json_string);
die();
}elseif(!isset($decoded["p"])){
$decoded = $decoded[0];
}
switch ($decoded["p"]) {
case 'addSession':
print (json_encode($decoded['action']));
break;
default:
$json_string = json_encode(false);
print ($json_string);
break;
}

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.

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

JQuery ajax post to PHP server not working - "SyntaxError: Unexpected token < in JSON at position 0" [duplicate]

This question already has answers here:
"SyntaxError: Unexpected token < in JSON at position 0"
(40 answers)
Closed 5 years ago.
I am trying to send json data to a server, and receive a json response, code is as follows:
JS:
function login() {
console.log("clicked");
//get values of form into variables
var email = $("#email").val();
var password = $("#password").val();
//create data array
var dataString = {"email": email, "password": password};
console.log(dataString);
//check for blank inputs
if ($.trim(email).length == 0) {
myApp.alert("Email required", "Login Failed");
} else if ($.trim(password).length == 0) {
myApp.alert("Password required", "Login Failed");
}
//if form isnt empty, post ajax request to server
if ($.trim(email).length > 0 & $.trim(password).length > 0) {
console.log("input checked");
$.support.cors = true;
//ajax post
$.ajax({
type: "POST",
url: "http://gingr-server.com/login.php",
data: dataString,
dataType: 'json',
crossDomain: true,
cache: false,
beforeSend: function() {
$("#login").val('Connecting...');
console.log("connecting to server");
},
//display success/fail message - put something in data on server
success: function(data, textString, xhr) {
if (data.status == "correct") {
localStorage.login = "true";
localStorage.email = email;
localStorage.id = data.id;
mainView.router.loadPage("swipe.html");
} else {
myApp.alert("Incorrect email or password", "Login Failed");
}
},
error: function(xhr, ajaxOptions, errorThrown) {
console.log(xhr);
console.log(errorThrown);
myApp.alert("Unknown error, please try again", "Login Failed");
},
complete: function(data) {
if (data.readyState == "0") {
console.log("unsent");
} else if (data.readyState == "4") {
console.log("done");
}
}
});
}
return false;
}
PHP:
<?php
header("access-control-allow-origin: *");
header("access-control-allow-methods: GET, POST, PATCH, PUT, DELETE, OPTIONS");
header("access-control-allow-headers: X-Requested-With, Content-Type");
header('Content-Type: application/json');
//include databse info
require_once "db_config.php";
$email = $mysqli->real_escape_string(htmlspecialchars($_POST["email"]));
$password = $mysqli->real_escape_string(htmlspecialchars($_POST["password"]));
//get hashed password from db
$result = $mysqli->query("SELECT password, id FROM user_table WHERE
email = '$email'");
$row = $result->fetch_assoc();
$passwordHash = $row["password"];
$userID = $row["id"];
//free memory
$result->free();
//verify password for that email
if (password_verify($password, $passwordHash)) {
$response = array( "status" => "correct",
"id" => $userID));
} else {
$response = array("status" => "incorrect"));
}
echo json_encode($response);
$mysqli->close();
?>
The error message is as follows:
SyntaxError: Unexpected token < in JSON at position 0
at parse ()
To me, it looks as if the client is receiving HTML (hence the < tag) instead of json, but I have no idea why!
Found it! Nothing clever at all...
$response = array( "status" => "correct",
"id" => $userID));
spot the )); causing all the problems... Bed time I think

Categories

Resources