How to login with session using Angular? - javascript

login.js
$http({
url: 'http://ipadress/login.php',
method: 'POST',
data: {
'var_id': $scope.form.txt_id,
'var_pass': $scope.form.txt_pass
}
}//http
login.php
<?php
session_start();
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
mysql_connect("localhost","root","password");
mysql_select_db("db");
$data = file_get_contents("php://input");
$dataJsonDecode = json_decode($data);
$var_id = $dataJsonDecode->var_id;
$var_pass = $dataJsonDecode->var_pass;
$sql = "SELECT * FROM user WHERE user_login = '".($id)."' and user_pass = '".md5($pass)."'";
$query = mysql_query($sql);
$result = mysql_fetch_array($query);
$resource = mysql_query($sql);
$count_row = mysql_num_rows($resource);
if (!$result) {
$results = '{"results":"not match"}';
} else {
$_SESSION["users_login"] = $result["users_login"];
session_write_close();
if($count_row > 0){
$results = '{"results":"match"}';
} else {
$results = '{"results":"Error"}';
}
}
echo $results;
?>
$http.get('http://ipaddress/data_user.php')
.then(function (response) {
console.log(response.data.results);
$scope.myData = response.data.results;
}, function (error) {
console.log(error);
});
user_data.php
<?php
session_start();
if($_SESSION['users_login'] == ""){
$results = '{"results":"Please Login"}';
echo $results;
}
else{
mysql_connect("localhost","root","password");
mysql_select_db("db");
mysql_query( "SET NAMES UTF8" );
$sql = "SELECT * FROM users WHERE users_login = '".$_SESSION["users_login"]."' ";
$query = mysql_query($sql);
$count_row = mysql_num_rows($query);
if($count_row > 0){
while($result = mysql_fetch_array($query)){
$rows[] = $result;
}
$data = json_encode($rows);
$totaldata = sizeof($rows);
$results = '{"results": '.$data.'}';
}
echo $results;
}
?>
I have problem with login. My $results = please login.

First check what $result["users_login"] contains..
You are getting the please login because you don't have the session data.
I am not sure about your approach, but don't mix php session and Ionic, You can create a kind of API to check user credentials from your ionic App, or else handle it in the ionic app.
Session normally used in websites to pass data through out the page, not for API calls. Think of scenario 10 users access your app simultaneously, How you going to use the Session to verify them?
My advise is, instead of using PHP sessions, you can handle your sessions inside your app using the session storage
Read this. There are plenty of plugin available. OR you can create your as shown here
Good Luck!!

Related

Can'r Fetch data from database using Axios

I want to fetch data from database but can't get it and when I console print it, is just empty.
Is there something wrong with my code?
function har() {
axios.get(url2, {
headers: {
'X-RapidAPI-Key': 'your-rapidapi-key',
'X-RapidAPI-Host': 'body-mass-index-bmi-calculator.p.rapidapi.com',
},
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.error(error);
});
}
This is my my php code
<?php
include 'db.php';
$emparray = array();
$sql = 'SELECT * FROM schedule_list';
$results = mysqli_query($conn,$sql);
while($row = $results->fetch_assoc()){
$emparray[] = $row;
}
$hey = json_encode($emparray)
?>
I just want to get the data from the json encode to javascript without using react or vue, just plain vanilla javascript
You aren't outputting anything in your server code. Try instead to output the results like:
<?php
include 'db.php';
$emparray = array();
$sql = 'SELECT * FROM schedule_list';
$results = mysqli_query($conn,$sql);
while($row = $results->fetch_assoc()){
$emparray[] = $row;
}
echo json_encode($emparray);
?>

JSON/PHP/MYSQL login connection error

I'm new to PHP programming and I'm trying to test out a login page alongside JSON and MySQL. I managed to make most of it functional but I can't seem to find a way to make the query in which I verify the username and password to work.
Please help.
Here's the code:
login.js:
$(document).ready(function(){
$('#errorLogin').hide();
$('#formLogin').submit(function(e){
var username=$('#inputUser').val();
var password=$('#inputPassword').val();
$.ajax({
type:'get',
dataType: 'json',
url: 'dist/php/connection-login.php',
data: {
user: username,
pass: password
},
success: function(e){
console.log(e);
}
});
});
});
connection-login.php:
<?php
$con = new mysqli("localhost", "root", "root", "solucionar_manutencoes_db");
$lg_user=$_GET['user'];
$lg_password=$_GET['pass'];
if (mysqli_connect_errno()) trigger_error(mysqli_connect_error());
$qry = mysqli_query($con, "SELECT * FROM tb_login WHERE lg_user = '$lg_user' AND lg_password = '$lg_password';");
$result = mysqli_fetch_assoc($qry);
$row = mysqli_fetch_assoc($result);
if ($row != 0) {
$response["success"] = 1;
echo json_encode($response);
}
else {
$response["failed"] = 0;
echo json_encode($response);
}
?>
Your PHP should be more like:
connect.php - make sure this is a separate secure page
<?php
function db(){
return new mysqli('localhost', 'root', 'root', 'solucionar_manutencoes_db');
}
?>
I would change your JavaScript AJAX to a POST request, unless you have a reason for it.
connection-login.php
<?php
sesson_start(); include 'connect.php';
if(isset($_POST['user'], $_POST['pass'])){
$db = db(); $r = array();
$prep = $db->prepare('SELECT `lg_user` FROM login WHERE `lg_user`=? && lg_user=?');
$prep->bind_param('ss', $_POST['user'], $_POST['pass']); $prep->execute();
if($prep->num_rows){
$prep->bind_result($lg_user); $r['user'] = $lg_user;
$_SESSION['logged_in'] = $lg_user;
}
echo json_encode($r);
}
?
Now if your JavaScript AJAX result does not contain the a e.user then they are not logged in. Of course, you would probably want to store the original password as a SHA1 or stronger and use AES_ENCRYPTION or better for Personal Information, along with SSL.
I see several errors in your code. The first is that you are executing mysqli_fetch_assoc twice: once on the result, and then again on the array the first call returned. The next is that the $response variable was never declared. Here is the fixed PHP script:
<?php
$con = mysqli_connect("localhost", "root", "root", "solucionar_manutencoes_db");
$lg_user=$_GET['user'];
$lg_password=$_GET['pass'];
if (mysqli_connect_errno()) trigger_error(mysqli_connect_error());
$qry = mysqli_query($con, "SELECT * FROM tb_login WHERE lg_user = '$lg_user' AND lg_password = '$lg_password';");
$results = mysqli_fetch_assoc($qry);
$response = [];
if (count($results) != 0) {
$response["success"] = 1;
echo json_encode($response);
}
else {
$response["failed"] = 0;
echo json_encode($response);
}
?>
In your JavaScript make sure to use e.preventDefault() inside #formLogin's submit handler to prevent page reload when that form is submitted.

Ajax database insert isnt working

I am trying to insert values from an input field into a database with ajax as part of a conversation system.I am using an input form as follows.
<input data-statusid="' .$statuscommentid. '" id="reply_'.$statusreplyid.'" class="inputReply" placeholder="Write a comment..."/>
with the following jquery I carry out a function when the enter key is pressed by the user.
$(document).ready(function(){
$('.inputReply').keyup(function (e) {
if (e.keyCode === 13) {
replyToStatus($(this).attr('data-statusid'), '1',$(this).attr("id"));
}
});
});
within this function is where I am having the problem ,I have no problems calling the function with jquery but I have done something wrong with the ajax and I don't know what?
$.ajax({ type: "POST", url: $(location).attr('href');, data: dataString, cache: false, success: function(){ $('#'+ta).val(""); } });
Additionally this is the php I am using to insert into the database
<?php //status reply input/insert
//action=status_reply&osid="+osid+"&user="+user+"&data="+data
if (isset($_POST['action']) && $_POST['action'] == "status_reply"){
// Make sure data is not empty
if(strlen(trim($_POST['data'])) < 1){
mysqli_close($db_conx);
echo "data_empty";
exit();
}
// Clean the posted variables
$osid = preg_replace('#[^0-9]#', '', $_POST['sid']);
$account_name = preg_replace('#[^a-z0-9]#i', '', $_POST['user']);
$data = htmlentities($_POST['data']);
$data = mysqli_real_escape_string($db_conx, $data);
// Make sure account name exists (the profile being posted on)
$sql = "SELECT COUNT(userid) FROM user WHERE userid='$userid' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row = mysqli_fetch_row($query);
if($row[0] < 1){
mysqli_close($db_conx);
echo "$account_no_exist";
exit();
}
// Insert the status reply post into the database now
$sql = "INSERT INTO conversation(osid, userid, postuserid, type, pagetext, postdate)
VALUES('$osid','$userid','$postuserid','b','$pagetext',now())";
$query = mysqli_query($db_conx, $sql);
$id = mysqli_insert_id($db_conx);
// Insert notifications for everybody in the conversation except this author
$sql = "SELECT authorid FROM conversation WHERE osid='$osid' AND postuserid!='$log_username' GROUP BY postuserid";///change log_username
$query = mysqli_query($db_conx, $sql);
while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
$participant = $row["postuserid"];
$app = "Status Reply";
$note = $log_username.' commented here:<br />Click here to view the conversation';
mysqli_query($db_conx, "INSERT INTO notifications(username, initiator, app, note, date_time)
VALUES('$participant','$log_username','$app','$note',now())");
}
mysqli_close($db_conx);
echo "reply_ok|$id";
exit();
}
?>
Thanks in advance for any help it will be much appreciated
Why didn't you set the proper URL for Ajax calls instead of using location.href?
var ajax = ajaxObj("POST", location.href);
In additional, I guess ajaxObj is not defined or well coded. You are using, jQuery, why don't you try jQuery ajax?
http://api.jquery.com/jquery.ajax/
var ajax = ajaxObj("POST", location.href);
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
var datArray = ajax.responseText.split("|");
if(datArray[0] == "reply_ok"){
var rid = datArray[1];
data = data.replace(/</g,"<").replace(/>/g,">").replace(/\n/g,"<br />").replace(/\r/g,"<br />");
_("status_"+sid).innerHTML += '<div id="reply_'+rid+'" class="reply_boxes"><div><b>Reply by you just now:</b><span id="srdb_'+rid+'">remove</span><br />'+data+'</div></div>';
_("replyBtn_"+sid).disabled = false;
_(ta).value = "";
alert("reply ok!");
} else {
alert(ajax.responseText);
}
ajax.send("action=status_reply_ok&sid="+sid+"&user="+user+"&data="+data);
}
}

PHP query execute without error but return count 0

I am creating login in angularjs, in login.phppage i am verify whether user exist or not by number of rows exist or not means using rowCount() in php pdo but it always return 0 result. here is my php file:
<?php
/*
* Collect all Details from Angular HTTP Request.
*/
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$email = $request->email;
$pass = $request->password;
$user ="root";
$pass ="m2n1shlko";
$dbh = new PDO('mysql:host=localhost;dbname=blog_db', $user, $pass);
$query = $dbh->prepare("SELECT * FROM `signup_tbl` WHERE `email`='$email' AND `password`='$pass'");
$query->execute();
$count = $query->rowcount();
if($count>0){
echo "You have sucessfully login with this Email: ".$count; //this will go back under "data" of angular call.
}else{
echo "Error While Authentication with this Email: " .$count;
}
/*
* You can use $email and $pass for further work. Such as Database calls.
*/
?>
Data from the controller get here I didn't know where i am missing the code. Apreciate if help .. Thanks
You overwrite $pass to database (line 13) and for user (line 8). Change database password to $db_pass.
...
$email = '...';
$pass = $request->password;
...
$db_pass = '...';
...
$dbh = new PDO('mysql:host=localhost;dbname=blog_db', $user, $db_pass); // $pass to $db_pass
Its $query->rowCount(); NOT $query->rowcount();
$count = $query->rowCount();
if($count>0){
echo "You have sucessfully login with this Email: ".$count; //this will go back under "data" of angular call.
}else{
echo "Error While Authentication with this Email: " .$count;
}
Read Manual rowCount
I have done in my local system,it's working good,Try like below example,this is working fine.just follow this example and do your code right way:
<?php
$host = "localhost";
$username = "root";
$password = "";
$dbname = "xxx";
// Create connection
$conn = new PDO('mysql:host=localhost;dbname=xxx', $username, $password);
$query =$conn->prepare("select * from testing");
$query->execute();
$count = $query->rowCount();
echo "Counting:".$count;
?>
Output:-
Counting:3

Return echo from php-function to ajax

I have a question re. receiving data from php-function to ajax.
Ajax (in html-file):
function showUser(name) {
$.ajax({
type: 'POST',
url: '/api.php',
data: {
name : "\""+name+"\"",
func_id : "1"
},
dataType: 'json',
success: function(data)
{
if (data == null) {
console.log("Something went wrong..");
} else {
console.log(data);
Php (separate php-file):
<?php
error_reporting(E_ALL);
//MySQL Database connect start
$host = "localhost";
$user = "root";
$pass = "root";
$databaseName = "TFD";
$con = mysqli_connect($host, $user, $pass);
if (mysqli_connect_errno()) {
echo "Failed to connect to database: " . mysqli_connect_error();
}
$dbs = mysqli_select_db($con, $databaseName);
//MySQL Database connect end
$func_id = $_POST['func_id'];
function showUser() {
global $con;
$name = $_POST['name'];
$sql = "SELECT * FROM users WHERE first_name=$name";
$result = mysqli_query($con, $sql);
$array = mysqli_fetch_row($result);
mysqli_close($con);
echo json_encode($array);
}
if ($func_id == "1") {
showUser();
}
?>
The question: Everything works if I don't have the showUser-function in the php, i.e. I receive correct output to ajax if I have all php code in the "root" directly, but when I put that part in a function I don't get anything sent to ajax. The Network-panel in Chrome shows correct query from the sql so $array contains correct data, but I don't receive it in ajax.
Is there a fix for this?
Thanks!
The reason may be that the variables inside a function're visible only for function itself. Try this way:
$name = $_POST['name'];
function showUser($name) {
global $con;
$sql = "SELECT * FROM users WHERE first_name=$name";
$result = mysqli_query($con, $sql);
$array = mysqli_fetch_row($result);
mysqli_close($con);
echo json_encode($array);
}
Note: If you'll use 'mysql_escape_string' to prevent sql injections, don't forget to connect to db first, otherwise 'mysql_escape_string' will return empty string.

Categories

Resources