Getting variable value from PHP with jQuery - php

So how do i get variable value from php file with jquery...?
the jquery code is in other file (tpl)
for example i have register.php and register.tpl (template file for register.php)
register.php
...some includes here...
if(isset($_POST['submit'])) {
$username = mysql_real_escape_string(trim($_POST['username']));
$email = mysql_real_escape_string(trim($_POST['email']));
$check = $mysql->query("SELECT username FROM ".TBL_USERS." WHERE username = '".$username."' OR email = '".$email."'");
$rows_check = mysql_num_rows($check);
if($rows_check > 0) {
echo 1;
} else {
$password = mysql_real_escape_string($_POST['password']);
$salt = generate_salt($email);
$hash = hash_password($password, $salt);
$q = $mysql->query("INSERT INTO ".TBL_USERS." (username, password, email, salt) VALUES ('".$username."', '".$hash."', '".$email."', '".$salt."')");
if($q) {
header("Location: index.php");
} else {
die(mysql_error());
}
}
} else {
.. calling parse template function ...
}
register.tpl
..jquery library included..
<form id="register" action="register.php" method="post">
<tr>
<td>Username</td>
<td><input type="text" id="username" name="username" class="register" style="width: 200px;" />
</td>
email
...other inputs...
$("#username").blur(function()
{
var email_v = $("#email").val();
$("#msgbox").removeClass().addClass('messagebox').text('Checking...').fadeIn("slow");
$.post("register.php",{ username:$(this).val(), email: email_v, submit: true } ,function(data)
{
if(data=="1")
{
$("#msgbox").fadeTo(200,0.1,function()
{
$(this).html('This User name Already exists').addClass('messageboxerror').fadeTo(900,1);
});
}
else
{
$("#msgbox").fadeTo(200,0.1,function()
{
$(this).html('Username available to register').addClass('messageboxok').fadeTo(900,1);
});
}
});
});
</script>
when i changed the whole register.php for testing purposes to
or
the script worked...however with the original version it shows always that username is available...

Best bet is to output the PHP variable as a hidden field or a JavaScript variable:
<input type="hidden" id="my_var" name="my_var" value="<?php echo($my_var); ?>" />
// access it like this:
alert($('#my_var').val());
or
<script type="text/javascript">
var my_var = <?php echo($my_var); ?>;
</script>
// access it like this
alert(my_var);
That should do it :-)

Either you make a Jquery Ajax Request that will request a php page which will return whatever you want or you echo a javascript variable with php
<?php
echo '<script> var javascript_variable = "whatever"; </script>';
?>

It will work if you do
echo "1";
and then
if(result == "1") {
If it doesn't (but I've checked on a code of mine without the quotes, it didn't work, with, it was ok), check the response from Firebug console.

In situations where my company's application needs to call Jquery on a dynamic element and we have the Jquery call IN the php file we'll directly call php in the Jquery call.
For example:
alert($('#').val());
Not for all situations, certainly. If you have to call a variable where you don't have PHP access to the file (possibly such as a .tpl file, depending on your setup) you might resort to setting a hidden input as detailed above.

Related

Login form fails to login client

I've been trying to create an admin panel for my website. I created a login form but whenever I try to log in, it says that the user does not exist. I can't seem to find where I made a mistake.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login - Admin panel</title>
</head>
<body>
<?php
include 'db.php';
?>
<?php
include 'functions.php';
?>
<?php
include 'title_bar.php';
?>
<h3>Login Here: </h3>
<?php
if(isset($_POST['submit'])) {
$username = $_POST['username'];
$password = $_POST['password'];
if(empty($username) or empty($password)){
echo "<p>Fields should not be empty</p>";
} else {
$check_login=mysqli_query($con,"SELECT id, type FROM users WHERE username='$username' AND password='$password'");
if(mysqli_num_rows($check_login) == 1){
$run=mysqli_fetch_array($check_login);
$user_id=$run['id'];
$type=$run['type'];
if($type =='d') {
echo "<p>Your acount is deactivated by an admin!</p>";
} else {
$_SESSION['user_id'] = $user_id;
header('location: adminpanel.php');
}
} else {
echo "<p>Wrong Username or Password</p>";
}
}
}
?>
<form method='post'>
User name:
<input type ='text' name = 'username' />
<br/><br/>
Password:
<input type = 'password' name = 'password' />
<br/><br/>
<input type = 'submit' name = 'submit' value='Login' />
</form>
</body>
</html>
Any help would be appreciated.
Just because I see this all the time on SO, I will address some of my comments. There are a lot of reasons why it could fail based on what you have. First off, a solid framework would do almost all this for you, you would just have to do basic logic but not all the grunt work. Second, just because you want to echo some text in a specific part of your page, doesn't mean you should do a bunch of logic that leads up to echo in the same part of the page. The idea is that the browser output is the last thing to happen so you will want to do the bulk of your logic before the page outputs.
First break up your logic into a specific-task functions/class/methods that will be easily understood and ready to be re-used:
/functions.php
<?php
// I am going to use PDO because I am more familiar with it
function verifyUser($username,$password,$con)
{
// Get the basics from the database
$query = $con->prepare("SELECT `password`,`type`,`id` FROM `users` WHERE `username` = :0");
// Bind the value for security
$query->execute(array(":0"=>$username));
// Get the results
$result = $query->fetch(PDO::FETCH_ASSOC);
// If empty, return false
if(!$result)
return array('verified'=>false);
// You need to store the password using password_hash()
$verified = password_verify($password,$result['password']);
// If user is revoked
$revoked = is_deactivated($result);
// Return all the validation settings
return array(
'type'=>$result['type'],
'id'=>$result['id'],
'revoked'=> $revoked,
'verified'=>$verified,
'valid'=>($verified && !$revoked)
);
}
function getUserById($id,$con)
{
$query = $con->prepare("SELECT * FROM `users` WHERE `id` = :0");
$query->execute(array(":0"=>$id));
$result = $query->fetch(PDO::FETCH_ASSOC);
if(!$result)
return false;
return $result;
}
function is_deactivated($userArr = false,$con = false)
{
// Set default user empty
$user = false;
// If value is numeric (id)
if(is_numeric($userArr)) {
// Get the data by from database, assign to user
$user = getUserById($userArr,$con);
}
// If the value is an array, just assign to user
elseif(is_array($userArr))
$user = userArr;
// If the value is still empty, stop, return deactivated
if(empty($user))
return true;
else
// If user is valid (in db), return bool if they are revoked
return ($user['type'] == 'd');
}
function loginObserver(&$error,$con)
{
// See if the action to log in is set
if(isset($_POST['action']) && $_POST['action'] == 'login') {
// Run the verify function
$verify = verifyUser($_POST['username'],$_POST['password'],$con);
// If user is in db
if($verify['verified']) {
// See if they are revoked, send back error
if($verify['revoked']) {
$error = 'revoked';
return false;
}
// Assign your session id
$_SESSION['user_id'] = $verify['id'];
// Return true for success
return true;
}
else {
// User was not in system, send invalid error
$error = 'invalid';
return false;
}
}
else
// Return a string so the subsequent logic knows that
// no attempt was made to log in.
return 'invalid';
}
Secondly, now that you have all your business logic stored away in contained functions (classes/methods) you can cleanly apply them to the page.
/login.php
<?php
// Put this at the very beginning. I would consider putting it on a config page and
// including it would be better because then you will have some consistency
// through your site
session_start();
// Add your functions and or classes, better yet would be to have an autoloader
// to load classes and a pseudo-autoloader to load functions
include('functions.php');
// Put your database connection at the top, on the config page would be better
include('db.php');
// Move logic to the top and pass errors to the page
$error = false;
// Run the observer function
$login = loginObserver($error,$con);
// Invalid means no attempt was made to login
if($login != 'invalid')
// If there are no errors (empty), redirect
if(!$error) {
// This needs to go before output of html to browser
header('location: adminpanel.php');
// Stops the script from processing the rest of the page
exit;
}
}
?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login - Admin panel</title>
</head>
<body>
<?php
// This is probably fine, it's likely just html
include('title_bar.php');
?>
<h3>Login Here: </h3>
<?php if($error) {
echo ($error == 'invalid')? 'Wrong username or password.':'Your access has been revoked by admin.';
} ?>
<form method='post'>
<!-- add an action here -->
<!-- You should do a token system for verifying submission authenticity -->
<input type="hidden" name="action" value="login" />
User name:
<input type='text' name='username' />
<br/><br/>
Password:
<input type='password' name='password' />
<br/><br/>
<input type='submit' name='submit' value='Login' />
</form>
</body>
</html>
Finally, this code is not tested so there may be errors in logic. It is intended to show you how to apply my (and perhaps other's comments practically). I don't want to say "Don't do this and don't do that" but don't show an alternative. This script is based on yours so you can identify similarities easier, but is no way implied this is the only way, or the correct way to do a login.

Implement Security to this application?

At the moment I am attempting to create an application that passes on data to delete a row in my database. This row will be known by the ID passed on by the html file to js.
Currently I have a Html file, Javascript and PHP file which all work together to get this data passed in.
What im looking to do is secure it so no-one unauthorised can just send data to the javascript document in-order to delete the row.
HTML -- > JS --> PHP
JS:
function deleteListing(id) {
var answer = confirm("Are you sure you want to delete this listing?")
if (answer) {
$.post("assets/scripts/deleteListing.php", {
id: id
},
function (result) {
var response = jQuery.parseJSON(result);
if (response.available === true) {
location.reload();
} else if (response.available === false) {
// alert("FAILURE DELETING USER");
} else if (response.root === true) {
// alert("Cannot Delete Root User..");
}
});
} else {
return;
}
}
PHP:
<?
require("../../../assets/config/config.php");
$id_retrieve = $_POST['id'];
$data = new stdClass();
$sth= $dbh-> prepare("SELECT * FROM listings WHERE id='".$id_retrieve."'");
$sth -> execute();
$row = $sth -> fetch();
$data->available = true;
$dbh->exec("DELETE FROM listings WHERE id = '".$id_retrieve."'");
echo json_encode($data);
?>
Before anyone says the statement is not created using the prepared statement, I am aware of this and will fix it asap. Apart from that, is there anyway I can secure the Javascript file from unauthorised access? or could I limit it somehow?
Thanks!
There are a couple of solutions.
As #Tobias said above: Use sessions to handle the authentication. That will protect you some.
However, that alone doesn't stop Cross-Session attacks.
Take a look at this page: http://phpsec.org/projects/guide/2.html
It suggests putting a token value on the form and saving it in the session. That way, when the form is submitted you can compare the incoming token against the one in your session and verify that the form did, indeed, come from your site.
<?php
session_start();
if (isset($_POST['message']))
{
if (isset($_SESSION['token']) && $_POST['token'] == $_SESSION['token'])
{
$message = htmlentities($_POST['message']);
$fp = fopen('./messages.txt', 'a');
fwrite($fp, "$message<br />");
fclose($fp);
}
}
$token = md5(uniqid(rand(), true));
$_SESSION['token'] = $token;
?>
<form method="POST">
<input type="hidden" name="token" value="<?php echo $token; ?>" />
<input type="text" name="message"><br />
<input type="submit">
</form>
<?php
readfile('./messages.txt');
?>

Execute a php function with field value after it has been entered

I have a form that ask the email of the new user. I got a php function that can use this email to get informations (firstname, lastname, office, job...) using a cURL request and return it into an array ($full_informations).
I want this function to be executed after an email has been entered. For different reasons, I cannot directly add code to my form, so I need something can be read somewhere else in the body or the head.
I got this field that is automatically populated by a script:
<input onKeyPress="" class="editingSize " type="text" id="emails" name="emails" size="" value="" maxlength="150">
I want to be able to send the value of this field to a php function such as
$full_informations = get_more_info_from_mail($email)
then I could do something like
$firstname = $full_informations['firstname'];
$lastname = $full_informations['lastname'];
$job = $full_informations['job'];
//...
and make these variables automatically inserted in my mysql DB without asking the user to complete the form (I know how to make that part).
So, again, my question is, how can I get my function to be called with the value of the field after the user has entered an email?
I suppose I'll need some ajax request but I'm not familiar with those at all.
Are you using a mysql database. You can achieve this in php like this:
Put this at the beginning of you page
<?
if (isset($_POST['submit'])) {
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$mail = $_POST['mail'];
$result = mysql_query("SELECT * FROM users WHERE email = $mail");
$row = mysql_fetch_row($result);
$firstName = $row[0]; //FirstName
$lastName = $row[1]; //LastName
$job = $row[2]; //Job
}
?>
You html should look like this:
<form action="" method="POST">
<input type="text" name="mail" />
<input type="submit" value="submit" name="submit" />
</form>
Hope this helps!
With jquery:
<script type="text/javascript">
$(function() {
$('#emails').on('blur',function() {
$.post('/path/to/your/php.php',
{email: $('#emails').val()},
function(json) {
alert('responded with '+json.response);
});
});
});
</script>
Your php script should look like this:
<?php
$email = $_GET['email'];
// make sure you verify the email is in a correct format.
// save it to a database
//if it succeeds:
echo json_encode(array('response'=>'success'));
//if it fails:
echo json_encode(array('response'=>'failure'));

How can I assign session id of php in a jQuery file?

I have a main file
index.php
in which I include four other files like
header_get_started.php,
content_main.php,
right_sec_home.php,
footer.php.
Here is my code
"index.php"
<script src="js/ajax.js"></script>
<?php include_once('header_getstarted.php'); ?>
<?php include_once('content_main.php'); ?>
<?php include_once('right_sect_home.php'); ?>
<?php include_once('footer.php'); ?>
"header_getstarted.php"
<span class="select_input">
<?php
$sqlCmd = "some query";
echo combo('cmb_command','custom-class1 custom-class2','cmd_name','cmd_id','0',$sqlCmd,'sendpostmtu()' $width="style='width:250px;cursor:pointer;'")
?>
<input type="submit" name="" class="sub_bg" value="" onclick="get_request_by_command($('#cmb_command').val());">
</span>
In header_get_started.php
When select any command from select box, I want to assign it's id to $_SESSION['id'].
Onclick of selection box I have an ajax request which can refresh the main content (content_main.php). Also I want that selected id in another page in right_sec_home.php to refresh it's content.
How can I assign the php session id in JS file for 2nd page?
My JS file is
function get_request_by_command (commandId) {
var cmdTitle=$('#cmb_command :selected').text();
if(cmdTitle=="") {
cmdTitle='ABC';
}
$("#main_wrap").hide();
if(cmdTitle=='--Select--'){
$("#cmdTitle").html("");
}else{
$("#cmdTitle").html(cmdTitle);
}
$("#cmbs_cmd").val(commandId);
document.getElementById('request_list').innerHTML='<img src="images/loader.gif" />';
var strURL="request_by_command_tbl.php?id="+commandId;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
var ret = req.responseText;
$("#requestTitle").html("<span id='cmdTitle'>"+cmdTitle+"</span>);
$('#request_list').html('');
$('#request_list').html(ret);
$('#main').show();
$("#searchDiv").show();
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
With using this jQuery function, I have created an ajax request, and send the id to the "request_by_command_tbl.php" file.
In "request_by_command_tbl.php" file i assigned,
$_SESSION['id'] = $_REQUEST['id'];
Also I want this $_SESSION['id'] in right_sec_home.php at same instant.
So is their any way to assign php $_SESSION['id'] in the jQuery script file before sending ajax request.
My other files
"content_main.php"
<div id="request_list"> </div>
<div> </div>
<div id="add_space"></div>
Right section home file in which i need session id
"right_sec_home.php"
<?php
function getRequestByMonth($month, $year, $id){
$que ="SELECT distinct(MS.date) FROM commands AS MC , ranks AS MR ,steady_tours AS MST, preferred_tours AS MPT, registration AS MMS where date_format(rm_date, '%c-%Y') = '".$month."-".$year."'
AND MMS.cmd_id ='".$_SESSION['id']."'
order by MMS.date";
$res = mysql_query($que);
while($rows[]=mysql_fetch_array($res)){}
foreach ($rows as $res):
if($res['date'] == "") continue;
$dt = date("Y-n-j", strtotime($res['date']));
$return[getDateB($dt)] = $res['date'];
endforeach;
return $return;
}
I hope that this is clear enough.
Any ideas?
Please help.
there is no way for you to access the session information with jquery ..
explanation
sessions are files stored on the server --> where is java script is only a client side language ..
there is always a work around .. but i guess you should explain more about what exactly you want to achieve
<?php $sessionId = session_id(); ?>
<input id="session_id" name="session_id" type="hidden" value="<?php echo $sessionId; ?>" />
Get the value of the hidden field using jquery.
You can use some hidden fields or script variables inside the php file.
example :
<script>
var id = <?php echo $_SESSION['id']; ?>;
</script>
varible id can be accessible using the javascript or jquery

[PHP / AJAX]: Change color of the message according to the entered text

In my website home page, I have a new user registration Form. It contains a field "User Name". When the user enters the user name and the focus is pointed to another field, an AJAX code is executed that checks whether any user with the entered username already exists or not.
The AJAX code that I am using is this:
function toggle_username(userid) {
if (window.XMLHttpRequest) {
http = new XMLHttpRequest();
} else if (window.ActiveXObject) {
http = new ActiveXObject("Microsoft.XMLHTTP");
}
handle = document.getElementById(userid);
var url = 'ajax.php?';
if(handle.value.length > 0) {
var fullurl = url + 'do=check_username_exists&username=' + encodeURIComponent(handle.value);
http.open("GET", fullurl, true);
http.send(null);
http.onreadystatechange = statechange_username;
}
else
{
document.getElementById('username_exists').innerHTML = '';
}
}
The file "AJAX.PHP" called by the above code, is like this:
<?php
mysql_connect ('localhost', 'MyServer', 'user1');
mysql_select_db('globaldb');
$do = $_GET['do'];
switch($do) {
case 'check_username_exists':
if(get_magic_quotes_gpc()) {
$username = $_GET['username'];
}else{
$username = addslashes($_GET['username']);
}
$count = mysql_num_rows(mysql_query("SELECT * FROM `student_login` WHERE `username`='".$username."'"));
header('Content-Type: text/xml');
header('Pragma: no-cache');
echo '<?xml version="1.0" encoding="UTF-8"?>';
echo '<result>';
if($count > 0) {
$_SESSION['UserExists'] = "true";
}else{
$_SESSION['UserExists'] = "false";
}
$_SESSION['UserExists'] = "false";
echo '</result>';
break;
default:
echo 'Error, invalid action';
break;
}
?>
In my registration form, just below the username input box, I want to define a section where in I can show the messages:
User with this name exists, or
Username is available.
In my home page, I am using following code:
<input name="username" type="text" id="username" onchange="toggle_username('username')" style="width:150px;" maxlength="40" size="22" >
<?PHP
if ($_SESSION['UserExists'] == "true")
{
echo "<div id='username_exists' style='font-size: 11px;font-weight: bold;color:red'>User with this name unavailable.</div>";
}
else
{
echo "<div id='username_exists' style='font-size: 11px;font-weight: bold;color:darkgreen'> User with this name is available </div>";
}
?>
The home page consists of the above code and the first code block (JavaScript) on top that I gave.
This code is not working. And I guess the reason is that I am have included the messages in the PHP block. Being server-side, it is not showing the messages.
Please let me know how to handle this issue. Whether to modify the JavaScript code that calls the AJAX or include something in the PHP.
Please also note that what actually I want is to show the messages in green or red color. If the user name is available, then green else in red color.
I'd do this using jQuery and have the PHP page return a code (0 for false, 1 for true) or similar. You can then use jQuery's addClass() method depending on the returned result, all in the javascript.
How about having ajax.php return a bit of pre-formatted HTML and using the statechange_username function, which you've set to process the response, to stick it in a placeholder div/span?
By the way, why are you setting a session variable?
I guess you are missing the statechange_username function, something like
function statechange_username()
{
if (http.readyState==4)
{
document.getElementById(\"username_eixsts\").innerHTML=http.responseText;
}
}

Categories