Create Instance of PHP object from AJAX call - javascript

I'm playing with using AJAX to perform a simple login function using PHP. I haven't been able to get the AJAX call to successfully create an instance of the Controller class in the login handler file. I feel like I'm just not seeing something that is really basic.
I want to just say thank you in advance for any help! Also, this is not meant to be a real website or a real login script. I understand there are SO many security holes the way it is currently written. I fully intent to add all the bells, whistles, validation, etc. necessary to turn this simple code into something useful as soon as I understand the mistake.
The 4 files that should communicate with each other are as follows:
view/login.php
function signIn( )
{
if(checkString( ))
{
$.ajax({
type: "POST",
url: "ajax.php",
data: "username=" + $("#username").val( ) + "&password=" + $("#password").val( ),
dataType: "html",
async: false,
cache: false,
success: function(result){
$("#temp_container").html(result);
}
});
}
}
AJAX.php
<?php
if(isset($_POST['username']) && !empty($_POST['password']))
{
$controller = new IndexController( );
$result = $controller->login($_POST['username'], $_POST['password']);
if($result > 0)
$user_validation = array('true', 'view/chat_app.php');
else
$user_validation = array('false', 'index.php?error_num=1');
echo json_encode($user_validation);
}
else if(isset($_POST['username']) && empty($_POST['password']))
{
//notify the user they didn't put in a password
}
?>
Controller.php
<?php
include_once("model/indexModel.php");
class IndexController
{
public $model;
public function __construct( )
{
$model = new IndexModel( );
}
public function login($username, $password)
{
$result = $model->login($username, $password);
if($result >= 1)
return true;
else
return false;
}
}
?>
Model.php
<?php
include_once("config/config.php");
$db = new mysqli($GLOBALS['config']['db_host'], $GLOBALS['config']['db_username'], $GLOBALS['config']['db_password'], $GLOBALS['config']['db_name']);
class IndexModel
{
public function login($username, $password)
{
global $db;
$statement = $db->prepare("SELECT 1 FROM authorized_users
WHERE username = ?
AND password = ?");
$statement->bind_param('ss', $username, $password);
$statement->execute( );
$statement->close( );
return $statement->affected_rows;
}
}
?>

Related

Requesting data from php through ajax

Trying to request the posts made by users and loading more posts on user's request.
Getting Unexpected end of JSON input error while making ajax request in console.
Javascript
$("#ajax_load_more").click(function(){
$.ajax({
type: "GET",
url: "action.php?action=morePosts",
success: function(response){
var result = $.parseJSON(response);
console.log(result);
}
});
});
Making request to following code.
$_SESSION['posts']) stores the number of posts to be loaded in the session.
if($_GET['action']=="morePosts"){
if(isset($_SESSION['posts'])){
$_SESSION['posts'] = $_SESSION['posts'] + 4;
echo fetchAllPosts($_SESSION['posts']);
} else if(isset($_SESSION['posts'])&& $_SESSION['posts']>4){
$_SESSION['posts'] = 4;
}
}
Function for requesting all posts
function fetchAllPosts2($array_length){
$db = new db; //Class for database
$query = "SELECT * FROM `posts` ORDER BY `post_id` DESC LIMIT $array_length";
$result = $db::query($query);
$row = mysqli_fetch_all($result);
$post = array();
for($i=0; $i<$array_length; $i++){
if(!empty($row[$i])){
for($j=0;$j<count($row);$j++){
$post['id']=$row[$i][0];
$post['user_id']=$row[$i][1];
$post['title']=substr($row[$i][2], 0 ,75);
$post['text']=strip_tags(mb_substr($row[$i][3],0,50));
$post['image']=$row[$i][4];
$post['date']=$row[$i][5];
}
return json_encode($post);
}
elseif(empty($row[count($row)])){
return json_encode(array());
}
}
}
Please suggest better ways of achieving this functionality,
Try to use echo instead of return and change ajax like also you din not echo the code inside elseif part:
$("#ajax_load_more").click(function(){
$.ajax({
type: "GET",
dataType: "json",
url: "action.php?action=morePosts",
success: function(response){
console.log(response);
}
});
});
try this :
function fetchAllPosts2($array_length){
$db = new db; //Class for database
$query = "SELECT * FROM `posts` ORDER BY `post_id` DESC LIMIT $array_length";
$result = $db::query($query);
$row = mysqli_fetch_all($result);
$post = array();
if($result && mysqli_num_rows($result) > 0) {
foreach($row as $key=>$value){
$post[$key]['id']=$value['id'];
$post[$key]['user_id']=$value['user_id'];
$post[$key]['title']=substr($value['title'], 0 ,75);
$post[$key]['text']=strip_tags(mb_substr($value['text'],0,50));
$post[$key]['image']=$value['image'];
$post[$key]['date']=$value['date'];
}
return json_encode($post);
}
return json_encode(['error'=>"no post found"]);
}

[Ajax][PHP] - login form, response is always empty

I have a problem with my login form. Every time when i write (correct or incorrect) login and password in my login form, my JS script return error and when i try to print "response" it is empty.
Can anyone help?
$(document).ready(function(){
$("#submit").click(function(e){
e.preventDefault();
var name = $("#name").val().trim();
var paw = $("#paw").val().trim();
$.ajax({
url: 'check.php',
type: 'POST',
data: {name:name, paw:paw},
success: function(response){
if(response == 1){
window.location= "home.php";
}
else{
alert("error");
}
}
});
});
});
<?php
session_start();
require_once 'dbconfig.php';
error_reporting(E_ALL ^ E_NOTICE);
if(isset($_POST['submit']))
{
$name = trim($_POST['name']);
$paw1 = trim($_POST['paw']);
$paw = md5($paw1);
try {
$stmt = $pdo->prepare("SELECT * FROM user WHERE login=:nazwa and haslo=:has");
$stmt->execute(array(':nazwa'=>$name, ':has'=>$paw));
$count = $stmt->rowCount();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if($row['haslo']==$paw){
echo 1;
$_SESSION['user_session'] = $row['login'];
}
else {
echo 0;
}
} catch (\Exception $e) {
echo $e->getMessage();
}
}
?>
Remove the if(isset($_POST['submit'])) line. The reason is that the button key value is not sent via the AJAX call. To verify, do a print_r($_POST);
instead verify that name and password variables are not empty()
if (!empty($_POST['name']) && !empty($_POST['paw'])) {
}
Also do not use md5() for your passwords. use php's password_hash() to hash and password_verify() to verify that the posted password via the form matches the hash stored in the database for that user.

Wordpress wp_signon() do not work in ajax call

I am trying to build an costum login to Wordpress in a AJAX call. I a remove the wp_signon() from the PHP function I do get the right echo. But then I add the wp_signon() it always return my whole login page in HTML. I can't see what I am doing wrong. And can't get the login to work.
Please help!
js
$.ajax({
method: 'POST',
url: '/wp-admin/admin-ajax.php',
dataType: 'json',
data: {
'action': 'getLoggedIn',
'user_name': user_name,
'user_password': user_password,
'user_remember': user_remember
},
success: function(response) {
if (response === 'ok') {
window.location = '/app/';
}
},
error: function(){}
});
PHP
function getLoggedIn() {
global $wpdb;
// Check if users is already logged in
if ( is_user_logged_in() ) {
echo 'You are already logged in';
die;
}
//We shall SQL escape all inputs
$username = $wpdb->escape($_REQUEST['user_name']);
$password = $wpdb->escape($_REQUEST['user_password']);
$remember = $wpdb->escape($_REQUEST['user_remember']);
$creds = array();
$creds['user_login'] = $username;
$creds['user_password'] = $password;
$creds['remember'] = $remember;
$user_signon = wp_signon( $creds, false );
// Check if error
if ( is_wp_error($user_signon)) {
echo $user_verify->get_error_code();
exit();
} else {
echo 'ok';
exit;
}
die();
}
add_action('wp_ajax_getLoggedIn', 'getLoggedIn');
add_action('wp_ajax_nopriv_getLoggedIn', 'getLoggedIn');
The problem was not the wp_signon() function. It was an other Wordpress action that redirects the page after user login has failed. This:
add_action( 'wp_login_failed', 'login_failed' );
I got caught up in the same situation. did you remove that wp_login_failed action or how did you work this out?

Ajax failed registration do not echo result

I have a an ajax post method that if success will alert "account successfully created". my problem is when it's not created it should alert account already exists, But what the problem it still alert the same.
script code:
$(document).ready(function(){
$("#btn-register").click(function(){
var regaccount = $("#regaccount").val();
var regpass = $("#regpass").val();
if((regaccount == "") || (regpass == "")){
alert("Information required!");
}else {
$.ajax({
type: "POST",
url: "register.php",
data: "regaccount="+regaccount+"&regpass="+regpass,
success: function(data){
alert("account successfully created!");
},
error:function(){
alert("account already exists");
}
});
}
$("#regaccount").val('');
$("#regpass").val('');
return false;
});
});
register.php
<?php
include 'function.php';
session_start();
ob_start();
$userid = rand(100000, 999999);
$regaccount = $_POST['regaccount'];
$regpass = $_POST['regpass'];
$regaccount = stripslashes($regaccount);
$regpass = stripcslashes($regpass);
$salt = "dctech2015ABcRXd";
$regpass = md5($regpass) . $salt;
$regpass = sha1($regpass);
$con = new Functions();
$con = $con->db;
$stmt = $con->query("SELECT * FROM users WHERE username = '$regaccount'");
$count = $stmt->rowCount();
if($count != 1){
$con = new Functions();
$con = $con->db;
$status="Offline";
$stmt = $con->prepare("INSERT INTO users(user_id, username, password, status)VALUES(:userid, :account, :password, :status)");
$stmt->bindValue(':userid', $userid);
$stmt->bindValue(':account', $regaccount);
$stmt->bindValue(':password', $regpass);
$stmt->bindValue(':status', $status);
$stmt->execute();
}else{
echo '<script>alert("account name already exists");</script>';
}
ob_end_flush();
?>
You need to do following changes to make this work:
1) In your PHP code, do not write any alert.
2) Whether user exists in database or newly inserted, AJAX request will fetch only data. We have to handle the logic.
3) AJAX error method will be called only when AJAX request is failed (either request not sent or response status is not 200 OK).
4) In your case, error method will never be called if user already exists or even user is inserted as data is being correctly transferred from JavaScript to PHP.
if($count != 1){
$con = new Functions();
$con = $con->db;
$status="Offline";
$stmt = $con->prepare("INSERT INTO users(user_id, username, password, status)VALUES(:userid, :account, :password, :status)");
$stmt->bindValue(':userid', $userid);
$stmt->bindValue(':account', $regaccount);
$stmt->bindValue(':password', $regpass);
$stmt->bindValue(':status', $status);
$stmt->execute();
echo 'success';
}
else{
echo 'exists';
}
AND
$.ajax({
type: "POST",
url: "register.php",
data: "regaccount="+regaccount+"&regpass="+regpass,
success: function(data){
if (data == 'success') {
alert("account successfully created!");
}
else if (data == 'exists') {
alert("account already exists");
}
},
error:function(){
alert("Unknown problem occured.");
}
});
Here you are trying to prompt message into AJAX error section which is wrong. You need to handle both into success section.
The very simple example is, return $count and check that value if greater then 0 means record is exist.
Changes in register.php code:
if($count != 1){
$con = new Functions();
$con = $con->db;
$status="Offline";
$stmt = $con->prepare("INSERT INTO users(user_id, username, password, status)VALUES(:userid, :account, :password, :status)");
$stmt->bindValue(':userid', $userid);
$stmt->bindValue(':account', $regaccount);
$stmt->bindValue(':password', $regpass);
$stmt->bindValue(':status', $status);
$stmt->execute();
}
echo $count;
I remove else part which is not require. And use $count for AJAX response.
And make correspond change into AJAX part also:
$.ajax({
type: "POST",
url: "register.php",
data: "regaccount="+regaccount+"&regpass="+regpass,
success: function(data){
//If record exist...
if(data > 0){
alert("account name already exists");
}
else {
alert("account successfully created!");
}
},
error:function(){
alert("There is some error, Please try after some time OR contact site admin.");
}
});
Hope this is very easy to understand and help to other user also.

Codeigniter ajax call error

I'm trying to make an ajax call to get result from my database, but i'm facing an error.
My javascript:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script language="Javascript">
setTimeout(makeAjaxCall, 1000);
function makeAjaxCall(){
$.ajax({
type: "post",
url: "call/update",
cache: false,
data: {action: 'getUpdate', term: '<?php echo $id;?>'},
success: function(json){
try{
var obj = jQuery.parseJSON(json);
alert( obj['STATUS'] + obj['results']);
}catch(e) {
alert('Exception while request..');
}
},
error: function(){
alert('Error while request..');
}
});
}
</script>
And my controller's method:
public function update()
{
if (isset($_POST['action'])){
if ($_POST['action'] == 'getUpdate'){
pollNewData();
}
}
function pollNewData(){
$term = $_POST['term'];
$query = $this->db->query("SELECT * FROM users where guid <> '' and user_id = '$term'");
$res = $query->result();
echo json_encode(array('STATUS'=>200, 'results'=>$res));
}
}
i have this error on chrome debugs tool:
500 (Internal Server Error)
You have several issues. Below is the working code:
public function update()
{
if(!function_exists('pollNewData')){ // don't redeclare if already exists
function pollNewData($db){ // pass $db
$term = $_POST['term'];
$query = $db->query("SELECT * FROM users where guid <> '' and user_id = '$term'");
$res = $query->result();
echo json_encode(array('STATUS'=>200, 'results'=>$res));
}
}
if (isset($_POST['action'])){
if ($_POST['action'] == 'getUpdate'){
pollNewData($this->db); // pass $this->db
}
}
}
Changes:
Moved the function definition to before it is called - it must exist before calling.
The $this context is not set in the function, so pass the $db object as an argument.
When defining functions inside a class method, you must have a function_exists() check because on the second call, it will try to redeclare the function and produce a fatal error.
For future debugging you should turn errors on:
error_reporting(E_ALL);
ini_set('display_errors', '1');
Some suggestions:
url: "<?php echo base_url();?>call/update",
//pollNewData();
echo $this->pollNewData(); //call like this and echo it out to the ajax
//echo json_encode(array('STATUS'=>200, 'results'=>$res));
return json_encode(array('STATUS'=>200, 'results'=>$res)); //return it instead to the calling function

Categories