create a session using php and ajax - javascript

I am beginner in web development so please understand me. I am trying to create a session using php file and call it in javascript using ajax request. but after I input the path of the index.html in address bar, it always shows the index. I want to know how can i possibly do this with javascript and php. restricting the all the pages of the site if there is no user active.
for example logic:
if (userhasValue == true) {
//redirect to index and can access the whole website
} else {
// redirect to login page
}
I have tried the code below but it still redirecting to index.html even if the data recieve in ajax request is empty.
<?php
include('config.php');
session_start();
$user_check = $_SESSION['login_user'];
$temparray = array();
$ses_sql = mysqli_query($db,"select user_id,username,fullname from user where username = '$user_check'");
$row = mysqli_fetch_array($ses_sql,MYSQLI_ASSOC);
if ($row > 0 ){
array_push($temparray, $row); //save your data into array
echo json_encode($temparray);
} else {
echo 'Error';
}
?>
function getUser(){
var user ='';
var fullname ='';
var id ='';
var tempArray = '';
var name = '';
$.ajax({
type:'POST',
url:'../bench/php/session.php',
data:'',
success:function(msg){
alert(JSON.stringify(msg));
let tempArray = JSON.parse(msg)
user = JSON.stringify(tempArray[0]['username']);
fullname = JSON.stringify(tempArray[0]['fullname']);
id = JSON.stringify(tempArray[0]['id']);
document.getElementById('fullname').innerHTML = fullname;
if (msg == 'Error') {
window.location.href = "../pages-login.html";
}
}, error: function(e){
console.log(e);
}, complete: function(c){
console.log(c);
}
});
}
The code above does not restrict the accessibility of the index.html and other pages if the user is not logged in.
I want to restrict the index page and other pages if the user try to redirect to index page without logging in.
Please help me. Any help will much be appreciated! Thanks in advance

Related

Data Insertion And Page Redirect Not Working jQuery directly printing Else Part

I am working with HTML, PHP, jQuery.
In HTML Form with input type button I am sending data to jQuery and with post I am send to PHP file and then inserting in the database, the problem in my scenario is that in JavaScript file I am just getting else part of the code, the else part is "Enter Your Details Correctly" and data is not inserted in the database, and also page redirect is not working in both success or failure of data insertion. I will really appreciate your time if you guys can help.
On different project my data is inserted in the database but page redirect not working, for page redirect I tried window.location.href, window.location.replace.
$(document).ready(function() {
"use strict";
$("#submit").click(function() {
var name = $("#name").val();
var email = $("#email").val();
var contact = $("#contact").val();
var gender = $("input[type=radio]:checked").val();
var msg = $("#msg").val();
if(name ===''|| email===''|| contact===''|| gender===''|| msg==='') {
alert("Insertion Failed Some Fields are Blank....!!");
}
else {
$.post(
"contactsave.php",
{ name: name, email: email, contact: contact,gender:gender, msg:msg},
function(data) {
if(data.message==='success')
{
window.location.replace("http://multimighty/contactthankyou.php");
}
else
{
alert("Enter Your Details Correctly");
}
},
'json');
}
});
});
/*contactsave.php*/
<?php
$name=$_POST['name'];
$email=$_POST['email'];
$contact=$_POST['contact'];
$gender=$_POST['gender'];
$msg=$_POST['msg'];
$sql = "INSERT INTO test(name, email, phone, gender, message) VALUES ('$name','$email','$contact','$gender','$msg')";
if ($con->query($sql) === TRUE) {
echo json_encode(array("message"=>"success"));
} else {
echo json_encode(array("message"=>"failuer".$con->error));
}
$con->close();
exit;
?>
I just want a simple form insertion without page refresh and after that page redirect

I can run my project in xampp (localhost) but I cannot run when am trying run in another computer even after configuring

<?php
session_start();
define("HOST","localhost");
define("USER","root");
define("PASS","");
define("DB","project_inv");
define("DOMAIN","http://localhost/
inv_project/public_html/dont");
?>
Database:
<?php
class Database
{
private $con;
public function connect(){
include_once("constants.php");
$this->con = new Mysqli(HOST,USER,PASS,DB);
if ($this->con) {
return $this->con;
}
return "DATABASE_CONNECTION_FAIL";
}
}
//$db = new Database();
//$db->connect();
?>
JavaScript Validation Part: It comes here and keeps on loading when am trying to take from ip, e.g. http://xx.xx.xx.xx/inv_project/public_html/dont/
//For Login Part
$("#form_login").on("submit",function(){
var email = $("#log_email");
var pass = $("#log_password");
var status = false;
if (email.val() == "") {
email.addClass("border-danger");
$("#e_error").html("<span class='text-danger'>Please Enter Email Address</span>");
status = false;
}else{
email.removeClass("border-danger");
$("#e_error").html("");
status = true;
}
if (pass.val() == "") {
pass.addClass("border-danger");
$("#p_error").html("<span class='text-danger'>Please Enter Password</span>");
status = false;
}else{
pass.removeClass("border-danger");
$("#p_error").html("");
status = true;
}
if (status) {
$(".overlay").show();
$.ajax({
url : DOMAIN+"/includes/process.php",
method : "POST",
data : $("#form_login").serialize(),
success : function(data){
if (data == "NOT_REGISTERD") {
$(".overlay").hide();
email.addClass("border-danger");
$("#e_error").html("<span class='text-danger'>It seems like you are not registered</span>");
}else if(data == "PASSWORD_NOT_MATCHED"){
$(".overlay").hide();
pass.addClass("border-danger");
$("#p_error").html("<span class='text-danger'>Please Enter Correct Password</span>");
status = false;
}else{
$(".overlay").hide();
console.log(data);
window.location.href = DOMAIN+"/dashboard.php";
}
}
})
}
})
While am trying to run from other computer it displays the design and content of the page but it is not validating but when am trying locally it works fine.
Don't define DOMAIN as "localhost". This will cause errors, while calling the page from other computers.
Localhost means always the computer the script is running on. Using this in a JavaScript the reference to the server is lost and it tries to connect/forward to the client-computer - with no success. This works on the first computer, because this might be the server.

Ajax dependent text field and dropdown menu (Php and Javascript)

I'm a student and still new with Javascript and php, i need to make a login page for my website that can check user input in the database using ajax.
Example: When the user enter their username and password into the field given,the system will automatically check in database either the user exist or not and return the data needed such as user responsibilty from the response table to the dropdown menu below, then they can login into the system.
Below is my basic coding:
Config.php:
e$host = "localhost";
$User = "root"
$Pass = "passw";
$db = "skm_spm";
Login.php:
<?
require ("config.php");
$conn=mysqli_connect($host,$user,$pass,$db);
$duser="select * from tab_user where user_name = '".$_POST["Lname"]."'";
$uresult=myqli_query($conn,$duser);
if(!$uresult)
die("Invalid query: ".mysqli_error());
else
if(mysqli_num_rows($uresult)== 0){
echo "User does not exist";
}
else
{
$row=mysqli_fetch_array($result,MYSQL_BOTH);
if($row["User_Password"] == $_POST["Lpass"])
{
$dresp="select resp_id,resp_name from tab_resp";
$result2 = mysqli_query($conn,$dresp);
}
else
{
}
}
?>
<html>
<b>Login</b><br>
Name : <input type = "text" name="Lname" id="Lname" placeholder="Username"/><br>
Password: <input type = "password" name="Lpass" id="Lpass" placeholder="password"/><br><br>
<div class = "optresp">
<select name="sresp" id="sresp">
<option>--Responsibility--</option>
<?
while (mysqli_fetch_array($result2)){
echo "<option value='$row[1]'>$row[1]</option>";
?>
</select>
</div>
</html>
I have learn on internet and try to code with my understanding,but still failed. I need a php ajax coding that can work with code above.
Thank you.
I will provide you with some code from my recent project and hopefully you will be able to understand it and adapt it to your needs.
Firstly, you should have the login form in a separate file to the PHP login code. Then have button on the page or an enter events that run a Javascript function, in my case Login(). In this Javascript function the text within the input fields are saved to two variables and some basic checks are done on them to ensure that they have been filled in. Next, the PHP login function file (it has no visible content in just processes some data in PHP) using the $.post line. This also passed the two input variables (under the same name) to the PHP file. You can also see that depending on what is returned/echoed from the PHP file as "data" several possible outcomes may occur (Login Success, Account Banned or Invalid Login). I personally call these outcomes error messages or success messages, for example error message 6 for incorrect password/username.
//FUNCTIONS
function Login(){
var StrUsername = $("#txtUsername" ).val();
var StrPassword = $("#txtPassword").val();
if (StrUsername == "" && StrPassword == ""){
$('#pError').text('Enter your Username and Password!');
}
else if(StrUsername == ""){
$('#pError').text('Enter your Username!');
}
else if(StrPassword == ""){
$('#pError').text('Enter your Password!');
}
else{
$.post('https://thomas-smyth.co.uk/functions/php/fnclogin.php', {StrUsername: StrUsername, StrPassword: StrPassword}, function(data) {
if (data == 0){
window.location.href = "https://thomas-smyth.co.uk/home";
}
else if (data == 1){
window.location.href = "https://thomas-smyth.co.uk/banned";
}
else if (data == 6){
$('#pError').text('Username & Password combination does not exist!');
}
});
}
}
Next the PHP function file. Firstly, the variables passed by the Javascript are collected using $_POST. My SQL class is then pulled into the file, this does all my SQL DB connections. I then have my SQL statement that will search to see if the account exists. Notice the ? in it. This prevents SQL injections as the variables is bound into the statement through the SQL server meaning it won't allow people to put SQL code within my input fields to break my database. I then check whether the account exists, if it doesn't I save data to 6, which will cause the error message 6 in the Javascript to run when data is returned. I have a field in my database that contains a rank. If the login is correct then I create a SESSION variable to store their username and rank in. This is later used on pages to check whether they are logged in before displaying a page (this speeds up navigation as it means that the DB doesn't need to be searched everytime the user switches page, however does bring some issues like if you ban a user while they are logged in they will stay logged in until their session dies). You could use this on your dropdown menu to ensure the user is logged in and/or get their username. Finally, I return 0 or 1, so that the Javascript then re-directs them to the correct page.
<?php
//Retrieves variables from Javascript.
$StrUsername = $_POST["StrUsername"];
$StrPassword = $_POST["StrPassword"];
require "sqlclass.php";
$TF = new TF_Core ();
$StrQuery = "
SELECT Username, Rank FROM tblUsers
WHERE Username = ? AND Password = ?";
if ($statement = TF_Core::$MySQLi->DB->prepare($StrQuery)) {
$statement->bind_param('ss',$StrUsername,$StrPassword);
$statement->execute ();
$results = $statement->get_result ();
if($results->num_rows == 0){
$data = 6;
}
else {
while ($row = $results->fetch_assoc()) {
//Other groups
if ($row["Rank"] == "Developer" || $row["Rank"] == "Staff" || $row["Rank"] == "Cadet"){
session_start();
$_SESSION["LoginDetails"] = array($StrUsername, $row["Rank"]);
$data = 0;
}
//Banned
else if ($row["Rank"] == "Banned"){
session_start();
$_SESSION["LoginDetails"] = array($StrUsername, "Banned");
$data = 1;
}
}
}
}
echo $data;
?>
Hopefully this helps you. Please say if you need more help!
You need to make ajax call on blur of username to check if user exists in database and on success of that you can make one more ajax to check for password match of that particular user. This will give you both cases whether a user exixts or not if exixts then does the password match or not only after that user will be logged in and then you can show the responsibilities of that particular user.
For username:
$('#Lname').blur(function(){
$.ajax({
url:'url where query for matching username from database',
data:'username collected from input on blur',
type:'POST',
success:function(data){
//Code to execute do on successful of ajax
}
})
})
For Password:
The ajax call remains the same only url, data and response changes

ajax responseText contains php source code

I am trying to make a ajax call and validate a input html field. But, instead of getting simple echo message. I am getting complete source code in responseText.
JavaScript
function checkUsername() {
document.getElementById("username").className = "thinking";
usernameRequest = createRequest();
if (usernameRequest == null)
alert("Unable to create request");
else {
var theName = document.getElementById("username").value;
var username = escape(theName);
var url= "checkName.php?username=" + username;
usernameRequest.onreadystatechange = showUsernameStatus;
usernameRequest.open("GET", url, true);
usernameRequest.send(null);
}
}
function showUsernameStatus() {
alert(usernameRequest.responseText);
if (usernameRequest.readyState == 4)
{
if (usernameRequest.status == 200) {
if (usernameRequest.responseText == "okay") {
document.getElementById("username").className = "approved";
document.getElementById("register").disabled = false;
}
else {
document.getElementById("username").className = "denied";
document.getElementById("username").focus();
document.getElementById("username").select();
document.getElementById("register").disabled = true;
}
}
}
}
checkName.php
<?php
$takenUsernames = array('bill', 'ted');
sleep(2);
if (!in_array($_REQUEST['username'],$takenUsernames )) {
echo 'okay';
} else {
echo 'denied';
?>
Previously, I tried to integrate PHP into tomcat, but I was advice it was not a good practice. TRIAL TO INTEGRATE PHP
What I can make out of this situation is that Tomcat is not parsing PHP file and instead it is returning the source code. I believe there should be a means for me to let tomcat parse php files and send the right response.
I have also tried with simple php code, with one statment <?php echo 'HELLO'; ?> and I still get the source code.
Thanks in advance.
NOTE : I do not know php, I am working an example from HEAD FIRST AJAX
you need to install PHP for Tomcat & set its path to compile it.see the below link for php configuration settings.
http://php-java-bridge.sourceforge.net/doc/tomcat6.php
http://www.studytrails.com/blog/php-on-a-java-app-server-apache-tomcat-using-quercus/

PHP session lost after redirecting with Javascript?

So I am grabbing data through AJAX in order to redirect the user to a page , but the PHP session data gets lost after being redirected to the page ... Below is my code , can anyone tell me what might be causing that ... I'm copying the relevant code below
$("#activation").click(function(event){
event.preventDefault();
var first_name = $("#first_name").val();
var last_name = $("#last_name").val();
var customer_phone = $("#customer_phone").val();
var pin = $("#pin").val();
var carrier_id = $("#selCarrier option:selected").val();
var phone_number = ValidateMobNumber('customer_phone');
$.ajax({
url:"add_customer.php",
data:{first_name:first_name,last_name:last_name,pin:pin,carrier_id:carrier_id,customer_phone:customer_phone},
type:"POST",
success:function(result){
var customer_id = result;
var url ="http://www.example.com/store/activation.php?id="+customer_id;
if(customer_id !=""){
window.location.href = url;
return false;
}
else {
alert("Please enter a first name , last name and pin for activation");
}
}
});
});
I was having the same problem, but changing the absolute path to a relative one fixed it for me.
I changed this
window.location.replace('http://www.example.com/folder/subfolder/subfolder/file.php');
To this
window.location.replace('../../folder/subfolder/subfolder/file.php');
Hope it helps.

Categories

Resources