I have written a little function to check if the username/password of a certain user is correct using a json query. If result is ok i want to load a certain page into a div, if the result is error i want to load a different page into a div.
Normally i would use $('#test').load("members.php"); to achieve this but it just isnt working (my div has an id of test - members is the page to be loaded).
function dologin(){
var email = $('#email').val();
var wachtwoord = $('#wachtwoord').val();
if($.trim(email) != '' && $.trim(wachtwoord) != ''){
$.post("login2.php", {email:email,wachtwoord:wachtwoord})
.done(function(data) {
var response = jQuery.parseJSON(data);
var result = response.result;
if(result == 'ok')
{
// logged on
$('#test').load("members.php");
}else{
// error
$('#test').load("loginfailed.php");
}
}, "json");
}
}
Related
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
<?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.
I have made a register form, from where data is getting stored into the local storage. Only after user logs in successfully, it redirects to success.html or else takes user back to the login page. I have added the following script at the head of success.html-
<script>
if (localStorage.getItem('status') != null)
{
//redirect to page
window.location.href = "success.html";
}
else
{
//show validation message
window.location.href = "login.html"
}
</script>
and following is my login validation function-
//Storing data from local storage into an array of objects
var usersdata = JSON.parse( localStorage.getItem('key_users' ) );
function loginvalidate()
{
usersdata = JSON.parse( localStorage.getItem('key_users' ) );
var usernameinput = document.getElementById("username");
var passwordinput = document.getElementById("password");
for(var p in usersdata)
{
console.log(p+':'+usersdata[p].username+'|'+usersdata[p].email);
if(usernameinput==usersdata[p].username && passwordinput==usersdata[p].password)
{
alert("Logged in successfully");
}
}
jQuery(window).load(function() {
localStorage.setItem('status','loggedIn')
});
}
Here, I am unable to set the status to 'loggedIn' and if I set it manually through console the success.html keeps on loading just like running any infinite loop.
The loop is occurring because of the following condition on the success page. It redirects even when you are at the success page and thus the loop.
if (localStorage.getItem('status') != null)
{
//redirect to page
window.location.href = "success.html";
}
Change it to
if (localStorage.getItem('status') == null)
{
//show validation message
window.location.href = "login.html"
}
P.S. I do highly recommend not to use localstorage to send the username and password to the clientside. It breaks the whole point of authentication and authorization services even existing.
The javascript is supposed to handle form submission. However, even if called with
script src="js/registerform.js"> Uncaught ReferenceError: sendreg is not defined .
The function is called onclick. Can be reproduced on www.r4ge.ro while trying to register as well as live edited. Tried jshint.com but no clue.
I will edit with any snips required.
function sendreg() {
var nameie = $("#fname").val();
var passwordie = $("#fpass").val();
var emailie = $("#fmail").val();
if (nameie == '' || passwordie == '' || emailie == '') {
alert("Please fill all the forms before submitting!");
} else {
// Returns successful data submission message when the entered information is stored in database.
$.post("http://r4ge.ro/php/register.php", {
numeleluii: nameie,
pass: passwordie,
mail: emailie
}, function(data) {
alert(data);
$('#form')[0].reset(); // To reset form fields
setTimeout(fillhome, 1000);
});
}
}
function sendpass() {
var oldpassw = $("#oldpass").val();
var newpassw = $("#newpass").val();
if (oldpassw == '' || newpassw == '') {
alert("Please fill all the forms before submitting!");
} else {
// Returns successful data submission message when the entered information is stored in database.
$.post("http://r4ge.ro/php/security.php", {
xoldpass: oldpassw,
xnewpass: newpassw
}, function(data2) {
alert(data2);
$('#passform')[0].reset(); // To reset form fields
});
}
}
function sendmail()
{
var curpass = $("#curpass").val();
var newmail = $("#newmail").val();
if (curpass == '' || newmail == '')
{
alert("Please fill all the forms before submitting!");
}
else
{
// Returns successful data submission message when the entered information is stored in database.
$.post("http://r4ge.ro/php/security.php", {
curpass: curpass,
newmail: newmail
}, function(data3) {
alert(data3);
$('#mailform')[0].reset(); // To reset form fields
});
}
}
I'm guessing here but... I imagine you are doing something like
...<button onclick="sendreg">...
And you have your <script> in the bottom on the code. Just put them on top or use $("#mybtn").click(sendreg)
Try using $("#mybtn").click(sendreg) instead of inline onclick.
The script wasn't called in the html. sorry for wasting time. A simple
<script src="js/registerform.js"></script> Fixed it.
There is no syntax error there, and I don't see any such error when trying the page.
The error that you get is that you can't make a cross domain call. Do the request to the same domain:
$.post("http://www.r4ge.ro/php/register.php", {
or:
$.post("/php/register.php", {
I have a Google spreadsheet with a script that checks a local library catalog to see if an ISBN-searched book has shown up or not. There's no API or RSS feature so I'm using UrlFetchApp to screen scrape for certain unique phrases that appear in the HTML source for a given book status.
Right now my spreadsheet only updates the "Status" column (which invokes the script based on an ISBN field) when I open the spreadsheet. Is there a way I can have Google Script run my main function and then trigger for changes? The documentation I've read has only mentioned user edits, which is not what I'm looking for.
function ISBNsearch(ISBN){
var consortURL = "http://LIBRARYURL/search~S6/?searchtype=i&searcharg=" + ISBN + "&searchscope=4";
var retrieveURL = UrlFetchApp.fetch(consortURL).getContentText();
var searchURLno = retrieveURL.search("BROWSE SCREEN TABLE");
var searchURLyes = retrieveURL.search("Item Location");
var searchURLordered = retrieveURL.search("copy ordered for");
if (searchURLno > -1){
var answer = "Not found"
} else if (searchURLyes > "-1") {
answer = "in Consort"
} else if (searchURLordered > "-1") {
answer = "on order"
} else if ((searchURLno == "-1") && (searchURLyes == "-1") && (searchURLordered == "-1")) {
answer = "no input"; }
return answer;
}
function testScript(){
var response = ISBNsearch("9782711802036");
Logger.log("The answer is " + response);
return response;
}
You can use Time Driven triggers to schedule function executions.
You can also programmatically manage these triggers.