I've been trying to grab a username based on registered email when user enters his email and click on a button I've provide two data to my ajax request first is [cf] which identify which portion of code should be processed and second is the email but when clicking the button nothing happens and no errors appear in the console only when I open the page that have the php code of ajax request it says "Notice: Undefined variable: funcCall in D:\XAMPP\htdocs\lahj\framework\signin.php on line 19"
Here I will provide my code for ajax:
$("#login-next-btn").click(function(){
if(!$("#signin-email").val().trim()){
var email = $("#signin-email").val().trim();
$.ajax({
url: "framework/signin.php",
type: "POST",
data: {cf:'cf1',email:email},
dataType:"json",
success: function(data){
if(data.result != "0")
{
alert("helo");
$("#signin-box-header p:first-of-type").text("مرحبًا");
$("#signin-box-header p:last-of-type").remove();
$("#signin-box-header").append("<p id='sigin-email-display'>"+data.result+"</p>");
$("#first-loader").fadeOut(600,function(){
$("#second-loader").css({"display":"flex"}).fadeIn(400);
});
}
else
{
alert("fail");
}
}
});
}
});
and here is my php code in a file called signin.php in a folder called framework:
<?php
ini_set( 'error_reporting', E_ALL );
ini_set( 'display_errors', true );
include_once 'db.php';
$email = null;
$funcCall = null;
if(isset($_POST['email']))
{
$email = $_POST['email'];
}
if(isset($_POST['cf']))
{
$funcCall = $_POST['cf'];
}
if($funcCall == 'cf1' && !empty($email))
{
try
{
$database = new db();
$db = $database->openConnection();
$stmt = $db->prepare("select userName from khUsers where email = ?");
$stmt->execute(array($email));
$usersName = $stmt->fetchColumn();
$data = array('result' => $usersName);
echo json_encode($data);
}
catch (PDOException $e)
{
echo "There is some problem in connection: " . $e->getMessage();
$data = array('result' => "0");
echo json_encode($data);
}
}
?>
Add exit() function at the end of json_encode() function. it will show you result/error on your request in console.
if($funcCall == 'cf1' && !empty($email))
{
try
{
$database = new db();
$db = $database->openConnection();
$stmt = $db->prepare("select userName from khUsers where email = ?");
$stmt->execute(array($email));
$usersName = $stmt->fetchColumn();
$data = array('result' => $usersName);
echo json_encode($data); exit();
}
catch (PDOException $e)
{
echo "There is some problem in connection: " . $e->getMessage();
$data = array('result' => "0");
echo json_encode($data); exit();
}
}
Related
I am doing a custom script to restrict a private website, user need access-code and their last name to access the website. The Webiste made with WordPress while the restrict credentials was from an external php application.
I have two files one is home.php and another is autho.php. The login form is in home.php where the form and Ajax code written their. The autho.php is the server-side script and creating the session to restrict WordPress site.
The session validation happening at /wp-content/themes/twentynineteen/header.php file. At the area of wordpress site I cannot able to find the session data which was created at autho.php. Please suggest.
home.php (login form)
<script type='text/javascript'>
$(document).ready(function(){
$('#login_error').hide();
$('#accessform').on('submit', function(event){
event.preventDefault();
$.ajax({
url:"doctor_autho.php?action=login&type=login",
method:"POST",
data:$(this).serialize(),
dataType:"json",
beforeSend:function(){
$('#submit').attr('disabled', 'disabled');
},
success:function(data)
{
if(data.result = 'false')
{
$('#login_error').show();
$('#login_error').html("<strong> Doctors last name or code is invalid </strong>");
$('#submit').prop('disabled', false);
}
if(data.result = 'true')
{
$('#login_error').show();
$('#login_error').html("<strong> Access Granted !!! </strong>");
window.location.href = "/index.php");
}
$('#submit').attr('disabled', false);
},
error: function (response) {
$('#login_error').show();
$('#login_error').html("<strong> Doctors last name or code is invalid </strong>");
$('#submit').prop('disabled', false);
}
})
});
});
</script>
autho.php PHP file
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
$type = isset($_GET['type'])?$_GET['type']:"";
$action = isset($_GET['action'])?$_GET['action']:"";
if(isset($_POST) && $action == "login" && $type=="login"){
$doctor_invitation_code= isset($_POST['doctor_invitation_code'])?$_POST['doctor_invitation_code']:"";
$doctor_last_name= isset($_POST['doctor_last_name'])?$_POST['doctor_last_name']:"";
if($doctor_invitation_code =="" OR $doctor_last_name ==""){
$data = array("result" => "false", "msg" => "Parameter is required");
die(json_encode($data));
}else{
check_login($doctor_invitation_code,$doctor_last_name);
}
}else{
$data = array("result" => "false", "msg" => "Parameter wrong used!");
die(json_encode($data));
}
function check_login($doctor_invitation_code,$doctor_last_name){
Global $conn;
$doct_auto_query ="SELECT * FROM `tbl_user_master` WHERE patient_invition_code='".$doctor_invitation_code."' AND user_lname='".$doctor_last_name."' AND user_type='2' and is_deleted=0 limit 1";
//echo $doct_auto_query;
$result = $conn->query($doct_auto_query);
if($result->num_rows > 0){
$data = array("result" => "true", "msg" => "Access Granted !!!");
session_start();
$_SESSION['invitation_code'] = $doctor_invitation_code;
$_SESSION['last_name'] = $doctor_last_name;
die(json_encode($data));
}else{
$data = array("result" => "false", "msg" => "The Invitation code or Last Name is wrong used!");
header ("Location: home.php");
die(json_encode($data));
}
}
Session validation on theme's header.php file
session_start();
if (!isset($_SESSION['invitation_code']) && !isset($_SESSION['last_name']) ) {
header("Location: https://www.website.com/home.php");
}
At WordPress site under the theme header file I cannot able to access $_SESSION['invitation_code'] and $_SESSION['last_name'] there, please suggest how to fix this.
At First Put the session_start(); at wp-config.php file.
define( 'WP_SESSION_USE_OPTIONS', true );
session_start();
Your JQuery something like this
<script type='text/javascript'>
$(document).ready(function(){
$('#login_error').hide();
$('#accessform').on('submit', function(event){
event.preventDefault();
$.ajax({
url:"autho.php?action=login&type=login",
method:"POST",
data:$(this).serialize(),
dataType:"json",
beforeSend:function(){
$('#submit').attr('disabled', 'disabled');
},
success:function(data)
{ console.log(data);
if(data.result =="true") {
$('#login_error').show();
$('#login_error').html("<strong> "+data.msg+" </strong>");
window.location.href = "index.php";
return false;
}
if(data.result == "false") {
$('#login_error').show();
$('#login_error').html("<strong> "+data.msg+" </strong>");
$('#submit').prop('disabled', false);
return false;
}
$('#submit').attr('disabled', false);
},
error: function (response) {
$('#login_error').show();
$('#login_error').html("<strong> There is an error! </strong>");
$('#submit').prop('disabled', false);
}
})
});
});
</script>
Your PHP code something like this
<?php
$con = mysqli_connect("127.0.0.1","dbuser","dbpassword","dbname");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
$doctor_last_name = mysqli_real_escape_string($con, $_POST['doctor_last_name']);
$password = mysqli_real_escape_string($con, $_POST['doctor_invitation_code']);
if($doctor_last_name !="" && $password !=""){
$query ="SELECT * FROM `tbl_user_master` WHERE is_deleted=0 AND user_type='2' ";
if($doctor_last_name !=""){
$query .=" AND user_lname='".$doctor_last_name."' ";
$data=mysqli_query($con, $query);
if ($data){
if (mysqli_num_rows($data) == 0){
$data = array("result" => "false", "msg" => "The Last Name is invalid.");
}
}
}
//end
//validation for invitation code
if($password !=""){
$query .=" AND patient_invition_code='".$password."' ";
$data=mysqli_query($con, $query);
if ($data){
if (mysqli_num_rows($data) == 0){
$data = array("result" => "false", "msg" => "The Invitation Code is invalid.");
}
}
}
$data=mysqli_query($con, $query);
if ($data){
if (mysqli_num_rows($data) > 0){
session_start();
$_SESSION['invitation_code'] = $password;
$_SESSION['last_name'] = $doctor_last_name;
$data = array("result" => "true", "msg" => "Access Granted !!!");
echo json_encode($data);
exit();
}else {
//validation of code and lastname only
$data = array("result" => "false", "msg" => "The Last name & Invitation Code is invalid.");
echo json_encode($data);
exit();
}
}
}else{
$data = array("result" => "false", "msg" => "Parameter is required.");
echo json_encode($data);
exit;
}
reset($doctor_last_name);
reset($password);
mysqli_close($con);
exit;
?>
And Lastly you can put session validation in any header file of your WordPress theme.
session_start();
if(!isset($_SESSION['invitation_code']) || $_SESSION['invitation_code'] == '') {
header('location:home.php');
}
Here is my api code for search data by pin code:
function findPlace(){
$request = \Slim\Slim::getInstance()->request();
$pinCode = json_decode($request->getBody());
try {
if(1){
$vendorSearchData = '';
$db = getDB();
$sql = "SELECT vendor_name,logo,phone_no FROM vender_list WHERE post_code LIKE :post_code";
$stmt = $db->prepare($sql);
$stmt->bindParam("post_code", $pinCode, PDO::PARAM_STR);
$stmt->execute();
//echo "<pre>"; print_r($stmt); echo"</pre>";die;
$vendorSearchData = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
if($vendorSearchData)
echo '{"vendorSearchData": ' . json_encode($vendorSearchData) . '}';
else
echo '{"vendorSearchData": ""}';
} else{
echo '{"error":{"text":"No access"}}';
}
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
Here is the file, where I call function to find data. If its true, then will navigate to another page, but on that page I get blank page:
findPlace(searchVal){
this.authService.postData(this.vendorSearchPostData, "findPlace")
.then((result) => {
this.responseData = result;
if (this.responseData.vendorSearchData) {
this.dataSet = this.responseData.vendorSearchData;
this.navCtrl.push(SearchResultPage, { data: searchVal});
} else {
let toast = this.toastCtrl.create({
message: "No data Found",
duration: 2000
});
toast.present();
}
}, (err) => {
});
}
How display the search result on another page?
So I have these codes wherein I want a notification to appear in every event. I want to check if the record exists, then a notification will appear, saying the college already exists. But that doesn't happen tho. I keep on inputting duplicate input, but the notification still says it's successful. Is there a mistake in my code?
add-college.php
<?php
function findDuplicate($code) {
try {
include($_SERVER['DOCUMENT_ROOT']."/config/db-config.php");
$sql = "SELECT * FROM colleges WHERE collegecode = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $code);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows > 0) {
return true;
}
else {
return false;
}
}
catch (Exception $e) {
return false;
}
}
try {
include($_SERVER['DOCUMENT_ROOT']."/config/db-config.php");
$code = $_POST['code'];
$name = $_POST['name'];
$result = array();
if (findDuplicate($code)) {
$result['message'] = 'duplicate';
}
else {
$sql = "INSERT INTO colleges(collegecode, collegename) VALUES(?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $code, $name);
if ($stmt->execute()) {
$result['message'] = 'success';
}
else {
$result['message'] = 'error';
}
}
echo json_encode($result);
}
catch (Exception $e) {
echo json_encode($result);
}
?>
script.js
$("#save-new").click(function() {
var form = $("#add-college");
var code = $("#code").val();
var name = $("#name").val();
$.ajax({
type: "POST",
data: {
code: code,
name: name
},
url: "../ajax/add-college.php",
dataType: "html",
success: function(data) {
if (data.message = "success") {
$.notify({
// options
message: 'College has been added.'
},{
// settings
type: 'success'
});
}
else if (data.message = "duplicate") {
$.notify({
// options
message: 'College already exists.'
},{
// settings
type: 'warning'
});
}
else {
$.notify({
// options
message: 'College cannot be added.'
},{
// settings
type: 'error'
});
}
$("#code").val("");
$("#name").val("");
$("#add-new").modal('hide');
showColleges();
}
});
});
data.message = "success" this is assignment operation, if you want to compare two string use == operator.
So, the correct statement would be for the if condition would be if(data.message == "success")
Similarly, if(data.message == "duplicate"). I am sure you are aware of all this!
What I'm trying to do is calling some database data via ajax and php. But the ajax call doesn't work, and I can't find out a solution on the web.
So here is my code:
test.php
<?php
include_once 'db_class.php';
$cat = $_GET['cat'];
$dbconn = new dbconn('localhost', 'root', 'somepsw', 'blog');
$dbconn->set_query("select * from posts where category = '".$cat."'");
echo '<br/>'.$dbconn->query.'<br/>';
$result = $dbconn->result;
$num = $dbconn->num_results;
$array = mysqli_fetch_assoc($result);
echo json_encode($array);
?>
If i type that url on browser: http://127.0.0.1:82/blog/ws/test.php?cat=css
The data returned via jsonEncode is correct, but when i'm loading it on a html page with jquery he can't read the data.
test.html
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script>
function ajaxCall() {
var css;
$.ajax({
url: 'test.php',
type: "GET",
data: {cat: css},
dataType: 'json',
success: function(rows)
{
alert(rows);
},
error: function() { alert("An error occurred."); }
});
}
ajaxCall();
</script>
</head>
<body></body>
</html>
Thanks in advance.
I just rewrote the php code using PDO, should be more safe now.
db.php
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpsw = "somepsw";
$dbname= "blog";
try {
#$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpsw);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch(PDOException $e) {
echo "Connection failed, an error occured! Please contact server administrator."; //user friendly message
getErrorsLog($e->getMessage());
}
function closeDbConn () {
$dbh = null;
}
function getErrorsLog($message) {
$file = 'dberrors.log';
$date = date("d/m : H:i :");
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new error message to the file
$current .= $date.$message;
$current .= "\r\n";
// Write the contents back to the file
file_put_contents($file, $current);
exit();
}
?>
blogdata.php
<?php
include_once "db.php";
$tableName = "posts";
$data = array();
#$view = $_GET["view"];
if (isset($_GET["view"])) {
$stmt = $dbh->prepare("SELECT * FROM $tableName WHERE category =? ORDER BY created DESC");
}
else {
try {
$stmt = $dbh->prepare("SELECT * FROM $tableName ORDER BY created DESC");
}
catch (PDOException $e) {
getErrorsLog($e->getMessage());
}
}
$stmt->bindValue(1, $view, PDO::PARAM_STR);
$stmt->execute();
$affected_rows = $stmt->rowCount(); //Rows count
if ($affected_rows == 0) {
echo "The data you looking for no longer exist, please contact the administrator.";
exit();
}
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
$data[] = $row;
}
echo json_encode($data);
closeDbConn();
?>
Your variable css has no value. You wanted to use the string 'css'. Maybe you want to be able to load other categories, too. So change your ajaxCall function to
function ajaxCall(category)
{
$.ajax({
url: 'test.php',
type: "GET",
data: {cat: category},
dataType: 'json',
success: function(rows) {
alert(rows);
},
error: function() {
alert("An error occurred.");
}
});
}
and call it using
ajaxCall('css');
I have a issue with my ajax form submission.I am dynamically submitting a form and using php at the server side to process it.This is the ajax success function.
$.ajax({
type: "POST",
url: "register.php",
data: "uname="+uname+"&eid="+eid+"&pwd="+pass+"&cpwd="+cpass+"&country="+coun+"&contact="+contact,
dataType: "html",
success: function(data){
if(data!="error")
{
//alert(data);
$("#user_status", window.parent.document).html("Welcome "+data+" | <a href='forum/logout.php'>Logout</a>");
if(window.parent.document.getElementById('post_user_name'))
$("#post_user_name", window.parent.document).html(msg);
parent.$.fancybox.close();
}
if(data=="error")
{
//alert(data);
$("#status").html("<span><center><font class='formright err_msg' style='width:176px;'>The user is already register with us.</font><center></span>");
return false;
}
Now if the user is valid he is logged in and f not there has to be an error like "Already exists".The valid part works fine but for invalid I return an error from the php file but still my error message doesn't show up and just error is printed on the screen.I am using fancybox for my forms(jquery fancybox)
PHP code is
if($_POST['pwd']==$_POST['cpwd'])
{
$username = $_POST['uname'];
$email = $_POST['eid'];
$password = md5($_POST['pwd']);
$cpassword = $_POST['cpwd'];
$contact_no = $_POST['contact'];
$country = $_POST['country'];
$cnt = $checkUser['cnt'];
if($cnt!=0)
{
echo "error";
//exit;
/*$_SESSION['error_msg'] = 'Email Address already exists';
redirect_to_link("index.html");*/
}
else
{
//echo "entered here";
$userArray = array();
//$user = return_post_value($_POST['uname']);
$userArray['uname'] = return_post_value($_POST['uname']);
$userArray['email'] = return_post_value($_POST['eid']);
$userArray['password'] = md5(return_post_value($_POST['pwd']));
$userArray['contact_no'] = return_post_value($_POST['contact']);
$userArray['country'] = return_post_value($_POST['country']);
//print_r($userArray);
//exit;
$userObj->addUserValue($userArray);
$_SESSION['username']= $userArray['uname'];
echo $userArray['uname'];
// return $user;
}
The echo $userArray['uname']; part works but echo "error" doesn't.Checked in Firebug response header,i can see the error word returned.
Can anyone throw some light on it?
Thanks
Use this to compare if($.trim(data)!="error")
And don't recheck for if($.trim(data)=="error")
use
if($.trim(data)!="error")
{
//
}
else{
//
}