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/
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.
Working example below, hopefully this will help others learn!
I'm using AJAX in javascript to send a JSON string to PHP.
I'm not familiar with AJAX, javascript or php, so this is taking me a while to get started.
I have a html file with a username field, password field, and login button.
Then I have a javascript file that takes the username pass and sends it to a php file.
I know the php file is being accessed because I am seeing the test echo in console.
I just cant figure out how to access the data I'm sending to the php.
script.
function attemptLogin(){
var inputUserName = JSON.stringify(document.getElementById("userName").value);
var ajaxData = new XMLHttpRequest();
ajaxData.open('GET', 'ajax.php', true);
ajaxData.onreadystatechange = function(){
var DONE = 4;
var OK = 200;
if (ajaxData.readyState === DONE) {
if (ajaxData.status === OK) {
console.log(ajaxData.responseText);
}else{
console.log("ERROR : " + ajaxData.status);
}
}
};
ajaxData.send(inputUserName);
}
ajax.php
<?php
echo"TestInPHP";
?>
For now all I want to do is echo the username back to console, I'm sure the syntax is something simple, I just cant figure out what it is.
Here is an edit for the working code thanks to SuperKevin in the
comments below. This code will take the string in the username and
password fields in HTML by the JS, send it to PHP and then sent back
to the JS to output to the browser console window.
index.html
<input type="text" name="userID" id="userName" placeholder="UserID">
<input type="password" name="password" id = passW placeholder="Password">
<button type="button" id = "button" onclick="attemptLogin()">Click to Login</button>
script.js
function attemptLogin(){
var inputUserName =
JSON.stringify(document.getElementById("userName").value);
// console.log(inputUserName);
var inputPassword = JSON.stringify(document.getElementById("passW").value);
var cURL = 'ajax.php?fname='+inputUserName+'&pass='+inputPassword;
var ajaxData = new XMLHttpRequest();
ajaxData.open('GET', cURL, true);
ajaxData.onreadystatechange = function(){
var DONE = 4;
var OK = 200;
if (ajaxData.readyState === DONE) {
if (ajaxData.status === OK) {
console.log(ajaxData.responseText);
}else{
console.log("ERROR : " + ajaxData.status);
}
}
};
ajaxData.send();
}
ajax.php
<?php
echo $_GET['fname'];
echo $_GET['pass'];
?>
Here's a simple example of how you would make a vanilla call.
This is our main file, call it index.php.
<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "delete.php", true);
xhttp.send();
</script>
Here's our server script. delete.php
<?php
echo "HELLO THERE";
Now, if you wanted to pass data to your script you can do the following:
xhttp.open("GET", "delete.php?fname=Henry&lname=Ford", true);
xhttp.send();
To access this data you can use the global $_GET array in php. Which would look like this:
$fname = $_GET['fname'];
$lname = $_GET['lname'];
Obviously, you have to sanitize the data, but that's the gist of it.
For a much more in depth tutorial visit W3Schools Tutorial PHP - AJAX.
You can see all the data sent to your php with :
<?php
print_r($_GET); //if it's send via the method GET
print_r($_POST); //if it's send via the method POST
?>
So, in your case it will be something like :
<?php
echo $_GET['username'];
?>
If you're not using jQuery then don't pay attention to my answer and stick to the pure javascript answers.
With jQuery you can do something like this:
First Page:
$.ajax({
url: 'sportsComparison.php',
type: 'post',
dataType: 'html',
data: {
BaseballNumber = 42,
SoccerNumber = 10
},
success: function(data) {
console.log(data);
});
which will send the value 42 and 10 to sportsComparison.php with variable names BaseballNumber and SoccerNumber. On the PHP page they can then be retrieved using POST (or GET if that's how they were sent originally), some calculations performed, and then sent back.
sportsComparison.php:
<?php
$BaseballValue = $_POST["BaseballNumber"];
$SoccerValue = $_POST["SoccerNumber"];
$TotalValue = $BaseballValue * $SoccerValue;
print "<span class='TotalValue'>".$TotalValue."</span>";
?>
This will return a span tag with the class of TotalValue and the value of 420 and print it in the console.
Just a simple way to do ajax using jQuery. Don't forget commas in the parameter list.
I have a PHP file and JavaScript file.
JavaScript transfers 3 variables into PHP file, PHP file transfers the result into JavaScript. The process is working and gives me the right result, however as a last action in JavaScript when I checking the result it is give me false instead of true. So please help me to find out what is wrong.
PHP:
if ((isset($_POST['st'])) && (!empty($_POST['st'])))
{
$status=$_POST['st'];
switch($status)
{
case '0': {
break;
}
case "1": {
$login = $_POST['login'];
$pas = $_POST['pas'];
check($login,$pas);
break;
}
}
exit;
}
function check ($login,$pas) {
include "php/log_bd.php";
$result = mysql_query("SELECT * FROM users WHERE Login='$login'",$db); //I know, i know, that it is dangerous in case of SQL injection, but I use it for educational example.
$row = mysql_fetch_array($result);
if (empty($row))
{
exit('er');
}
if ($row['Pas']!= $pas)
{
exit('er');
}
exit(0);
}
JavaScript:
$(document).on("click","input[name=door_open]", function () {
var login = $("input[name=login]").val();
var pas = $("input[name=pas]").val();
$.post("index.php",{ st:1, login:login , pas:pas} ,function(data)
{
alert (data); // I have 'er'
if (data == 'er')
{
alert ("Sorry incorrect data");
return false;
}
else
{alert (data);}
});
return false;
});
So It give me in JavaScript file 'er' result but when I check data == 'er', it told me that it is false.
As was suggested I add some some log console comands
This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 1 year ago.
I have some information from my db that is being loaded onto my page, but I would like to be able to use an if statement regarding the value of this, and then assign a javascript value to be a boolean value. How can I go about this? (at the moment I am just printing the value)
<?php
if ($_SESSION['loggedin'] = true){
print_r($_SESSION['userlevel']); // THIS IS WHAT I WANT TO SPECIFY IN AN IF STATEMENT
}
?>
<script>
var userloggedin = false;
</script>
What I would like to do in pseudocode:
<script>
var userloggedin = false;
function somefunction(){
if (userloggedin == true){
//Do stuff...//
}
}
</script>
Sorry for my lack of knowledge on the subject, I'm only beginning to learn backend web development.
Have you tried searching the forum for any previous posts with regards to parsing PHP variables to javascript?
With a simple search I found a feed relating to parsing PHP variables to JavaScript here:
Get variable from PHP to JavaScript
Anyway, from my understanding of your problem does this serve as a suitable answer?
<?php
if ($_SESSION['loggedin'] == true){
$userLevel = $_SESSION['userlevel'];
$userLoggedIn = true;
}
else {
$userLevel = null;
$userLoggedIn = false;
}
?>
<script type="text/javascript">
var userLoggedIn = "<?php Print($userLoggedIn); ?>";
var userLevel = "<?php Print($userLevel); ?>";
if (userLoggedIn == true) {
if (userLevel == "levelOne") {
//Your code here
}
else if (userLevel == "levelTwo") {
//Your code here
}
else {
//Your code here
}
}
</script>
You can echo bits of Javascript code from PHP, like this:
<script>
var userloggedin = <?php echo ($_SESSION['loggedin'] ? 'true' : 'false'); ?>;
</script>
First change your if statement to use == double equal signs if you want the expression to work as expected. Then you can simply echo a variable into javascript as in example below:
Simple solution would be similar to:
<?php
if ($_SESSION['loggedin'] == true){
$logged_in = "true";
} else {
$logged_in = "false";
}
?>
<script>
var userloggedin = <?php echo $logged_in;?>;
</script>
You can set a javascript variable with a php value by:
<script>
var jsVar='<?php echo $phpVar ?>';
</script>
A simple solution would be just to echo variable value in script tag. But this is unsafe, because variable is global, meaning it can be modified in client-side console.
Better solution would be an ajax request and php script that returns some response, this way the variable is scoped to ajax response function, so it's safe from modifications. Here's an example:
...
echo json_encode($_SESSION['loggedin'] ? 'true' : 'false');
...
In javascript, you can use jquery .get() request:
$.get("userLoggedIn.php", function(data) {
var response = JSON.parse(data);
if(data === true) {
// user is logged in
}
else {
// not logged in
}
});
If it's important that this functionality is handled before anything else, an synchronous ajax request:
$.ajax({
url: "userLoggedIn.php",
async: false, // this makes request synchronous
success: function (data) {
var response = JSON.parse(data);
if (data === true) {
// user is logged in
} else {
// not logged in
}
});
Synchronous request means that client will wait for request to finish before doing anything else. It's not recommended to be used a lot, but sometimes it's the only way to go about.