How can i get result from PHP fetch assoc - javascript

// Request password
$app->get('/api/admin/forgot', function(Request $request, Response $response){
$email = $request->getParam('email');
$sql = "SELECT admin_password FROM administrators WHERE admin_email = '$email' ";
try{
$db = new db();
$db = $db->connect();
$stmt = $db->query($sql);
$admin = $stmt->fetch(PDO::FETCH_ASSOC);
$db = null;
if($admin == null){
echo json_encode(array(
"errno" => 1,
"message" => "No account",
)
);
return;
}
echo $admin;
require_once "vendor/autoload.php";
//PHPMailer Object
$mail = new PHPMailer;
//From email address and name
$mail->From = "contact#SMS.com";
$mail->FromName = "SAMPLES Management Software";
//To address and name
$mail->addAddress($email);
//Address to which recipient will reply
$mail->addReplyTo("contact#SMS.com", "SAMPLE Management Software");
//Send HTML or Plain Text email
$mail->isHTML(true);
$mail->Subject = "Password recovery";
$mail->Body = "<h3>Password recovery<h3></br><p>Hi there, your password is '$admin'</p>";
if(!$mail->send()) {
echo json_encode(array(
"errno" => 0,
"message" => "Email not sent.",
)
);
} else {
echo json_encode(array(
"errno" => 0,
"message" => "Email sent.",
)
);
}
} catch(PDOException $e) {
echo json_encode(array(
"errno" => 1,
"feedback" => $e->getMessage(),
"message" => "Error occured",
)
);
}
}
);
Okay so i have this code to retrieve passwords and send to mail directly, it works great and i get the mail but the only problem is i am getting the password as 'array'. The password is $admin. Any help? Thanks in advance

With $stmt->fetch(PDO::FETCH_ASSOC); you get a row ( in this case the first row) and not the column values
for get the column values you should use
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$admin = $row['admin_password'];
and if you retunr more than a value you shold loop over the query result

Related

Uncaught SyntaxError: JSON.parse: unexpected character ierror after include php file

Uncaught SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data site:stackoverflow.com error is showing in firefox debug console.
I have a form in my website and on submit button this functions calls
$("#contact-form").on("submit",function(e)
{
var sendData = $(this).serialize();
e.preventDefault();
if ( checkSubmitInputs(this) )
{
$.ajax({
type: "POST",
url: "js/ajaxsubmit.php",
data: sendData,
success: function(data)
{
$("#loading-img").css("display","none");
// $(".response_msg").text(data);
// document.getElementById('contact-form').style.display = 'none'
// document.getElementById('success').style.display = 'block'
data = JSON.parse(data);
if(data.status){
document.getElementById('contact-form').style.display = 'none';
$("#error").text('');
$("#success").text(data.msg);
document.getElementById('success').style.display = 'block';
document.getElementById('scicon-c').style.display = 'block';
document.getElementById('error').style.display = 'none';
$("#contact-form").find("input[type=text], input[type=email], textarea").val("");
}
else {
document.getElementById('contact-form').style.display = '';
$("#success").text('');
$("#error").text(data.msg);
document.getElementById('error').style.display = 'block'
document.getElementById('success').style.display = 'none'
document.getElementById('scicon-c').style.display = 'none'
}
}
});
} else{
document.getElementsByClassName('error').style.display = 'block'
}
})
This line data = JSON.parse(data); shows above error as soon as i add include_once('mail.php'); in my ajaxsubmit.php file and without including it works perfectly.
Mail.php I am receiving mail too
<?php
error_reporting(-1);
ini_set('display_errors', 'On');
set_error_handler("var_dump");
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
require_once("vendor/autoload.php");
$mail = new PHPMailer(true);
//Enable SMTP debugging.
$mail->SMTPDebug = 3;
//Set PHPMailer to use SMTP.
$mail->isSMTP();
//Set SMTP host name
$mail->Host = "email-smtp.us-west-1.amazonaws.com";
//Set this to true if SMTP host requires authentication to send email
$mail->SMTPAuth = true;
//Provide username and password
$mail->Username = "ID";
$mail->Password = "Pass";
//Set TCP port to connect to
$mail->Port = 587;
$mail->setFrom('demo#example', 'demo#example');
error_reporting(E_ALL); // Error/Exception engine, always use E_ALL
ini_set('ignore_repeated_errors', TRUE); // always use TRUE
ini_set('display_errors', true); // Error/Exception display, use FALSE only in production environment or real server. Use TRUE in development environment
ini_set('log_errors', TRUE); // Error/Exception file logging engine.
ini_set('error_log', 'zeeErrors.log'); // Logging file path
function sendEmailToUser($con, $emailMsg, $Subject)
{
global $mail;
$msg = "";
$subject = $Subject;
$tempArray = explode(',', $emailMsg);
$name = $tempArray[0];
$mobile = $tempArray[1];
$email = $tempArray[2];
$mail->Subject = "Test.";
$to = $email;
$htmlTemplate = file_get_contents('ration.html', true);
$mail->addAddress($to, $name); //Add a recipient
//$mail->addAddress('ellen#example.com'); //Name is optional
//$mail->addCC('cc#example.com');
//$mail->addBCC('varun7952#gmail.com');
$mail->isHTML(true);
$mail->Body = $msg;
//$mail->AltBody = "This is the plain text version of the email content";
try {
$mail->send();
echo "Message has been sent successfully";
return true;
} catch (Exception $e) {
echo "Mailer Error: " . $mail->ErrorInfo;
return false;
}
}
?>
AjaxSubmit.php
<?php
include_once('mail.php');
$response = array();
if((isset($_POST['name'])&& $_POST['name'] !='') && (isset($_POST['email'])&& $_POST['email'] !='') && (isset($_POST['phone'])&& $_POST['phone'] !=''))
{
//whether ip is from share internet
$ia = '';
if (!empty($_SERVER['HTTP_CLIENT_IP']))
{
$ia = $_SERVER['HTTP_CLIENT_IP'];
}
//whether ip is from proxy
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
{
$ia = $_SERVER['HTTP_X_FORWARDED_FOR'];
}
//whether ip is from remote address
else
{
$ia = $_SERVER['REMOTE_ADDR'];
}
/*Get user ip address details with geoplugin.net*/
$geopluginURL='http://www.geoplugin.net/php.gp?ip='.$ia;
$addrDetailsArr = unserialize(file_get_contents($geopluginURL));
/*Get City name by return array*/
$city = $addrDetailsArr['geoplugin_city'];
/*Get Country name by return array*/
$country = $addrDetailsArr['geoplugin_countryName'];
$region = $addrDetailsArr['geoplugin_regionName'];
if(!$city){
$city='Not Define';
}
if(!$country){
$country='Not Define';
}
if(!$region){
$region='Not Define';
}
//file_put_contents('zee1.log', print_r($addrDetailsArr, TRUE));
$yourName = $conn->real_escape_string($_POST['name']);
$yourEmail = $conn->real_escape_string($_POST['email']);
$yourPhone = $conn->real_escape_string($_POST['phone']);
$city = $conn->real_escape_string($city);
$country = $conn->real_escape_string($country);
$region = $conn->real_escape_string($region);
$checkSql = "SELECT name, email, contact from reg where email='".$yourEmail."' OR contact='".$yourPhone."'";
$resultCheck = $conn->query($checkSql);
if($resultCheck->num_rows > 0) {
$response['status'] = false;
$response['msg'] = "You have registered already with ".$yourEmail." OR ".$yourPhone."";;
}else {
$userLocation = $city.' '.$region.' '.$country;
$sql="INSERT INTO reg (name, email, contact,IP_Address,City) VALUES ('".$yourName."','".$yourEmail."', '".$yourPhone."','".$ia."','".$userLocation."')";
if(!$result = $conn->query($sql)){
$response['status'] = false;
$response['msg'] = 'There was an error running the query [' . $conn->error . ']';
}
else
{
$response['status'] = true;
$response['msg'] = "Thank you $yourName. Welcome in SAAS Application. We will connect with you soon. :)";
$msg = $yourName.','.$yourPhone.','.$yourEmail.','.$userLocation;
if(sendEmailToUser($conn,$msg,'Reg')){
//Email Sent
}
}
}
}
else
{
$response['status'] = false;
$response['msg'] = 'Please fill Name and Email';
}
echo json_encode($response);
?>
As i said everything is working if i don't add require in ajaxsubmit file. I am not good in php or JS so after reading so many answers i still can't figure out why i am not able to parse json at my form.
This is JSON Returned by AJAXsubmit
{
"status": true,
"msg": "Thank you Demo. Welcome in SAAS Application. We will connect with you soon. :)"
}
Your problem is that mail.php has this code in it:
try {
$mail->send();
echo "Message has been sent successfully";
return true;
} catch (Exception $e) {
echo "Mailer Error: " . $mail->ErrorInfo;
return false;
}
which, regardless of the result, causes text to be echo'ed. As a result, your json response will look something like:
Message has been sent successfully
{
... normal json response
}
which will not parse successfully.

How do i use fetch API to get multiple variables from php

im trying to get more than one variable from my remote php using the Javscript fetch API, \
this is my php
<?php
include 'config.php';
//$email = $_GET['email'];
try {
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$sql = "SELECT name, phone FROM searchResults WHERE email=:email";
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->prepare($sql);
$stmt->bindParam(":email", $_GET['email']);
$stmt->execute();
$row = $stmt->fetch();
$name = $row[0];
$number = $row[1];
echo $name;
echo $number;
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
?>
this is my javascript
var email = appSettings.getString("email");
var url = "https://adekunletestprojects.000webhostapp.com/skog/getMyname.php?search=" + encodeURIComponent(email);
fetch(url).then((response) => response.text()).then((res) => {
viewModel.set("myName", res.name);
alert(res.name);
appSettings.set("myNme", res.name);
appSettings.set("myNumber", res.number);
}).catch((err) => {
});
please help
You should return all the variables in a JSON object.
<?php
include 'config.php';
//$email = $_GET['email'];
try {
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$sql = "SELECT name, phone FROM searchResults WHERE email=:email";
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->prepare($sql);
$stmt->bindParam(":email", $_GET['email']);
$stmt->execute();
$row = $stmt->fetch();
$name = $row[0];
$number = $row[1];
echo json_encode(['name' => $name, 'number' => $number]);
} catch(PDOException $e) {
echo echo json_encode(['error' => ['text' => $e->getMessage() ]]);
}
?>
Then use response.json() to decode it in JavaScript.
var email = appSettings.getString("email");
var url = "https://adekunletestprojects.000webhostapp.com/skog/getMyname.php?search=" + encodeURIComponent(email);
fetch(url).then((response) => response.json()).then((res) => {
if (!res.error) {
viewModel.set("myName", res.name);
alert(res.name);
appSettings.set("myNme", res.name);
appSettings.set("myNumber", res.number);
} else {
alert(res.error.text);
}
}).catch((err) => {
Instead of echoeing the variables, always use JSON.
echo $name;
echo $number;
becomes
echo json_encode(["error"=>,"","name" => $name,"number"=>$number]);
also do the same thing for your error:
echo json_encode(['error' => $e->getMessage()]);

Stripe integration with composer not working on live server same works for localhost

I have integrated stripe using composer and passing values from previous payment file to stripe page and its working fine on local and creating payment on stripe user dashboard with custom values passed from files.While in live server with same secret key and publishable key getting error.And i have passed \Stripe\Stripe::setVerifySslCerts(false); before charge api it's still giving same error any help must be appreciated.
Stripe code:
function my_theme_send_email() {
if(isset($_POST['stripeToken'])){
$token = $_POST['stripeToken'];
$name = $_POST['name'];
$email = $_POST['email'];
$card_num = $_POST['card_num'];
$card_cvc = $_POST['cvc'];
$card_exp_month = $_POST['exp_month'];
$card_exp_year = $_POST['exp_year'];
$tutorName = $_POST['selectedTutor'];
$Subject = $_POST['slectedSubject'];
$selectedDates = $_POST['slectedDates'];
$selectedPrice = $_POST['slectedPrice'];
$priceplan = $_POST['packageName'];
$tutorid = $_POST['tutor_id'];
$student_id = $_POST['student_id'];
$currency_switcher = $_POST['currencyswitcher'];
include( get_template_directory() . 'STRIPE/init.php');
include( get_template_directory() . 'STRIPE/vendor/autoload.php');
//set api key
$stripe = array(
"secret_key" => "sk_test_Nf2k88X8CCoqJrkXwUft89xR",
"publishable_key" => "pk_test_1Lc32jHzjANsBUyPydlZ6iKK"
);
\Stripe\Stripe::setApiKey('sk_test_Nf2k88X8CCoqJrkXwUft89xR');
//add customer to stripe
$customer = \Stripe\Customer::create(array(
'email' => $email,
'source' => $token
));
//echo "<pre>";
//print_r($customer);
//item information
$itemName = $Subject;
$itemNumber = "PS123456";
// $currency = $_POST['currencyswitcher'];
$orderID = "SKA92712382139";
//charge a credit or a debit card
\Stripe\Stripe::setVerifySslCerts(false);
$charge = \Stripe\Charge::create(array(
'customer' => $customer->id,
'amount' => $_POST['packageName'],
'currency' => $_POST['currencyswitcher'],
'description' => $itemName,
'metadata' => array(
"order_id" => "SKA92712382139"
)
));
//echo "<pre>";
// print_r($charge);
//retrieve charge details
$chargeJson = $charge->jsonSerialize();
//check whether the charge is successful
if($chargeJson['amount_refunded'] == 0 && empty($chargeJson['failure_code']) && $chargeJson['paid'] == 1 && $chargeJson['captured'] == 1){
//order details
$amount = $chargeJson['amount'];
$balance_transaction = $chargeJson['balance_transaction'];
$currency = $chargeJson['currency'];
$status = $chargeJson['status'];
$date = date("Y-m-d H:i:s");
//include database config file
global $wpdb;
//insert tansaction data into the database
$sql = $wpdb->prepare("INSERT INTO wp_stripe_orders(name,student_id,tutor_id,tutor_name,email,card_num,card_cvc,card_exp_month,card_exp_year,item_name,item_number,item_price,item_price_currency,paid_amount,paid_amount_currency,package_plan,txn_id,order_id,payment_status,created,booked_date,modified) VALUES('".$name."','".$student_id."','".$tutorid."','".$tutorName."','".$email."','".$card_num."','".$card_cvc."','".$card_exp_month."','".$card_exp_year."','".$itemName."','".$itemNumber."','".$priceplan."','".$currency."','".$amount."','".$currency."','".$priceplan."','".$balance_transaction."','".$orderID."','".$status."','".$date."','".$selectedDates."','".$date."')");
$insert = $wpdb->query($sql);
//if order inserted successfully
if($insert && $status == 'succeeded'){
$statusMsg = "<h2>The transaction was successful.</h2><h4>Order ID: {$last_insert_id}</h4>";
}else{
$statusMsg = "Transaction has been failed";
}
}else{
$statusMsg = "Transaction has been failed";
}
}else{
$statusMsg = "Form submission error.......";
}
//show success or error message
$statusMsg;
}
add_action( 'init', 'my_theme_send_email' );

Validate login form with JS/PHP

I want to be able to either send a user to a restricted area or return some text that says Email and or password do not exist or something similar. I'm having trouble getting this to work as whether or not the email and password are correct NOTHING happens. I'm sending the form to the index page where the script to run this sits. Not sure why I'm not redirecting or getting any kind of errors.
The restricted page checks if a $_SESSION variable isset(), if not then send them back home.
JS
loginBtn.addEventListener('click', e => {
e.preventDefault();
ajaxRequests.login(`login_email=${ loginEmail.value }&login_password=${ loginPassword.value }`);
});
ajaxRequests.login()
login(formData) {
return new Promise((resolve, reject) => {
this.xhr.open('POST', '//localhost/mouthblog/', true);
this.xhr.send(formData);
this.xhr.onload = () => {
if (this.xhr.status == 200) {
resolve();
} else {
reject(this.xhr.statusText);
}
};
this.xhr.onerror = () => {
reject(this.xhr.statusText);
};
});
}
this is the script that is supposed to run when form is sent
if (isset($_POST['login_email']) && isset($_POST['login_password'])) {
$email = htmlentities($_POST['login_email'], ENT_QUOTES, 'ISO-8859-15');
$password = htmlentities($_POST['login_password'], ENT_QUOTES, 'ISO-8859-15');
$login = new Login($email, $password);
unset($login);
}
check for valid $_SESSION vars
session_start();
if (!isset($_SESSION['id']) || !isset($_SESSION['name']) || !isset($_SESSION['email'])) {
header('Location: index.php');
}
login query (just incase it is needed)
class Login extends Connection {
public function __construct($email, $password) {
$this->connect();
$sql = "SELECT `id`, `name`, `email`, `password` FROM `users` WHERE `email`=:email";
$query = $this->connect()->prepare($sql);
$result = $query->execute(
[
':email' => htmlentities($email, ENT_QUOTES, 'ISO-8859-15'),
]
);
// check if EMAIL exists
if ($result) {
$row = $query->fetch(PDO::FETCH_OBJ);
$id = htmlentities($row->id, ENT_QUOTES, 'ISO-8859-15');
$name = htmlentities($row->name, ENT_QUOTES, 'ISO-8859-15');
$email = htmlentities($row->email, ENT_QUOTES, 'ISO-8859-15');
$hashed_password = htmlentities($row->password, ENT_QUOTES, 'ISO-8859-15');
// check if user input PASSWORD matches the unhashed PASSWORD in the database
if (password_verify($password, $hashed_password)) {
$_SESSION['id'] = htmlentities($id, ENT_QUOTES, 'ISO-8859-15');
$_SESSION['name'] = htmlentities($name, ENT_QUOTES, 'ISO-8859-15');
$_SESSION['email'] = htmlentities($email, ENT_QUOTES, 'ISO-8859-15');
header('Location: blog_roll.php');
} else {
header('Location: index.php');
}
} else {
echo 'THAT EMAIL ADDRESS DOES NOT EXIST';
}
}
}
You have to set the content type for your ajax request
this.xhr.open('POST', '//localhost/mouthblog/', true);
this.xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
this.xhr.send(formData);

Differ PhpMailer in AngularJS foreach

I have problems :
My code for emailing is working, but I don't think its the right way to do so. Is it possible to use the $http service inside an AngularJS foreach loop? Will it overheat the process, if each loop is destined to PhpMailer to send one mail each time? Should I use the $q service? The code works to send a low amount of emails but will it overheat the php script if more emails are sent?
AngularJS code
$scope.submit = function(contactform) {
$scope.submitted = true;
$scope.submitButtonDisabled = true;
angular.forEach($scope.intervenants,function(data){
var x = angular.copy($scope.formData);
x.destinataire = data.email;
$http({
method : 'POST',
url : 'contact-form.php',
data : $.param(x), //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';
}
});
});
}
PhpMail code
//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->IsSMTP();
$mail->Host = "smtp.orange.fr";
$mail->From = $_POST['inputEmail'];
$mail->FromName = $_POST['inputName'];
$mail->AddAddress($_POST['destinataire']); //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);
}

Categories

Resources