I'm not understanding something at PHP handling - php

i'm new to programming so sorry if this question doesn't makes much sense.I learned PHP handling and i succeed at it. But i am not able to do something.
First take a look at the code...
<body>
<form action="get.php" method="get">
Username: <input type="text" name="name"><br>
<input type="submit"value="Connect" class="btn">
</form>
<>
</body>
</html>
And the get.php file:
<html>
<body>
Connected to: <?php echo $_GET["name"];?><br>
</body>
</html>
The output (connected to $name) will be on a blank page, without the other html and css elements. Is there a way to print the output right below the connect button ?

It's not the best approach in modern web programming, but since you're a beginner: you can combine the PHP connection logic with the HTML into the same file.
<!DOCTYPE html>
<html>
<body>
<form method="get">
Username: <input type="text" name="name" />
<input type="submit" value="Connect" class="btn" />
</form>
<?php
if (isset($_GET["name"])) {
echo "Connected to: " . $_GET["name"];
}
?>
</body>
</html>
Note that I omitted the action="...", in order to target to the current page.
By the way, a good approach will be to separate the business logic from the visual components (I recommend you to read about the MVC design pattern).
In addition, if you want to obviate refreshing the whole page, you can use JavaScript and AJAX (I recommend you to read about jQuery), but it's a bit more advanced.

The web is "stateless" and what it sounds like you want to do is to submit the form without refreshing the page. This can be done client side in JavaScript. The following for instance uses jQuery to make the JS you have to write smaller, but can (arguably should) done in straight JS.
<html>
<body>
<form action="get.php" method="get" id="the-form">
<label for="name">Username: <input type="text" id="name" name="name">
<br>
<input type="submit"value="Connect" class="btn">
</form>
<div id="response">
<?php
if(isset($_GET['name']))
{
include('get.php');
}
?>
</div>
</body>
</html>
<script src="path/to/jquery.min.js"></script>
<script>
$(#the-form).submit(function(event)
{
event.preventDefault();
$.ajax({
url: 'get.php',
type: 'get',
data: $("#the-form").serialize(),
success: function(data)
{
$('#response').append(data);
}
});
});
</script>
If you're not worried about the page refresh, then Reflection's answer is what you are looking for. That said, you could do both using the JS/ajax free version as a fall back and the AJAX version as a progressive enhancement.

Related

Taking values from form, pulling results from MySQL, and using AJAX for results

I am having a bit of trouble figuring out how exactly to make a certain connection. It's a project I thought might be simple enough for me to do on my own without help, but I've hit a wall unfortunately. It's an 'exercise generator' that basically asks a few basic questions, and based on your answers, it outputs a recommended workout routine. I've constructed the MySQL database with plenty of exercises, have successfully connected the database, and have made the form.
What I am having trouble though, however, is storing those form results into variables, and based on those variables (if workout days is 3, for example, there would only be 3 groups of workouts printed instead of 5) output a routine into the same div as the form, effectively replacing it with the answer instead of placing it underneath the submitted form.
Index.php
<!DOCTYPE html>
<html>
<?php $page_title = "Workout Generator"; ?>
<link rel="stylesheet" type="text/css" href="style.css">
<head>
<script type="text/JavaScript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js" ></script>
</head>
<body>
<?php include("header.php"); ?>
<?php include("connect.php"); ?>
<div id="appWindow">
<h3>Please answer the following questions and click 'Submit' to generate your workout routine.</h3>
<form id="homeForm" method="post" >
<label for="name">Name: </label>
<input type="text" name="name"><br>
<label for="age">Age: </label>
<input type="number" name="age"><br>
<label for="workoutdays">How many days a week can you workout?</label>
<select name="workoutdays">>
<option value="1">3</option>
<option value="2">5</option>
</select><br>
<label for="workoutstyle">Do you prefer a gym, or bodyweight exercises?</label>
<select name="workoutstyle">>
<option value="1">Gym</option>
<option value="2">Bodyweight</option>
</select><br>
<button type="submit" name="submit">Submit</button>
<button type="reset" name="reset">Reset</button>
<div class="form_result"></div>
</form>
<?php
$age = $_POST['age'];
$workoutdays = $_POST['workoutdays'];
$workoutstyle = $_POST['workoutstyle'];
?>
</div>
<br><br><br>
<?php include("footer.php"); ?>
</body>
</html>
I don't necessarily want an answer giving me the exact code to enter, but would appreciate being pointed in the right direction to get that form pulling data from MySQL, and using AJAX to print in the same window without refreshing.
THANK YOU
First of all, you need to post your request. With $.ajax this
//Do this thing on page load
$(function() {
//handle submit
$("#homeForm").submit(function(e) {
//customize your submit
e.preventDefault();
$.ajax({
type: "POST",
url: youURL, //maybe an url pointing to index.php
data: yourData, //attach everything you want to pass
success: function(response) {
$("#appWindow").html(response);
}
});
});
});
code should help. You need to make sure you pass the necessary elements and you provide the correct url. On server side, generate the desired html and send back as response.
In the script file
$(document).ready(function(){
$(document).on('click','#submit_btn',function(){
var url = '/xyz.php'; //full path of the function where you have written the db queries.
var data = '';//any data that you would like to send to the function.
$.post(url,{data: data}, function(result){
var arr = JSON.parse(result);
});
});
});
in your php file once your database query has been executed and you get the result. for example
$result = //result of your mysql query.
echo json_encode($result);
exit;

HTML editor embedded in admin page

I'm working on a simple webpage for a company and the company wants to be able to edit the content themselves from time to time. However they have no programing knowledge and therefore I want to use an embedded HTML editor, I have chosen jQuery TE.
The problem is that I only know how to use this as a form, e.g.:
<form id = "wyForm" method="post" action="test.php">
<textarea class="editor"name = "testText">Hi</textarea>
<input type="submit" class="wymupdate" />
</form>
Then I would convert the textarea to an editor with jQuery:
<script> $('.editor').jqte() </script>
This makes it possible to send the result to a .php page that updates the database. However many times I don't want to use a textfield or a form, but just a simple object that I convert to an editor in the same way. But how do I save the change in that case?
Catch the form submit event and copy the content to a hidden field.
<form id = "wyForm" method="post" action="test.php">
<div class="editor" name="testText">Hi</div>
<input type="submit" class="wymupdate" />
<input type="hidden" id="editorHiddenField" />
</form>
...
$('#wyForm').submit(function() {
$('#editorHiddenField').val($('.editor').html());
});
You may need to use an API to get the content instead (I'm not familiar with the plugin), but the concept is sound.
Edit - If you don't want to use a form at all:
<div class="editor></div>
<button id="SaveButton">Save</button>
...
$(document).ready(function() {
$('#SaveButton').click(function(e) {
e.preventDefault();
$.post('savepage.php', { data: $('.editor').html() }).done(function() { alert('saved!'); });
});
});

AJAX XMLHttpRequest not working

I'm trying to work with ajax. I have two pages: request.html and reply.php.
request.html:
<html>
<script language="javascript">
var xht = new XMLHttpRequest();
function testAJAX()
{
xht.open("get","http://localhost:9999//a.php", true);
xht.send();
xht.onreadystatechange=function() {
if (xht.readyState==4) {
alert("Text: "+xht.responseText);
}
}
}
</script>
<form id="form1" name="form1" method="post" action="">
btn
<input name="btn" type="submit" id="btn" onClick="testAJAX();" value="Submit" />
</form>
</html>
reply.php:
<?php
echo 'hi';
?>
The problem is that I don't get a response via xht.responseText and with xht.responseXML I get null and with xht.status I get 0.
I asked the link http://localhost:9999//a.php via browser and got hi correctly.
P.S: I tried this on Chrome 29.0.1547.18 and Maxthon v4.1.1
any ideas..
You don't need to mention "http://localhost".
The main mistake is you have given the input type as Submit If it is submit the form will be submitted first the click event will not trigger. Change the input type to button.
If you want to do form submission do it in java script
The corrected code is below.
<form id="form1" name="form1" method="post" action="">
btn
<input name="btn" type="button" id="btn" onClick="testAJAX();" value="Submit" />
// change type to button
</form>
var xht = new XMLHttpRequest();
function testAJAX()
{
xht.open("get","a.php", true); /// Change to a.php
xht.send();
xht.onreadystatechange=function() {
if (xht.readyState==4) {
alert("Text: "+xht.responseText);
}
}
}
Adding to SarathPrakash's answer, I would like to point out that there is nothing wrong with specifying localhost. It will still work as long as the PHP file's address is valid.
You can also have the submit button. But you'll have to modify the form opening tag as follows:-
<form id="form1" name="form1" method="POST" action="" onsubmit="return false">
This is will stop the default behaviour of the form being submitted. Although in my opinion, it is best to avoid it altogether, and just stick with assigning the correct event handler to the onclick attribute.
Also, it is good practice to follow the correct syntax for HTML documents.
<html>
<head>
<title> Your title here </title>
<script type="text/javascript"> Your script here </script>
</head>
<body>
Your main document text here. Forms, tables etc.
</body>
</html>
For a simple tutorial, you could try this.

PHP Working with Buttons and Functions

I'm having difficulties on the executing a php function with a button
I've been browsing through the net (and ofcourse here at stackoverflow) for a solution to this problem. However, still no luck.
This problem might have been asked many times in this site, but none of them seems to work to me (or am i just that poorly literate with programming).
What i am trying to achieve is to set a session variable once the button is clicked, and print it in the second page as it redirect.
here's what my first php page looks like:
<?php
session_start();
if(isset($_POST['submit']))
{
$_SESSION['testing']= "hello world";
}
?>
<form method="post" action="update.php">
<input type="submit" id="submit" name="sumbit" value="Submit" >
</form>
and here's the update.php:
<?php
session_start();
echo $_SESSION['testing'];
?>
It may look theres nothing wrong with it, but the script does not execute anything inside the "if(isset(..." statement.
I am using WAMP as a server and my PHP version is 5.3.13
PS: I am aware that PHP is a server-side programming, and what i'm trying to do is something similar to client-side scripting.
The problem is, i do not know how to work with javascripting and what they call it "Ajax" scripting.
Is there any way this could be fix? Is it possible to do this with PHP alone without using javascript or ajax?
Hi simply empty action like <form method="post" action=""> on form tag and redirect after session setting.like header("location:update.php");.Hope solve your problem.Your first page code will be
<?php
session_start();
if(!empty($_POST))
{
$_SESSION['testing']= "hello world";
header("location:update.php");
}
?>
<form method="post" action="">
<input type="submit" id="submit" name="sumbit" value="Submit">
</form>
While on update page
<?php
session_start();
echo $_SESSION['testing'];
?>
$.ajax({
type: "get",
url: "update.php",
success: function(){
alert("success");
// do something
}
});
Above is the example of jquery ajax.
Try this one:
First Page:
<form method="post" action="update.php">
<input type="submit" id="submit" name="sumbit" value="Submit" >
</form>
Update.php:
<?php
session_start();
$_SESSION['testing'] = 'Hello World';
echo $_SESSION['testing'];
?>
Since you want to print the session in the second page, you should put a value of session in update.php not in your first page..

Submit button clicking changing the value of it to another thing

maybe very easy!
I'm php coder and I don't have experience in js but I must do this for one of my codes
suppose I have sub1 in page after clicking it must be that sub1 but value now is sub2
<html>
<head>
<title>pharmacy</title>
</head>
<body>
<form method="post" action="pharmacy.php">
<?php
//some code
if(array_key_exists('update',$_POST)){
//somecode
}
?>
<input type="submit" name="update" value="<?php echo if(isset($_GET['update'])) ? 'Show' : 'Update' ?> ">
</form>
</body>
</html>
show as function name does not really make sense here (imo), but you could do:
<input type="submit" name="sub" value="sub1" onclick="show(this)">
and
function show(element) {
element.value = 'sub2';
}
Important:
But that will actually not solve your problem. As soon as you click the button, the form is submitted, meaning the browser initiates a new request and will load a new page. So every change you made the current page is lost anyway.
The question is: What are you trying to do?
It seems to me that you should change the value of the button on the server side. You have to keep track which form was submitted (or how often, I don't know what you are trying to do) and set the value of the button accordingly.
Update:
I see several possibilities to solve this:
You could keep using JavaScript and send and get the data via Ajax. As you have no experience with JavaScript, I would say you have to learn more about JavaScript and Ajax first before you can use it.
You could add a GET parameter in your URL with which you can know which label to show for the button. Example:
<form method="post" action="?update=1">
and
<input type="submit" name="sub" value="<?php echo isset($_GET['update']) ? 'Show' : 'Update' ?> ">
Similar to 2, but use a session variable (and not a GET parameter) to keep track of the state.
Update2:
As you are already having $_POST['update'] you don't need the URL parameter. It could just be:
<html>
<head>
<title>pharmacy</title>
</head>
<body>
<form method="post" action="pharmacy.php">
<input type="submit" name="update" value="<?php echo isset($_POST['update']) ? 'Update' : 'Show'; ?> ">
</form>
</body>
</html>
This should do it
function show(){
document.getElementsByName('sub')[0].value = 'sub2';
return false;
}
Edit: if you don't want it to submit the form, just add a return false, but then you'd need to change your onclick from your submit button to your forms onsubmit;
<html>
<head>
<title>test</title>
<script>
function show()
{
document.getElementById("sub").value= "sub2";
return true;
}
</script>
</head>
<body>
<form method="post">
<input type='submit' id="sub" name='sub' value="sub1" onclick="return show()">
</form>
</body>
</html>

Categories