PHP - Can't get text from textbox throught get and post - php

I have 3 textboxes and i can't get it value with $_GET and $_POST options. I need something like this:
-I fill textboxes with text
-I click button
-I activate function when clicking button
-In this function I recieve text from textboxes
-I save it to file (saving to file works ;) )
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>One Hit Point</title>
<link href="Bez_nazwy1.css" rel="stylesheet">
<link href="test.css" rel="stylesheet">
</head>
<body>
<form action="<?php $_PHP_SELF ?>" method="GET">
<label for="" id="Label1" style="position:absolute;left:67px;top:16px;width:194px;height:31px;line-height:31px;z-index:0;">Imię</label>
<input type="text" id="x11" name="x1" style="position:absolute;left:158px;top:23px;width:196px;height:16px;z-index:1;" value="">
<label for="" id="Label2" style="position:absolute;left:67px;top:63px;width:289px;height:31px;line-height:31px;z-index:2;">Nazwisko</label>
<input type="text" id="x22" name="x2" style="position:absolute;left:158px;top:70px;width:196px;height:16px;z-index:3;" value="">
<label for="" id="Label3" style="position:absolute;left:67px;top:111px;width:194px;height:31px;line-height:31px;z-index:5;">Telefon</label>
<input type="text" id="x33" name="x3" style="position:absolute;left:158px;top:118px;width:196px;height:16px;z-index:6;" value="+48 ">
<input type="button" id="Button1" onclick="<?php costam() ?>;" name="" value="Zatwierdź" style="position:absolute;left:194px;top:164px;width:96px;height:25px;z-index:7;">
</form>
</body>
<body>
<?php
//window.location.href='./niespodzianka.html';return false;
function costam(){
$imie= $_GET['x1'];
$Nazwisko=$_GET['x2'];
$Numer= $_GET['x3'];
//łączenie
$dane=$imie.", ".$Nazwisko.", ".$Numer;
//dodawanie nowej linii
$popr=$dane." k\n";
//otwieranie, zapisanie, zamknięcie
$plik=fopen("zap.txt", "a");
fputs($plik, $popr);
fclose($plik);
}
?>
</body>
</html>
EDIT:
new code (now there are 2 files):
File 1 (dz.php):
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>One Hit Point</title>
<link href="Bez_nazwy1.css" rel="stylesheet">
<link href="test.css" rel="stylesheet">
</head>
<body>
<form action="pliki.php" method="GET">
<label for="" id="Label1" style="position:absolute;left:67px;top:16px;width:194px;height:31px;line-height:31px;z-index:0;">Imię</label>
<input type="text" id="x11" name="x1" style="position:absolute;left:158px;top:23px;width:196px;height:16px;z-index:1;" value="">
<label for="" id="Label2" style="position:absolute;left:67px;top:63px;width:289px;height:31px;line-height:31px;z-index:2;">Nazwisko</label>
<input type="text" id="x22" name="x2" style="position:absolute;left:158px;top:70px;width:196px;height:16px;z-index:3;" value="">
<label for="" id="Label3" style="position:absolute;left:67px;top:111px;width:194px;height:31px;line-height:31px;z-index:5;">Telefon</label>
<input type="text" id="x33" name="x3" style="position:absolute;left:158px;top:118px;width:196px;height:16px;z-index:6;" value="+48 ">
<input type="button" id="Button1" onclick="location.href='pliki.php'" name="" value="Zatwierdź" style="position:absolute;left:194px;top:164px;width:96px;height:25px;z-index:7;">
</form>
</body>
</html>
File 2 (pliki.php):
<?php
//window.location.href='./niespodzianka.html';return false;
$imie= $_GET['x1'];
$Nazwisko=$_GET['x2'];
$Numer= $_GET['x3'];
//łączenie
$dane=$imie.", ".$Nazwisko.", ".$Numer;
//dodawanie nowej linii
$popr=$dane." k\n";
//otwieranie, zapisanie, zamknięcie
$plik=fopen("zap.txt", "a");
fputs($plik, $popr);
fclose($plik);
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Bez nazwy</title>
<meta name="generator" content="WYSIWYG Web Builder 14 - http://www.wysiwygwebbuilder.com">
<link href="Bez_nazwy1.css" rel="stylesheet">
<link href="niespodzianka.css" rel="stylesheet">
</head>
<body>
<div id="wb_TextArt1" style="position:absolute;left:16px;top:13px;width:867px;height:470px;z-index:0;">
<img src="images/img0001.png" id="TextArt1" alt="Bede dzownić xd" title="Bede dzownić xd" style="width:867px;height:470px;"></div>
</body>
</html>

That code can't works. You can't call PHP function using javascript onclick.
For your clarification this code would execute costam() function everytime page is loaded.
Try to change Button1 with:
<input type="submit" id="Button1" name="submit" value="Zatwierdź" style="position:absolute;left:194px;top:164px;width:96px;height:25px;z-index:7;">
Then change php code in:
<?php
if($_GET['submit']){
$imie= $_GET['x1'];
$Nazwisko=$_GET['x2'];
$Numer= $_GET['x3'];
//łączenie
$dane=$imie.", ".$Nazwisko.", ".$Numer;
//dodawanie nowej linii
$popr=$dane." k\n";
//otwieranie, zapisanie, zamknięcie
$plik=fopen("zap.txt", "a");
fputs($plik, $popr);
fclose($plik);
}
This should works, but is not a good approch. Also the page will refresh.
If you're familiar with jQuery:
jQuery.ajax({
type: "POST",
url: 'your_functions_address.php',
dataType: 'json',
data: {functionname: 'add', arguments: [1, 2]},
success: function (obj, textstatus) {
if( !('error' in obj) ) {
yourVariable = obj.result;
}
else {
console.log(obj.error);
}
}
});
This may help you: Call php function from JavaScript

Related

$_SESSION not storing values

I am having an issue with storing $_SESSION variables, i am a little new at PHP and I like it to the extent of my current knowledge.
first my creds:
Win 7 Pro 64
PHP 5
Remote Server(not sure of its config)
So what I am trying to do is set up a Login Page that contains a hardcoded username and password for testing purposes.
I want to display the username on a successor page to confirm it.
Login.php
<?php session_start();?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head >
<title>Login</title>
<link rel="stylesheet" href="style.css" type="text/css" media="screen" />
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta http-equiv="content-language" content="en-gb" />
<script type="text/javascript">
// Perform Client side validation of Username and Password
function redirect() {
var username = document.getElementById("username");
var password = (document.getElementById("password"));
if (!username.value == " ") {
if (!password.value == " ") {
if (username.value == "aknight") {
if (password.value == "00226291") {
window.location = "Home.php";
exit();
} else
alert("Username or Password Invalid");
}
} else
alert("Password is required");
} else
alert("Username is required");
}
</script>
</head>
<body>
<div id="header">
<h1>Product Order System</h1>
<br/>
<h2>The most expensive crap youll ever find...</h2>
</div>
<div id="content">
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$_SESSION['username'] = $_POST['username'];
}else{
?>
<form action="" method="POST">
<fieldset>
<legend>Login Information</legend>
<p>
<label for="Username">Username:</label>
<input type="text" name="username" id="username" />
</p>
<p>
<label for="Password">Password:</label>
<input type="password" name="password" id="password" />
</p>
<p>
<input type="button" name="login" value="Login" onclick="redirect();"/>
<input type="button" name="cancel" value="Cancel" />
</fieldset>
</form>
<?php }
include ('includes/footer.html');
?>
home.php
<?php
session_start();
$page_title = 'Home';
include ('includes/header.php');
if(isset($_SESSION['username'])) { $name = $_SESSION['username'];}else{echo "<p>error</p>";}
echo "<h3>Welcome ".$name."!</h3>" ;
?>
I have tried printing out the $_SESSION values and they are coming up empty.
producing this result
<?php
echo "<pre>".print_r($_SESSION)."</pre>";
?>
Array {
[username] =>
}
Please do not mind the JS, it is preschool client validation just to move forward.
Any help would be greatly appreciated.
Give your login form a name, and then in your JavaScript validation function, instead of window.location, do a document.forms['yourformname'].submit().
I think your Javascript validation is actually what's causing the issue.
You're setting the session variable in Login.php using the POST request, but no POST is actually being sent to Login.php since your Javascript is redirecting to Home.php once the form is considered valid. You need to submit the form at some point in the process, so you actually get some POST values which you'll use to populate your SESSION variables.
If you want to keep your Javascript validation, maybe have a look at submit() : http://www.w3schools.com/jsref/met_form_submit.asp
You'll have to set a correct action property on your form before submitting it.
So heres a fix that seems to be working
<?php session_start();?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head >
<title>Login</title>
<link rel="stylesheet" href="style.css" type="text/css" media="screen" />
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta http-equiv="content-language" content="en-gb" />
<script type="text/javascript">
// Perform Client side validation of Username and Password
function redirect() {
var username = document.getElementById("username");
var password = (document.getElementById("password"));
if (!username.value == " ") {
if (!password.value == " ") {
if (username.value == "aknight") {
if (password.value == "00226291") {
document.forms[0].submit();
exit();
} else
alert("Username or Password Invalid");
}
} else
alert("Password is required");
} else
alert("Username is required");
}
</script>
</head>
<body>
<div id="header">
<h1>Product Order System</h1>
<br/>
<h2>The most expensive crap youll ever find...</h2>
</div>
<div id="content">
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$_SESSION['username'] = $_POST['username'];
header('Location : ../Home.php');
}else{
?>
<form action="Home.php" name="login" method="POST">
<fieldset>
<legend>Login Information</legend>
<p>
<label for="Username">Username:</label>
<input type="text" name="username" id="username" />
</p>
<p>
<label for="Password">Password:</label>
<input type="password" name="password" id="password" />
</p>
<p>
<input type="button" name="login" value="Login" onclick=" redirect();"/>
<input type="button" name="cancel" value="Cancel" />
</fieldset>
</form>
<?php }
include ('includes/footer.html');
?>
Will post again if the nex series of pages has a similiar issue
Thanks

POST Method not working with jquery.mobile-1.4.0.min.js

I am developing a phonegapp app. Have a simple login form in action.php file and for test purpose I am just printing the submit variable in other file see.php.
Issue is that if I include following line of code in action.php then submitted variables from form are not getting printed:
<script src="http://code.jquery.com/mobile/1.4.0/jquery.mobile-1.4.0.min.js" type="text/javascript"></script>
But If I remove the above line from action.php, form is getting submitted properly and input variables are getting printed in see.php
action.php
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Application</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.0/jquery.mobile.structure-1.4.0.min.css" />
<link href='http://fonts.googleapis.com/css?family=EB+Garamond&subset=latin,cyrillic-ext,vietnamese,latin-ext,cyrillic' rel='stylesheet' type='text/css'>
<script src="http://code.jquery.com/jquery-1.10.2.min.js" type="text/javascript"></script>
<script src="http://code.jquery.com/mobile/1.4.0/jquery.mobile-1.4.0.min.js" type="text/javascript"></script>
</head>
<body>
<form action="see.php" method = "post">
<label for="Cedula" style="font-size:10px; color:#FFF; text-shadow:none">Cedula</label>
<input type="text" name="usr" id="usr" value="username" data-clear-btn="true">
<label for="Contrasena" style="font-size:10px; color:#FFF; text-shadow:none">Contrasena</label>
<input type="password" name="pwd" id="pwd" value="password" data-clear-btn="true">
<input type="submit" data-role="button" style="font-weight:100" value="Submit"/>
</form>
</body>
</html>
see.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
$uid = $_POST['usr'];
$upwd = $_POST['pwd'];
echo $uid;
echo "<br>";
echo $upwd;
echo "<br>";
?>
As you see in console ( network ) , see.php is being called and values of post are printed . You can turn your firebug ON and check the results ..
In jQuery Mobile, form submissions are automatically handled using Ajax whenever possible
To submit the form normally you can use data-ajax="false" in form
<form data-ajax="false" action="" method="">

Jquery, PHP Calling other form after click

Im just learning javascript the last days (started PHP some months ago).
So, my code make this:
e.g
http://controljuridico.com/video01/
I have three files.
An Html file with the form.
A javascript file with the functions after click on "enviar" (send) button.
A php that process the data.
HTML file (index.html)
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>index</title>
<link href="css/css.css" type="text/css" rel="stylesheet" media="screen" />
<script src="js/jquery.js" type="text/javascript" language="JavaScript"></script>
<script src="js/js.js" type="text/javascript" language="JavaScript"></script>
</head>
<body>
<div id="content">
<h1>Test.</h1>
<h1>Step 1) choose city</h1>
<br />
<br />
<label>test(*)</label>
<hr />
<br />
<form name="form_data" id="form_data">
<label>(*) City</label>
<br />
Medellin
<input type="radio" name="ciudad" value="Medellin" />
Manizales
<input type="radio" name="ciudad" value="Manizales"/>
Cali
<input type="radio" name="ciudad" value="Cali"/>
<br />
<label>(*) Especialidad</label>
<br />
<input type="button" value="Enviar" id="btn_enviar" />
<br />
<br />
<label id="mensaje"></label>
</form>
<div id="resultado" ></div>
</div>
</body>
</html>
js.js File
$(document).ready(function(){
$('#btn_enviar').click(function(){
if( validaRadio( 'ciudad','Ciudad' ) == false) return false;
$.ajax({
type:'POST',
url :'upload.php',
data: $('#form_data').serialize(),
beforeSend : function(){
$('#mensaje').html('Enviando datos...');
},
success: function (data){
$('#mensaje').html('Datos enviados correctamente.');
$('#resultado').html(data);
},
complete: function(){
$('#form_data').slideUp();
$('#resultado').slideDown();
}
});
});
});
Php File (upload.php)
<?php
$sergu = $_POST['ciudad'];
if ($_POST['ciudad'] == "Medellin") {
?>
<label>Ciudad Ingresada:</label>
<br />
<label><?php echo $_POST['ciudad'] ?></label>
<hr />
<?php
}else{
echo "it is not medellin....";
}
?>
So, this works very well but. What if I want this:
After click on "enviar" button also show another similar form at the left of this form.
I mean its just like choosing steps if you choose the step one I need another step and so on and I want that this another step just appear to the left of the previus form.
It is possible? how?
Thanks in advance for your help! I really appreciate it.
You could for example just hide the 'second form' when the page first loads via css like this:
<form id="second_form" style="display: none">...
and when your success function fires you remove the css like so:
success: function(){
...
$('#second_form').show();
}
Short answer: yes.
In jquery, there is .insertBefore(). An easy way to implement what you (kind of) want, is to just echo out the new form in the php, and instead of
$('#resultado').html(data);
Do the following:
$(data).insertBefore('#resultado');
This will insert the new form, echoed out by the PHP, under the previous one. Ofcourse you also have to delete the
$('#form_data').slideUp();
Else, the forms will be hidden.

<!DOCTYPE HTML> declaration causes div contents to NOT display

I have an html page which contains a div that displays the html from an external php file.
It works great until I add a DOCTYPE declaration to the html page. The page continues to function, except the external content does not appear in the div.
<!DOCTYPE HTML>
<html dir="ltr" lang="en-US">
<head>
<title>Test Page</title>
<!--meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"-->
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<script type="text/javascript" src="./inc/jquery.js"></script>
<script type="text/javascript">
function getinfo()
{
$.post('prodinfo.php', { prodcode: prodcodeform.prodcodevar.value},
function(output)
{
$('#prodinfo').html(output).show;
});
}
function hideinfo()
{
$('#prodload').hide();
$('#openprodinfo').show();
}
function showinfo()
{
$('#prodload').show();
$('#openprodinfo').hide();
}
</script>
</head>
<body>
<input style="position:relative;" type="button" class="button" id="openprodinfo" title="Open" value="INFO" onclick="showinfo();">
<DIV id="prodload" style="position:absolute;margin-left:auto;margin-right:auto;display:none;text-align:center;background-color:#000000;z-index:200;border:1px solid #4e443b;">
<div id="prodinfo" style="position:relative;display:block;top:0;width:1000px;height:820px;background-color:#ffffff;margin-left:auto;margin-right:auto;">
</div>
<form name="prodcodeform">
<input type="text" readonly="readonly" id="prodcodevar" name="prodcodevar" value="nil" >
</form>
<div ID="prodinfobutton" style="position:relative;">
<input style="position:relative;" type="button" class="button" id="closeprodinfo" title="Close" value="CLOSE" onclick="document.getElementById('prodcodevar').value='nil'; hideinfo(); ">
</div>
<input type="button" id="button001" value="ONE" onclick="document.getElementById('prodcodevar').value='item1'; getinfo();">
<input type="button" id="button002" value="TWO" onclick="document.getElementById('prodcodevar').value='item2'; getinfo();">
</DIV>
</body>
</html>
You are switching to Standards mode, so your browser is no longer playing the game of being compatible with Internet Explorer 4.
prodcodeform.prodcodevar.value will error because prodcodeform is undefined.
You don't get a global variable for every element with an id or name in a document.
Change:
<form name="prodcodeform">
To
<form id="prodcodeform" method="post" action="prodinfo.php">
… and make it do something sane when a non-Ajax request gets posted (move it so it is around the buttons, make them submit buttons, and cancel the default event if the JS succeeds).
Then add:
var prodcodeform = document.getElementById('prodcodeform');
before you try to use the variable.
You started your body with </body> instead of <body>.

Get variable from PHP file using JQuery/AJAX

This is my first post here and I hope that someone will be able to help me.
For the past week I have been working on a project of mine. Apparently, I have stuck with the last part.
So basically, I have an AJAX chat and when I submit a line I send (using a Post method) the whole line to be analyzed (to a file named analysis.php).
The chat line is being analyzed and find the variable I needed by doing queries on a MySql Database.
All I need now, is to have this variable taken with JQuery-AJAX and put it on a div in my html file(so it can be displayed on the right-left-whatever of the chat).
Here are my files :
analysis.php
<?php
$advert = $row[adverts];
?>
ajax-chat.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>AJAX Chat</title>
<link rel="stylesheet" type="text/css" href="js/jScrollPane/jScrollPane.css" />
<link rel="stylesheet" type="text/css" href="css/page.css" />
<link rel="stylesheet" type="text/css" href="css/chat.css" />
</head>
<body>
<div id="chatContainer">
<div id="chatTopBar" class="rounded"></div>
<div id="chatLineHolder"></div>
<div id="chatUsers" class="rounded"></div>
<div id="chatBottomBar" class="rounded">
<div class="tip"></div>
<form id="loginForm" method="post" action="">
<input id="name" name="name" class="rounded" maxlength="16" />
<input id="email" name="email" class="rounded" />
<input type="submit" class="blueButton" value="Login" />
</form>
<form id="submitForm" method="post" action="">
<input id="chatText" name="chatText" class="rounded" maxlength="255" />
<input type="submit" class="blueButton" value="Submit" />
</form>
</div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script src="js/jScrollPane/jquery.mousewheel.js"></script>
<script src="js/jScrollPane/jScrollPane.min.js"></script>
<script src="js/script.js"></script>
</body>
</html>
So, I am basically trying to get the $advert from the analysis.php file(after the whole analyze is done) , and by using JQuery/AJAX pass it eventually to the ajax-chat.html file.
Any help is really appreciated. I have googled everything but haven't found something to help me.
Thanks in advance.
If I understand right, you need to use JSON. Here is a sample.
In your PHP write:
<?php
// filename: myAjaxFile.php
// some PHP
$advert = array(
'ajax' => 'Hello world!',
'advert' => $row['adverts'],
);
echo json_encode($advert);
?>
Then, if you are using jQuery, just write:
$.ajax({
url : 'myAjaxFile.php',
type : 'POST',
data : data,
dataType : 'json',
success : function (result) {
alert(result['ajax']); // "Hello world!" alerted
console.log(result['advert']) // The value of your php $row['adverts'] will be displayed
},
error : function () {
alert("error");
}
})
And that's all. This is JSON - it's used to send variables, arrays, objects etc between server and user. More info here: http://www.json.org/. :)

Categories