How to execute code from php file when ajax called - javascript

Okay so i have php code which is supposed to check if there is an existing user in database when login is attempted and send back to javascript fail or success
Php code:
<?php
require_once 'Korisnik.php';
require_once 'dbconn/korisnikdb.php';
if ($_SERVER["REQUEST_METHOD"] === "POST") {
// collect value of input field
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
$korisnik = getKorisnikByUserPass($username, $password);
if ($korisnik == null) {
$statusArray = array("status"=>"fail");
echo json_encode($statusArray);
return;
} else {
session_start();
$_SESSION["prijavljeniKorisnik"] = $username;
$statusArray = array("status"=>"success");
echo json_encode($statusArray);
return;
}
}
?>
Here i have my javascript code :
$(document).ready(function() {
var usernameInput = $('#usernameInput');
var passwordInput = $('#passwordInput');
var pogresniPodaci = $('#pogresniPodaci');
var praznaPolja = $('#praznaPolja');
pogresniPodaci.hide();
praznaPolja.hide();
$('#submitButton').on('click', function(event) {
var username = usernameInput.val();
var password = passwordInput.val();
console.log(username);
console.log(password);
if (username == '' || password == '') {
praznaPolja.show();
event.preventDefault();
return false;
}
var params = {
'username': username,
'password': password
}
$.post('loginCheck.php', params, function(data) {
console.log(data.status);
if (data.status == 'fail') {
pogresniPodaci.show();
usernameInput.val('');
passwordInput.val('');
return;
}
if (data.status == 'success') {
location.href = 'pocetna';
}
});
event.preventDefault();
return false;
});
});
http://prntscr.com/skb37r -> here you can see status after i press that button
The problem is that php code in loginCheck.php never actually executes, I tried adding echo at start of php file but it doesn't execute.

You are sending http request to localhost. Even if file doesn't exist, your localhost will return status 200, unless it's configured to throw an error.
Try this:
go to http://localhost/loginCheck.php and echo anything there.
echo "This is loginCheck";
If it echoes, you are on the right route to loginCheck file.
If it works, go to browser dev tools > network > and see request headers and find "Request URL" header. it should be "http://localhost/loginCheck.php" - the route to file you visited previously. if its not, you have to fix it in $.post request.

Related

create a session using php and ajax

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

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.

Check if form has been submitted via ajax in php

I have a login form which is validated using javascript and then sent to php file for further processing. Form is submitted via ajax.
Currently, i have an if statement in php file that checks whether form has been submitted, problem is this if statement never evaluates to true. Hence my php code inside my if statement never runs. When request is sent via ajax, .onload event gets invoked without if statement inside php file evaluating to true.
Question
Once the form is submitted to php file via ajax, how can i detect in php file that form has been submitted via javascript.
Here's my php code
<?php
require 'DbConnection.php';
// if form is submitted
if(isset($_POST['login-btn'])) {
$username = $_POST['username-field'];
$password = $_POST['password-field'];
echo '<script>alert(\'form submitted\')</script>';
verifyLoginCredentials($username, $password);
} else {
echo '<script>alert(\'form not submitted\')</script>';
}
// verify admin login credentials
function verifyLoginCredentials($username, $password) {
global $dbConnect;
$query = 'SELECT full_name, username, password FROM admins WHERE username = ?';
$statement = $dbConnect->prepare($query);
if($statement) {
$statement->bind_param('s', $username);
$statement->execute();
$resultSet = $statement->get_result();
// since there will be only one row returned at max, no need of a loop
$row = $resultSet->fetch_assoc();
if($row != null) {
$adminFullName = $row['full_name'];
$adminUsername = $row['username'];
$adminPassword = $row['password'];
// if username/password is correct start session and store
// username, password, full name in the session
if($username === $adminUsername && password_verify($password, $adminPassword)) {
session_start();
$_SESSION['current_admin_fullname'] = $adminFullName;
$_SESSION['current_admin_username'] = $adminUsername;
$_SESSION['current_admin_password'] = $adminPassword;
}
else { // if username/password combination is incorrect
echo 'Incorrect Username/Password Combination';
}
} else { // if username doesn't exists in the database
echo 'Entered username isn\'t registered';
}
} else {
echo 'Error while preparing sql query';
}
}
?>
and here's relevant javascript code
let loginForm = document.querySelector('.login-form');
let usernameField = document.getElementById('username-field');
let passwordField = document.getElementById('password-field');
// submit login form to server using ajax
function ajaxFormSubmit() {
'use strict';
let ajaxRequest = new XMLHttpRequest();
let url = 'admin login.php';
// login form submitted on server successfully
ajaxRequest.onload = function () {
if (ajaxRequest.readyState === 4 && ajaxRequest.status === 200) {
console.log(ajaxRequest.responseText);
displayInfoMessage(ajaxRequest.responseText, 'success');
}
};
// error while login form submission on server
ajaxRequest.onerror = function () {
if (ajaxRequest.status !== 200) {
console.log(ajaxRequest.responseText);
displayInfoMessage(ajaxRequest.responseText, 'error');
}
};
ajaxRequest.open('POST', url, true);
ajaxRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
ajaxRequest.send(new FormData(loginForm));
}
function validateForm(e) {
'use strict';
// prevent form submission
e.preventDefault();
if (anyEmptyField()) {
displayInfoMessage('Please fill all the empty fields', 'error');
highLightEmptyFields();
//return false;
return;
}
// check if username is in right format
if (!(regexTester(/^[A-Za-z0-9_]+$/g, usernameField.value))) {
displayInfoMessage('Username not valid', 'error');
highLightTextField(usernameField);
//return false;
return;
}
// check if username is atleast 3 characters long
if (usernameField.value.length < 3) {
displayInfoMessage('Username should contain atleast 3 characters', 'error');
highLightTextField(usernameField);
//return false;
return;
}
// check if password is in right format
if (!(regexTester(/^[A-Za-z0-9_]+$/g, passwordField.value))) {
displayInfoMessage('Password not valid', 'error');
highLightTextField(passwordField);
//return false;
return;
}
// check if password is atleast 6 characters long
if (passwordField.value.length < 6) {
displayInfoMessage('Password should contain atleast 6 characters', 'error');
highLightTextField(passwordField);
//return false;
return;
}
//return true;
// submit form information to server via ajax
ajaxFormSubmit();
}
// add submit event listener on login form
loginForm.addEventListener('submit', validateForm);
There is no guaranteed way to know that the form was submitted via ajax.
Normally this is done via headers, in our case HTTP_X_REQUESTED_WITH which can be retrieved via the global $_SERVER variable.
Do note that headers can easily be spoofed.
You can check like so:
if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
{
// code here
}
Here's a few links to look at:
https://paulund.co.uk/use-php-to-detect-an-ajax-request
How to check if the request is an AJAX request with PHP

Javascript post to check username availability not working

Im trying to check if the register username's available but everytime the clientside returns that the username its available.
This is my clientside code:
$(document).ready(function()
{
$("#register_username").blur(function(){
var user = $("#register_username").val();
$.post("register",
{
username: user
},
function(data, status){
if(data == '1')
{
alert('Good, username its available!');
}
else
{
alert('Snap!You cant use this username :(!');
}
});
});
});
And this is the serverside code:
if(strlen($_POST['username']) > 0)
{
$usr = $_POST['username'];
if($usr == 'test')
echo '1';
else
echo '2';
}
PHP Version: 5.5
first of all, i guess if the input field has value "test" it would say "you cannot use this username"?
in your code if input is "test" ($usr == "test" - that comes from input) you echo 1, and in your code 1 means username is available? So shouldn't it be backwards?
Does it say "username is available" with every input?

User Register Sign up Error

I am making a website and I have a signup.php page where the users can register and enter their information into the mysqli database. When I do this, I am almost there, I just keep getting a problem at this one line:
ajax.send("&u="+u+"&e="+e+"&p="+p1+"&g="+g);
It is basically sending the variables in the ajax/javascript check to get ready for transport to server. But I am getting an internal server 500 error at that line. Any ideas? I will post more code if you want me to.
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
function signup(){
var u = _("username").value;
var e = _("email").value;
var p1 = _("pass1").value;
var p2 = _("pass2").value;
var g = _("gender").value;
var status = _("status");
if(u == "" || e == "" || p1 == "" || p2 == "" || g == ""){
status.innerHTML = "Fill out all of the form data";
} else if(p1 != p2){
status.innerHTML = "Your password fields do not match";
} else {
_("signupbtn").style.display = "none";
status.innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "signup.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText != "signup_success"){
status.innerHTML = ajax.responseText;
_("signupbtn").style.display = "block";
} else {
window.scrollTo(0,0);
_("signupform").innerHTML = "OK "+u+", check your email inbox and junk mail box at <u>"+e+"</u> in a moment to complete the sign up process by activating your account. You will not be able to do anything on the site until you successfully activate your account.";
}
}
}
type:post;
ajax.send("&u="+u+"&e="+e+"&p="+p1+"&g="+g);
}
}
A 500 Internal Server Error code is an HTTP response code, indicating that you have reached out to the server and it has responded with an error. So it doesn't appear to be a problem with your JS code (at least as far as we can tell from what you've posted).
Try doing var_dump($_REQUEST); die(); as the first line in signup.php. Does that give you a 200 status code? If so, try moving that line down your code on the server until you get back to the 500 Internal Server Error, and you've found the line that's causing the problem.
You have the question tagged with jQuery, but I don't see any jQuery in your code sample. If you do have it, try this:
function signup() {
var status = $('#status');
var signupbtn = $('#signupbtn');
var data = {
u: $('#username').val(),
e: $('#email').val(),
p: $('#pass1').val(),
g: $('#gender').val()
};
if (data.u == '' || data.e == '' || data.p == '' || data.g == '') {
status.text('Fill out all of the form data');
return;
} else if (data.p != $('#pass2').val()) {
status.text('Your password fields do not match');
return;
}
signupbtn.hide();
status.text('please wait...');
$.ajax({
type: 'post',
url: 'signup.php',
data: data,
success: function(responseText) {
if (responseText != 'signup_success') {
status.text(responseText);
signupbtn.show();
return;
}
window.scrollTo(0, 0);
$('#signupform').html('OK '+ data.u +', check your email inbox and junk mail box at <u>'+ data.e +'</u> in a moment to complete the sign up process by activating your account. You will not be able to do anything on the site until you successfully activate your account.');
},
});
}

Categories

Resources