AJAX error function invoked instead of success - javascript

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

Related

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;
}

javascript retreive fetch response from a php

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

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

AngularJS - php mailer keeps returning "500 (Internal Server 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!

Categories

Resources