error correction for the PHP code - php

I have written the following code and not able to figure out the errors in it..
It not poping out any errors ..what it does is that it just stays on the html page
whats wrong in it?
html page
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
function get(){
$("#button1").click(function(){
$.post('script_1.php', { name: form.name.value },
function(output) {
$('#age').html(output).show();
}) ;
});
}
$("#button2").click(function(){
$('form#myForm').attr({action: "script_2.php"});
$('form#myForm').submit();
});
});
</script>
</head>
<body>
<form id="myForm" method="post">
doi: <input type="text" name="name"/>
<input type="button" id="button1" value ="Get" onclick="get();"/>
<input type="button" id="button2" value="Submit to script 2" />
title:<input type="text" name="title"/>
</form>
<div id="age"></div>
</body>
</html>
script_1.php for the first button is
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL ^ E_NOTICE);
//connect to database
$name = mysql_real_escape_string($_POST['name']);
if ($name==NULL)
echo "please enter an id!";
else
{
$age= mysql_query("SELECT title FROM parentid WHERE id ='$name'");
$age_num_rows = mysql_num_rows($age);
if ($age_num_rows==0)
echo "id does not exist";
else
{
$sql ="SELECT * FROM parentid WHERE id = '$name'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
$abc_output= "Existing data of the record <br />";
$abc_output .="Title: " . $row['title'] . "<br />" ;
$abc_output .="Report No: " . $row['reportno'] . "<br />" ;
$abc_output .="URL: " . $row['calc_url'] . "<br />" ;
$abc_output .="Institution: " . $row['institution'] . "<br />" ;
}
}
echo $abc_output;
}
}
?>
script_2.php is another php file
with update operation in database.
//title form is only used in script_2.php for updation.
script_1.php is used for displaying already present elements in DB.
Help appreciated.

There is a slight problem with your HTML and Javascript code. The way you declared the click functions, was improper. Try this:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#button1").click(function(){
$.post('script_1.php', { name: $('input[name$="name"]', '#myForm').val() },
function(output) {
$('#age').html(output).show();
});
});
$("#button2").click(function(){
$('form#myForm').attr({action: "script_2.php"});
$('form#myForm').submit();
});
});
</script>
</head>
<body>
<form id="myForm" method="post">
doi: <input type="text" name="name"/>
<input type="button" id="button1" value ="Get"/>
<input type="button" id="button2" value="Submit to script 2" />
title:<input type="text" name="title"/>
</form>
<div id="age"></div>
</body>
</html>
Here are your two SQL queries that you asked for:
$age= mysql_query("SELECT title FROM parentid WHERE id =(select id from parentid where name='$name')");
$sql ="SELECT * FROM parentid WHERE id = (select id from parentid where name='$name')";

a few things pop into mind, first, where you have this:
if ($name==NULL)
echo "please enter an id!";
it should be more like
if (empty($name))
echo "please enter an id!";
next, you have this:
$name = mysql_real_escape_string($_POST['name']);
and it should me more like
if(isset($_POST['name'])) $name = mysql_real_escape_string($_POST['name']);
else echo "they didnt use the form.";
and finally, i do not see and code to actually connect to a database.

Okay, i have a solution for you.
here is my example form
<form action='posted.php' method='post'>
<input type='submit' name='b1' value='Button 1' /><br />
<input type='submit' name='b2' value='Button 2' /><br />
</form>
and here is 'posted.php'
<?php
if(isset($_POST['b1'])) echo 'Button 1';
if(isset($_POST['b2'])) echo 'Button 2';
?>
when you press 'Button 1', the php gives 'Button 1', and the same goes for button 2.

Related

php returning a EMPTY echo. HOW / WHY?

I am having a very difficult time to figure out WHY I am getting this empty echo. I am debugging and I see all the values in the right place but it does not echo!
<body>
<div class='wrapper'>
<div id='message'>
<h2>Mail Sent Successfully!</h2>
<p>We will be in touch soon.</p>
<?php
// Echo session variables that were set on previous page
if (isset($_POST['first_name'])) {
session_unset();
session_destroy();
$_SESSION['name'] = isset ($_POST['first_name']) ? $_POST['first_name'] : "";
$_SESSION["favcolor"] = "Green ";
echo "name: " . $_SESSION['name'] . ".<br>";
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
}
?>
</div>
<form method="POST" id="myform" class="myform" title="Apply Title" action="<?php echo $_SERVER['PHP_SELF']; ?>" style="background-color:#FFFFFF;">
<fieldset>
<div>
<label class="title">First Name</label>
<input type="text" name="first_name" id='first_name' class="required" minlength="2" data-msg-required="Please enter your first name" maxlength='128' value="<?PHP if(isset($_POST['first_name'])) echo htmlspecialchars($_POST['first_name']); ?>">
</div>
<p id="invalid-first_name" class="error_msg"></p>
</fieldset>
<fieldset>
<div>
<label class="title">Your employer's company name.</label>
<input type="text" name="employer" id='employer'>
</div>
<p id="invalid-employer" class="error_msg"></p>
</fieldset>
<input type="button" name="submit" id="submit_app" class="sub" value="submit"/>
</form>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src='http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js'></script>
<script src='http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/additional-methods.min.js'></script>
<script type="text/javascript" src="formToWizard.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#myform").formToWizard({ submitButton: 'submit_app' });
jQuery.validator.setDefaults({
errorPlacement: function(error, element) {
error.appendTo('#invalid-' + element.attr('name'));
}
});
});
</script>
While debugging the code I can see all the value that just got typed. But once you submit the form it does not echo!
You are trying to echo non existent session. Put session_start() before assigning variables.
<?php
// Echo session variables that were set on previous page
if (isset($_POST['first_name'])) {
session_unset();
$_SESSION['name'] = $_POST['first_name'];
$_SESSION['favcolor'] = "Green";
echo "name: " . $_SESSION['name'] . ".<br>";
echo "Favorite color is " . $_SESSION['favcolor'] . ".<br>";
}
?>
EDIT:
I cleaned your code a little bit, try now. Dont destroy session, you can simply unset it if u need to. Also, im not sure what are you trying to do with $_SESSION['name'] = isset ($_POST['first_name']) ? $_POST['first_name'] : ""; so i changed that.

How to make selected value to appear in other page

I have following code:
<html>
<head>
<meta charset="UTF-8"/>
</head>
<body>
<!--See siin all tekstiväli-->
<H3>Minu küsitlused </H3>
<hr>
<br>
<br>
<br>
<ol>
<?php
include_once 'init/init.funcs.php';
$result = mysql_query('SELECT * from katse_kysimustik_pealkiri');
while($row = mysql_fetch_assoc($result)) {
$titles[] = $row['pealkiri'];
}
foreach($titles as $title) {?>
<li>
<?php echo $title ?>
<form action='Minu_kysitlused_1.php' method="post">
<input type="submit" name = "saada" value="saada"/>
<input type="button" value="tulemused"/>
<input type="button" value="lõpeta ennetähtaegselt"/>
<input type="button" value="X"/>
</li>
</form>
<?php
}
?>
</ol>
</body>
</html>
<?php
if(isset($_POST['saada'])){
header("Location:http://localhost/Praks/saada.html");
}
?>
Right now there is button "saada" for each title in database. When I click "saada", page saada.html will appear.
This is saada.html
<!doctype html>
<html>
<head>
<meta charset="UTF-8"/>
<title>Saada</title>
</head>
<form action="test1.php" method="POST">
<body>
<header>Küsitluse pealkiri</header>
<br>
Lisa sõnumile pealkiri:
<br>
<textarea rows='1' name='pealkiri'>Küsitluse algne pealkiri</textarea>
<br>
Lisa Adressaadid: <br>
<textarea rows='1' name='email'></textarea>
<br>
Lisa sõnum:
<br>
<textarea rows='4' name='tekst'></textarea>
<br><footer>
<INPUT TYPE="submit" VALUE="Saada" NAME="Saada">
</form>
<FORM METHOD="LINK" ACTION="Minu_kysitlused.html">
<INPUT TYPE="submit" VALUE="Loobu">
</footer>
</body>
</html>
My question is how could I make it work so value of $title appears in saada.html. The value of this $title which is next to 'saada' button I clicked. I need this value to be in this line instead of Küsitluse algne pealkiri:
<textarea rows='1' name='pealkiri'>Küsitluse algne pealkiri</textarea>
You can not have a value through PHP in HTML type page....change page extension to .php
then pass your $title in input hidden field in your form
like this
foreach($titles as $title) {?>
<li>
<?php echo $title ?>
<form action='Minu_kysitlused_1.php' method="post">
<input type="submit" name = "saada" value="saada"/>
<input type="button" value="tulemused"/>
<input type="button" value="lõpeta ennetähtaegselt"/>
<input type="button" value="X"/>
<input type="hidden" name="title" value="<?php echo $title;?>"/>
</li>
</form>
<?php
}
?>
Now set the cookie
<?php
if(isset($_POST['saada']))
{
if(isset($_REQUEST['title']))
{
$title = $_REQUEST['title'];
setcookie("page_title", $title, time()+3600);
}
header("Location:http://localhost/Praks/saada.html");
}
?>
Now on Your saada.html you can use js to retrieve cookie like this
JS Function Reference
var title = getCookie("page_title"); // retrieve cookie
document.getElementById('page_title').value = title; // put title into textaread
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
<textarea rows='1' name='pealkiri' id="page_title" >Küsitluse algne pealkiri</textarea>

set value of input field by php variable's value

I have a simple php calculator which code is:
<html>
<head>
<title>PHP calculator</title>
</head>
<body bgcolor="orange">
<h1 align="center">This is PHP Calculator</h1>
<center>
<form method="post" action="phptest.php">
Type Value 1:<br><input type="text" name="value1"><br>
Type value 2:<br><input type="text" name="value2"><br>
Operator:<br><input type="text" name="sign"><br>
Result:<br><input type"text" name="result">
<div align="center">
<input type="submit" name="submit" value="Submit">
</div>
</form>
</center>
<?php
if(isset($_POST['submit'])){
$value1=$_POST['value1'];
$value2=$_POST['value2'];
$sign=$_POST['sign'];
if($value1=='') {
echo "<script>alert('Please Enter Value 1')</script>";
exit();
}
if($value2=='') {
echo "<script>alert('Please Enter Value 2')</script>";
exit();
}
if($sign=='+') {
echo "Your answer is: " , $value1+$value2;
exit();
}
if($sign=='-') {
echo "Your answer is: " , $value1-$value2;
exit();
}
if($sign=='*') {
echo "Your answer is: " , $value1*$value2;
exit();
}
if($sign=='/') {
echo "Your answer is: " , $value1/$value2;
exit();
}
}
?>
All I want to do is that answer should be displayed in the result input field instead of echoing them separately. Please help? I Know it's simple but I am new in PHP.
One way to do it will be to move all the php code above the HTML, copy the result to a variable and then add the result in the <input> tag.
Try this -
<?php
//Adding the php to the top.
if(isset($_POST['submit']))
{
$value1=$_POST['value1'];
$value2=$_POST['value2'];
$sign=$_POST['sign'];
...
//Adding to $result variable
if($sign=='-') {
$result = $value1-$value2;
}
//Rest of your code...
}
?>
<html>
<!--Rest of your tags...-->
Result:<br><input type"text" name="result" value = "<?php echo (isset($result))?$result:'';?>">
inside the Form, You can use this code. Replace your variable name (i use $variable)
<input type="text" value="<?php echo (isset($variable))?$variable:'';?>">
Try this
<input class="qtytext-box" type="number" value= <?php echo $colll2; ?> >

Why isn't my php form passing the data

here is my code. I am not sure why after i input the first and last name the second page does not show the proper text.. The form is suppose to take in first name and last name into a text box.. Then on the next page when person submits it should validate that the proper type of data was input, and then print out text if it was not, or print out text if it was successful.
<body>
<h2 style="text-align:center">Scholarship Form</h2>
<form name="scholarship" action="process_Scholarship.php" method="post">
<p>First Name:
<input type="text" name="fName" />
</p>
<p>Last Name:
<input type="text" name="lName" />
</p>
<p>
<input type="reset" value="Clear Form" />
<input type="submit" name="Submit" value="Send Form" />
</form>
my second form
<body>
<?php
$firstName = validateInput($_POST['fName'],"First name");
$lastName = validateInput($_POST['lName'],"Last name");
if ($errorCount>0)
echo <br>"Please use the \"Back\" button to re-enter the data.<br />\n";
else
echo "Thank you for fi lling out the scholarship form, " . $firstName . " " . $lastName . ".";
function displayRequired($fieldName)
{
echo "The field \"$fieldName\" is required.<br />n";
}
function validateInput($data, $fieldName)
{
global $errorCount;
if (empty($data))
{
displayRequired($fieldName);
++$errorCount;
$retval = "";
}
else
{
$retval = trim($data);
$retval = stripslashes($retval);
}
return($retval);
}
$errorCount = 0;
?>
</body>

How can I use jQuery to submit a form using Ajax and then get the output of the page it submitted to?

I'm learning PHP and JavaScript, and I'm building a blogging platform. I'm working on the comment system. I want to check if the name field matches any users in the database, and if it does, then I want to display a message that the name is taken.
Here's the page that contains the form. (fullpost.php)
<!DOCTYPE html>
<html>
<?php
include ('functions.php');
connectDB();
$id = $_GET['id'];
$result = queryDB('SELECT * FROM posts WHERE id='.$id);
$post = mysql_fetch_array($result);
?>
<head>
<title><?php echo $post['title']; ?> - SimpleBlog</title>
<link rel="stylesheet" href="style.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.microsoft.com/ajax/jQuery.Validate/1.6/jQuery.Validate.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".commentform").validate();
});
</script>
</head>
<body>
<div id="header">
SimpleBlog
</div>
<div id="wrapper">
<?php
//post found, display it
if (mysql_num_rows($result) >0) {
echo '<div class="post">';
echo '<div class="postheader">';
echo '<h1>'.$post['title'].'</h1>';
echo '<h5>by '.$post['author'].' at '.$post['date'].' in '.$post['category'].'</h5>';
echo '</div>';
echo '<p>'.$post['fullpost'].'</p>';
echo '</div>';
//display comments form
?>
<div id="commentform">
<form action="commentsubmit.php" method="POST" class="commentform"/>
<?php
//if not logged in, display a name field
if (!loggedIn()) {
echo '<label for="author">Name: </label><br />';
echo '<input type="text" name="author" class="required"/><br />';
}
?>
<label for="comment">Comment: </label><br />
<textarea type="text" name="comment" class="required"></textarea><br />
<input type="hidden" value="<?php echo $id; ?>" name="postid"/>
<input type="submit" name="submit" Value="Submit" id="sendbutton" class="button"/>
</form>
</div>
<?php
}
else {
//no posts found
echo "That post doesn't exist!";
}
$result = queryDB('SELECT * FROM comments WHERE postid='.$id.' ORDER BY date DESC');
$numcomments = mysql_num_rows($result);
//comments found, display them
if (mysql_num_rows($result) >0) {
if (mysql_num_rows($result) == 1) {
echo '<h5>'.$numcomments.' Comment:</h5>';
}
if (mysql_num_rows($result) > 1) {
echo '<h5>'.$numcomments.' Comments:</h5>';
}
while($comment = mysql_fetch_array($result)) {
echo '<h6> by '.$comment['author'].' on '.$comment['date'].'</h6>';
echo '<p>'.$comment['text'].'</p>';
}
}
else {
//no comments found
echo '<h4>No comments</h4>';
}
?>
</div>
</body>
</html>
Here's the page it submits to. (commentnew.php)
<?php
//creates a new comment
include('functions.php');
//form submitted
if (isset($_POST['submit'])) {
//set $author if not logged in
if(!loggedIn()) {
//check if username is taken
connectDB();
$result = queryDB("SELECT * FROM users WHERE username='".$_POST['author']."'");
if (mysql_num_rows($result) > 0) {
die('That name is taken!');
}
else {
//username is not taken
$author = mysql_real_escape_string($_POST['author']);
}
}
else {
//user is logged in, set author to their username
$author = $_SESSION['username'];
}
//$author is set, submit
if (!empty($author)) {
$postid = mysql_real_escape_string($_POST['postid']);
$comment = mysql_real_escape_string($_POST['comment']);
$date = mysql_real_escape_string(date("Y-m-d")." ".date("H:i:s"));
queryDB('INSERT INTO comments (postid,date,author,text) VALUES ("'.$postid.'","'.$date.'","'.$author.'","'.$comment.'")');
echo 'Comment Sent!';
}
}
?>
I tried using $.ajax in the script tags, but it seems to do nothing. Can I get an example of how to properly use it? How do I get it to pull the message from commentnew.php? Am I going about checking for the username the wrong way? Should I be using jQuery's validation plugin somehow?
in general:
var form = $("form.commentform");
$.post(form.attr('action') , form.serialize(), function(data) {
alert("Response: " + data);
});
Try this
$("form.commentform").submit(function(e){
e.preventDefault();
$.post({
url: $(this).attr('action'),
data: $(this).serialize(),
success: function(reponse){
//here response will contain whatever you send from the server side page
}
});
}):
Look into jquery ajax function. That's what I use. http://api.jquery.com/jQuery.ajax/

Categories