I have a session variable that is set when the user submits a form with a certain option selected. When the page refreshes I need to test this session variable and if it exists then make some of the form read only. This is my code so far, php:
<?php
require("header.php");
if(isset($_REQUEST['searching'])){ //check if form has been submitted
echo"<h2>Submitted</H2><p>";
connect('final');//connect to DB
$fName = $_POST['addFname'];
$lName = $_POST['addLname'];
$address = $_POST['address']
$dropdown = $_POST['field']; // yes or no option
$fName = htmlspecialchars($fName);
$fName = mysql_real_escape_string($fName);
$lName = htmlspecialchars($lName);
$lName = mysql_real_escape_string($lName);
$address = htmlspecialchars($line2); // stop HTML characters
$address = mysql_real_escape_string($line2); //stop SQL injection
if($dropdown== "no"){
$_SESSION['name'] = "$fName";
}
?>
'field' is the name of my dropdown with 2 options yes and no.
MY JS for getting the variable:
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type = "text/javascript">
var session;
function multi(){
$.ajaxSetup({cache: false})
$.get('getSession.php', {requested: 'foo'}, function (data) {
session = data;
});
}
</script>
I use that to get the variable from the session, getSession.php has the following:
<?php
session_start();
if (isset($_GET['name'])) {
// return requested value
print $_SESSION[$_GET['name']];
} else {
print json_encode($_SESSION);
}
?>
finally I have this function to disable the text fields
<script language="JavaScript">
<!--
function enable_text2()
{
if (session !=""){
status = "true";
document.add.addFname.readonly=readonly;
document.add.addLname.readonly=readonly;
}
}
//-->
</script>
the rest of my html is just a form, this is all in one document with the php code at the top, and the javascript functions in the head tag.
I call a wrapper function in the body onload tag, which then calls both of those functions, I thought the first function would get the session variable if it existed from the php document and then the second function would test if it was not empty, if it wasn't then it would make the fields read only.
However when I select no in the drop down and submit the form, the page refreshes and nothing happens, the fields are not read only.
Why You are using javascript for it??
session_start();
if (isset($_GET['name'])) {
$disable=true;
} else {
$disable=false;
}
<input type="text" name="addFname" <?php if($disable) { ?> readonly="readonly" <?php } ?>
Here i have taken "addFname" .you can disable any element inside that php if condition
Assuming PHP is generating the page you've got this "must be disabled" form on, there's no need for an ajax call - PHP can output a JS variable when it builds the page, e.g.
<script type="text/javascsript">
var disableForm = <?php echo (($_SESSION['somevar'] == 'whatever' ? 'true' : 'false') ?>;
if (disableForm) {
...
}
</script>
Related
i want to create a button in html that runs a php script,
i have this script:
<?php
$user = JFactory::getUser();
$userToken = JSession::getFormToken();
if (!$user->guest) : ?>
Log out
and i want to use it in a html button
any help?
call a js function onclick of your button and send ajax request on your script file to run php script...
<input type="button" value="Run Script" onclick="run_script();"/>
<script>
function run_()
{
$.post("yourScripFile.php",function(data){
if(data != null)
{
alert(data);
}
});
}
</script>
And in your php script file
<?php
$user = JFactory::getUser();
$userToken = JSession::getFormToken();
if (!$user->guest)
{
echo 'Log out';
die;
}
else
{
echo "else code here"; die;
}
?>
You can use a $_POST or $_GET parameter and pass it with the click of the button. Just put the script in an if block in the same page if($_GET['act'] == "logout"){//run script} and add ?act=logout to your url when you want to trigger the script. Instead of $_GET you can use $_POST and a hidden input named act
This is my html with script
<div id="info" class="container-fluid">Here is some text</div>
<script src="js/jquery-2.1.4.js"></script>
<script src="js/bootstrap.js"></script>
<script type="text/javascript">
$.post("testPHP.php", {name: "John"}, function(data)
{
$( "#info" ).html( data )
})
</script>
and the php code
<?php
$name=$_POST['name'];
echo $name;
?>
In html I may see the name John displayed in the div with id info.
But when I run the php file I get this error
Notice: Undefined index: name in C:\xampp\htdocs\ticketing\testPHP.php
on line 2
How can I send a variable via Ajax to a php file and echo this?
Ajax in pass some extra data like type:"ajax"
and file in check
<?php
if (isset($_POST['type']) && $_POST['type']=='ajax') {
$name = $_POST['name'];
echo $name;
} else {
echo "You access with direct URL";
} ?>
Try to check if there is a post request in your testPHP.php
<?php
if (isset($_POST['name'])) {
$name = $_POST['name'];
echo $name;
} else {
// do something else here
}
It won't send any data because there is no form in it. No object will be serialized(input, select, etc.).
I created a php page and javascript code that contains some variables from the PHP page, this is a code that inserts php variables into the database using Javascript :
<?php
$id = "Kevin";
$user = "Calvin";
?>
<!-- include jquery library file-->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<!-- The ajax/jquery stuff -->
<script type="text/javascript">
function send(e){
if(e.keyCode == 13 && !e.shiftKey){
$(document).ready(function(){
//Get the input data using the post method when Push into mysql is clicked .. we pull it using the id fields of ID, Name and Email respectively...
//Get values of the input fields and store it into the variables.
var msg=$("#reply").val();
clear();
//here you start PHP->>
//here we put the PHP Variables ^^^^^^^^^///\\\
//use the $.post() method to call insert.php file.. this is the ajax request
$.post('full.php', {msgg: msg, from: <?php echo json_encode($id); ?>, to: <?php echo json_encode($user); ?>},
function(data){
$("#message").html(data);
$("#message").hide();
$("#message").fadeIn(200);
});
function clear() {
$("#myre :input").each( function() {
$(this) .val('');
});
}
});
}
}
</script>
and in the full.php page
<?php
mysql_connect("localhost","root","");
mysql_select_db("db");
$to=mysql_real_escape_string($_POST['to']);
$from=mysql_real_escape_string($_POST['from']);
$msg=mysql_real_escape_string($_POST['msgg']);
$to = mysql_real_escape_string($to);
$from = mysql_real_escape_string($from);
$msg = mysql_real_escape_string($msg);
if(empty($msg)){
exit();
}
$query=mysql_query("INSERT INTO `message`(`user`,`who`,`message`) VALUES ('$to','$from','$msg')");
if($query){
echo "Perfect!";
}else{
echo "Failed!!";
?>
so is there any way to put the Javascript code into another page and inject it using ajax?
Assign PHP variable's value to java script variable :
<script type="text/javascript">
var json{
"id":<?php echo $id;?>,
"user" : "<?php echo $user;?>"
};
</script>
Change this line from your code :
$.post('full.php', {msgg: msg, from: json.id, to: json.user}
Now you'll have separate js file like:
function send(e){
if(e.keyCode == 13 && !e.shiftKey){
$(document).ready(function(){
//Get the input data using the post method when Push into mysql is clicked .. we pull it using the id fields of ID, Name and Email respectively...
//Get values of the input fields and store it into the variables.
var msg=$("#reply").val();
clear();
//here you start PHP->>
//here we put the PHP Variables ^^^^^^^^^///\\\
//use the $.post() method to call insert.php file.. this is the ajax request
$.post('full.php', {msgg: msg, from: json.id, to: json.user},
function(data){
$("#message").html(data);
$("#message").hide();
$("#message").fadeIn(200);
});
function clear() {
$("#myre :input").each( function() {
$(this) .val('');
});
}
});
}
}
Say this file is myjs.js now include it in php file:
<script type="text/javascript" src="myjs.js" />
I do not know if there is a better way to do this but I use this way (tell me if I am wrong) I want to make some JavaScript to show something if the user is logged in and hide that thing if the user is not logged in. but the function that did the log in credentials check is written in PHP :
function login()
{
$username = $_POST['username'];
$password = md5($_POST['password']);
$url = $_POST['url'];
$users = $GLOBALS['db']->query("SELECT * FROM users WHERE username='$username' AND password='$password'") or $GLOBALS['db']->raise_error(); // Leaving 'raise_error()' blank will create an error message with the SQL
$users_number = $GLOBALS['db']->num_rows($users);
if(!empty($users_number))
{
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
$_SESSION['is_logged'] = 'yes';
header('Location:?'.$url);
}
}
I am trying to get and check this value of $_SESSION['is_logged'] in JavaScript but I could not is there a way to pass or to read this value from jquery or javaScript
js file:
$(".link_to_comment a").live('click',function(){
//if you are not logged in you will see a log in box (with a link to register if you are not)
if(session == 'no')
{
$("#forum").html("<form name='login_form' action='?page=functions.php&fun=login' method='post'><table><tr><td>Username:</td><td><input type='text' name='username'></td><td>error</td></tr><tr><td>Password:</td><td><input type='password' name='password'></td><td>error</td></tr><tr><td></td><td><input type='submit'></td><td>error</td></tr><tr><td></td><td><input type='hidden' name='url' value="+url+"></td><td></td></tr></table>");
}
//if you are logged in you will add your comment here
else if(session == 'yes')
{
$("#forum").find(".make_a_comment").show();
$("#forum").find(".link_to_comment").hide();
}
});
the session varibale in js file should contain $_SESSION['is_logged'] but how this is my question????
You could output the variable as a <script> within the page itself, in the global scope. This would give any external Javascript files access to the variable:
<script>
var loggedIn = <?php echo isset($_SESSION['is_logged']) && $_SESSION['is_logged'] == 'yes' ? 'true' : 'false'; ?>;
</script>
This would output var loggedIn = true; or var loggedIn = false; depending on the session variable.
Now in any other Javascript you can check the variable:
if(loggedIn == false)
{
$("#forum").html("<form name='login_form' action='?page=functions.php&fun=login' method='post'><table><tr><td>Username:</td><td><input type='text' name='username'></td><td>error</td></tr><tr><td>Password:</td><td><input type='password' name='password'></td><td>error</td></tr><tr><td></td><td><input type='submit'></td><td>error</td></tr><tr><td></td><td><input type='hidden' name='url' value="+url+"></td><td></td></tr></table>");
}
Keep in mind that you need to output the variable before any other Javascript, otherwise the variable might not exist before the other script tries to access it.
yes you can assign value to on global variable in script tag then you can use in jquery function with variable name
var isUserLoggedIn = <?php echo ($_SESSION['is_logged']) ? "true" : "false"; ?>
let me know if i can help you more.
Your js code:
session = "<?php echo $_SESSION['logged_in']; ?>";
since I have not used var so it means it is globally available in all js files.
alert(session); //will return you the value of S_SESSION
You could create dynamic Javascript code through PHP, i.e.:
var isLogged = <?php echo (isset($_SESSION['is_logged']) && $_SESSION['is_logged']) ? "true" : "false"; ?>
This way, you can dynamically create a Javascript variable isLogged that you can use in your Javascript code
i have made a login form on a light box using a javascript function. Now i want to store a value on session variable, so to check if the user has logined , and not to show him login lightbox again and again on his navigations on the page.. My javascript function is:
<script language="javascript" type="text/javascript">
function createlightbox()
{
document.getElementById('light').style.display='block';
document.getElementById('fade').style.display='block'
}
function closelightbox()
{
document.getElementById('light').style.display='none';
document.getElementById('fade').style.display='none'
}
function checksession()
{ if (admin=="admin")
{closelightbox();}
else
{createlightbox();}
}
function check(form)/*function to check userid & password*/
{
/*the following code checkes whether the entered userid and password are matching*/
if(form.name.value == "admin" && form.password.value == "admin")
{
closelightbox();
var admin = <?php $_SESSION['Admin']= 1; ?>
}
else
{
document.getElementById("error").style.display='block';/*displays error message*/
}
}
</script>
And i m calling the checksession function in my forms onsubmit event as
<form id="Admin" onreset="checksession()">
The problem is, on every reset or submit of form, even on the page changes, the login form is shown. Why it is not checking the check session function.
Please tell me any fault i m making
i'm not sure where your conditions are.
but the following code should present in php script that generates your lightbox:
<?php echo '<script> var admin ='.$_SESSION['Admin'].'</script>'; ?>
(to check above is working correctly, you could View source code of your page and see if there is a line like: <script> var admin =1</script>)
the following should be before you access admin variable setted above:
<script language="javascript" type="text/javascript">
.... //other code
function checksession()
{ if(admin =="admin")
{closelightbox();}
else
{createlightbox();}
}
....
also note that if statement should compare == not assign =