Purpose:
Call a PHP function to read data from a file and rewrite it. I used PHP only for this purpose - FileIO - and I'm new to PHP.
Solution?
I tried through many forums and knew that we cannot achieve it normal way: onClick event > call function. How can we do it, are there other ways, particularly in my case?
My HTML code and PHP code is on the same page: Admin.php.
This is HTML part:
<form>
<fieldset>
<legend>Add New Contact</legend>
<input type="text" name="fullname" placeholder="First name and last name" required /> <br />
<input type="email" name="email" placeholder="etc#company.com" required /> <br />
<input type="text" name="phone" placeholder="Personal phone number: mobile, home phone etc." required /> <br />
<input type="submit" name="submit" class="button" value="Add Contact" onClick="" />
<input type="button" name="cancel" class="button" value="Reset" />
</fieldset>
</form>
This is PHP part:
function saveContact()
{
$datafile = fopen ("data/data.json", "a+");
if(!$datafile){
echo "<script>alert('Data not existed!')</script>";
}
else{
...
$contact_list = $contact_list . addNewContact();
...
file_put_contents("data/data.json", $contact_list);
}
fclose($datafile);
}
function addNewContact()
{
$new = '{';
$new = $new . '"fullname":"' . $_GET['fullname'] . '",';
$new = $new . '"email":"' . $_GET['email'] . '",';
$new = $new . '"phone":"' . $_GET['phone'] . '",';
$new = $new . '}';
return $new;
}
Have a look at these code, I want to call saveContact when people click on Add Contact button. We can reload page if need so. FYI, I use JQuery, HTML5 in page as well.
Thanks,
There are two ways. the first is to completely refresh the page using typical form submission
//your_page.php
<?php
$saveSuccess = null;
$saveMessage = null;
if($_SERVER['REQUEST_METHOD'] == 'POST') {
// if form has been posted process data
// you dont need the addContact function you jsut need to put it in a new array
// and it doesnt make sense in this context so jsut do it here
// then used json_decode and json_decode to read/save your json in
// saveContact()
$data = array(
'fullname' = $_POST['fullname'],
'email' => $_POST['email'],
'phone' => $_POST['phone']
);
// always return true if you save the contact data ok or false if it fails
if(($saveSuccess = saveContact($data)) {
$saveMessage = 'Your submission has been saved!';
} else {
$saveMessage = 'There was a problem saving your submission.';
}
}
?>
<!-- your other html -->
<?php if($saveSuccess !== null): ?>
<p class="flash_message"><?php echo $saveMessage ?></p>
<?php endif; ?>
<form action="your_page.php" method="post">
<fieldset>
<legend>Add New Contact</legend>
<input type="text" name="fullname" placeholder="First name and last name" required /> <br />
<input type="email" name="email" placeholder="etc#company.com" required /> <br />
<input type="text" name="phone" placeholder="Personal phone number: mobile, home phone etc." required /> <br />
<input type="submit" name="submit" class="button" value="Add Contact" onClick="" />
<input type="button" name="cancel" class="button" value="Reset" />
</fieldset>
</form>
<!-- the rest of your HTML -->
The second way would be to use AJAX. to do that youll want to completely seprate the form processing into a separate file:
// process.php
$response = array();
if($_SERVER['REQUEST_METHOD'] == 'POST') {
// if form has been posted process data
// you dont need the addContact function you jsut need to put it in a new array
// and it doesnt make sense in this context so jsut do it here
// then used json_decode and json_decode to read/save your json in
// saveContact()
$data = array(
'fullname' => $_POST['fullname'],
'email' => $_POST['email'],
'phone' => $_POST['phone']
);
// always return true if you save the contact data ok or false if it fails
$response['status'] = saveContact($data) ? 'success' : 'error';
$response['message'] = $response['status']
? 'Your submission has been saved!'
: 'There was a problem saving your submission.';
header('Content-type: application/json');
echo json_encode($response);
exit;
}
?>
And then in your html/js
<form id="add_contact" action="process.php" method="post">
<fieldset>
<legend>Add New Contact</legend>
<input type="text" name="fullname" placeholder="First name and last name" required /> <br />
<input type="email" name="email" placeholder="etc#company.com" required /> <br />
<input type="text" name="phone" placeholder="Personal phone number: mobile, home phone etc." required /> <br />
<input id="add_contact_submit" type="submit" name="submit" class="button" value="Add Contact" onClick="" />
<input type="button" name="cancel" class="button" value="Reset" />
</fieldset>
</form>
<script type="text/javascript">
$(function(){
$('#add_contact_submit').click(function(e){
e.preventDefault();
$form = $(this).closest('form');
// if you need to then wrap this ajax call in conditional logic
$.ajax({
url: $form.attr('action'),
type: $form.attr('method'),
dataType: 'json',
success: function(responseJson) {
$form.before("<p>"+responseJson.message+"</p>");
},
error: function() {
$form.before("<p>There was an error processing your request.</p>");
}
});
});
});
</script>
<div id="sample"></div>
<form>
<fieldset>
<legend>Add New Contact</legend>
<input type="text" name="fullname" placeholder="First name and last name" required /> <br />
<input type="email" name="email" placeholder="etc#company.com" required /> <br />
<input type="text" name="phone" placeholder="Personal phone number: mobile, home phone etc." required /> <br />
<input type="submit" name="submit" id= "submitButton" class="button" value="Add Contact" onClick="" />
<input type="button" name="cancel" class="button" value="Reset" />
</fieldset>
</form>
<script>
$(document).ready(function(){
$("#submitButton").click(function(){
$("#sample").load(filenameofyourfunction?the the variable you need);
});
});
</script>
You don't need javascript for doing so. Just delete the onClick and write the php Admin.php file like this:
<!-- HTML STARTS-->
<?php
//If all the required fields are filled
if (!empty($GET_['fullname'])&&!empty($GET_['email'])&&!empty($GET_['name']))
{
function addNewContact()
{
$new = '{';
$new .= '"fullname":"' . $_GET['fullname'] . '",';
$new .= '"email":"' . $_GET['email'] . '",';
$new .= '"phone":"' . $_GET['phone'] . '",';
$new .= '}';
return $new;
}
function saveContact()
{
$datafile = fopen ("data/data.json", "a+");
if(!$datafile){
echo "<script>alert('Data not existed!')</script>";
}
else{
$contact_list = $contact_list . addNewContact();
file_put_contents("data/data.json", $contact_list);
}
fclose($datafile);
}
// Call the function saveContact()
saveContact();
echo "Thank you for joining us";
}
else //If the form is not submited or not all the required fields are filled
{ ?>
<form>
<fieldset>
<legend>Add New Contact</legend>
<input type="text" name="fullname" placeholder="First name and last name" required /> <br />
<input type="email" name="email" placeholder="etc#company.com" required /> <br />
<input type="text" name="phone" placeholder="Personal phone number: mobile, home phone etc." required /> <br />
<input type="submit" name="submit" class="button" value="Add Contact"/>
<input type="button" name="cancel" class="button" value="Reset" />
</fieldset>
</form>
<?php }
?>
<!-- HTML ENDS -->
Thought I don't like the PHP bit. Do you REALLY want to create a file for contacts? It'd be MUCH better to use a mysql database. Also, adding some breaks to that file would be nice too...
Other thought, IE doesn't support placeholder.
cell1.innerHTML="<?php echo $customerDESC; ?>";
cell2.innerHTML="<?php echo $comm; ?>";
cell3.innerHTML="<?php echo $expressFEE; ?>";
cell4.innerHTML="<?php echo $totao_unit_price; ?>";
it is working like a charm, the javascript is inside a php while loop
Related
I need to create a table of 17 rows where each row contains information such as row number, name, surname, email and birthday. The data is provided by this form:
<form action="index.php" method="post">
<input type="text" name="name" placeholder="name" />
<input type="text" name="surname" placeholder="surname" />
<input type="text" name="emailbirthday" placeholder="emailbirthday" />
<input type="text" name="birthday" placeholder="birthday(dd/mm/aaa)" />
<button type="reset">Reset Form</button>
<button type="submit">Submit Form</button>
</form>
After clicking submit the data should be displayed in the nth row of the table(row number one if it is the first "pack" of data submitted, number two if its the second and so on). This problem could easely be solved using databases but i cannot use them(by professors order).
I tried to create an array than push values into it like this:
$array_name = array();
$name = $_POST["name"];
array_push($array_name, $name);
This approach doesn't work(the index of the array stays 0 alla of the time so it keeps replacing the first value again and again) and manually incrementing the index counter of the array doesn't work either.
Normally one should use a database approach but your professor explicitly forbids it.
There are many other ways to do it. (store as TEXT/JSON/CSV file or localstorage / cookies), etc. For me I would use session to do the job
declare a session variable which is an array
if user submits the form, store the POST data into another array (subarray) containing name, surname, birthday, email
add the subarray into the main session variable array
print it out at the end as a table
So the PHP will be:
<?php
session_start();
?>
<form action="#" method="post">
<input type="text" name="name" placeholder="name" />
<input type="text" name="surname" placeholder="surname" />
<input type="text" name="email" placeholder="email" />
<input type="text" name="birthday" placeholder="birthday(dd/mm/aaa)" />
<button type="reset">Reset Form</button>
<button type="submit">Submit Form</button>
</form>
<?php
if (!isset($_SESSION["arr"])){
$_SESSION["arr"]=array();
}
if ($_POST) {
$subarray=array(
"name"=>$_POST["name"],
"surname"=>$_POST["surname"],
"birthday"=>$_POST["birthday"],
"email"=>$_POST["email"]
);
$_SESSION["arr"][]=$subarray;
}
echo "<table border=1><tr><td>Name<td>Surname<td>Email<td>Birthday";
foreach($_SESSION["arr"] as $suba){
echo "<tr><td>" . $suba["name"] ;
echo "<td>" . $suba["surname"] ;
echo "<td>" . $suba["email"] ;
echo "<td>" . $suba["birthday"] ;
}
echo "</table>";
?>
However, if you need the data to be persistent (even after the user closes the browser), then you need to store the data say in file format or cookies, etc.
If you need to save data persistent and using file to save data is acceptable, i'd use something like that:
<?php
$file = 'path/to/file.txt';
$data = json_decode(file_get_contents($file), true);
if ($_POST) {
$data[] = [
"name" => $_POST['name'],
"surname" => $_POST['surname'],
"emailbirthday" => $_POST['emailbirthday'],
"birthday" => $_POST['birthday']
];
}
file_put_contents($file, json_encode($data));
?>
<form action="index.php" method="post">
<input type="text" name="name" placeholder="name" />
<input type="text" name="surname" placeholder="surname" />
<input type="text" name="emailbirthday" placeholder="emailbirthday" />
<input type="text" name="birthday" placeholder="birthday(dd/mm/aaa)" />
<button type="reset">Reset Form</button>
<button type="submit">Submit Form</button>
</form>
<table>
<tr>
<th>Name</th>
<th>Surname</th>
<th>Emailbirthday</th>
<th>Birthday</th>
</tr>
<?php
foreach ($data as $row) {
print '<tr>
<td>'.$row['name'].'</td>
<td>'.$row['surname'].'</td>
<td>'.$row['emailbirthday'].'</td>
<td>'.$row['birthday'].'</td>
</tr>';
}
?>
</table>
You can use the post values of hidden fields:
<form action="" method="post">
<input type="text" name="name" placeholder="name" />
<input type="text" name="surname" placeholder="surname" />
<input type="text" name="emailbirthday" placeholder="emailbirthday" />
<input type="text" name="birthday" placeholder="birthday(dd/mm/aaa)" />
<button type="reset">Reset Form</button>
<button type="submit">Submit Form</button>
<?php
if($_POST["names"] == "")
{
$value = $_POST["name"];
}
else
{
$value = $_POST["names"]."-".$_POST["name"];
}
?>
<input type="text" name="names" style='display:none;' value="<?php echo $value ?>">
</form>
We are using below code to update the form fields in a database
<form action="profile.php" method="POST">
Name :
<input type="text" name="txtuname" value="<?php echo $row['userName'] ?>" /><br/>
Email :
<input type="text" name="txtemail" value="<?php echo $row['userEmail'] ?>" />
<input id="sub" type="submit" name="submit" value="Save" style="display:none" />
<button class = "pedit" name="submit" onclick="work()">Edit</button>
</form>
script
<script>function work()
{
var see = document.getElementsByName("submit");
for (i = 0; i < see.length; i++)
{
see[i].style.display = see[i].style.display === 'none' ? 'block' : 'none'; }}
</script>
both form fields, edit and save parts are displaying in only one page & using only same css.
Perhaps the following, quickly written code, might help you change the appearance in the manner you are wishing.
echo "
<form>";
for( $i=0; $i < 10; $i++ ){
echo "
<div class='record'>
<output id='name$i' name='name'>Fred Bloggs $i</output><br />
<output id='email$i' name='email'>fred.bloggs_$i#gmail.com</output><br />
<input type='submit' value='Save' style='display:none'/>
<input type='button' value='Edit' />
</div>";
}
echo "
</form>
<script type='text/javascript'>
var col=document.querySelectorAll('input[type=\"button\"]');
if( col )for( var n in col )if( col[n] && col[n].nodeType==1 )col[n].onclick=function(e){
var parent = this.parentNode;
var fname = parent.querySelectorAll('output[name=\"name\"]')[0];
var femail = parent.querySelectorAll('output[name=\"email\"]')[0];
var bttn = parent.querySelectorAll('input[type=\"submit\"]')[0];
var vname = fname.innerHTML;
var vemail = femail.innerHTML;
parent.removeChild(fname);
parent.removeChild(femail);
fname = document.createElement('input');
fname.type='text';
fname.name='name';
fname.value=vname;
femail = document.createElement('input');
femail.type='text';
femail.name='email';
femail.value=vemail;
parent.appendChild(fname);
parent.appendChild(femail);
this.style.display='none';
bttn.style.display='block';
}.bind( col[n] );
</script>";
I created one more page as profile1.php with below code and i gave href to that page once we click on button, so that values are saving in profile1.php and once we click on save button , again it will redirect to edit page. and after clicking on edit button again it will redirect to save page.
profile.php
<form action="profile1.php" method="POST">
Name :
<input type="text" name="txtuname" value="<?php echo $row['userName'] ?>" /><br/>
Email :
<input type="text" name="txtemail" value="<?php echo $row['userEmail'] ?>" />
<button class="pedit" name="submit">Edit</button>
</form>
profile1.php
<form action="profile.php" method="POST">
Name :
<input type="text" name="txtuname" value="<?php echo $row['userName'] ?>" /><br/>
Email :
<input type="text" name="txtemail" value="<?php echo $row['userEmail'] ?>" />
<input type="submit" name="submit" value="Save" />
</form>
I have created an HTML form that stores data in a database and later on I take them, and today I wanted to make it more advanced.
I have a form that looks like this (not for login, just for example)
<form method="post" action="process.php" autocomplete="off">
Name: <input type="text" name="name"/>
Surname: <input type="text" name="surname" />
Phone: <input type="text" name="phone" />
<input type="submit" />
In process.php, it stores data in the database so later I can use them.
I want to make it so if one or more of them are empty, when you press submit button it shows error like "Must fill all fields", but if you have done everything, it just submits and stores data in database.
I thought I can make with this kind of code:
<?php
$required = array('name', 'surname', 'phone');
$error = false;
foreach($required as $field) {
if (empty($_POST[$field])) {
$error = true;
}
}
if ($error) {
Write an error message and don't react to submit
}
else {
If everything is done, allow to submit
}
?>
How can I make it work, so that you can't press Submit while you haven't finished all fields?
You're wanting something client side to validate the fields before you're able to submit to the next page. Look up validation in jQuery and maybe include the "required" attribute that's been added into HTML5.
Add name attribute to button set required to all required fields
<input name="submit" type="submit" />
in php
<?php
if(isset($_POST['submit'])){
$required = array('name', 'surname', 'phone');
$error = false;
foreach($required as $field) {
if (empty($_POST[$field])) {
$error = true;
}
}
if ($error) {
write and error message and don't react to submit
} else {
if everything is done, allow to submit
}
}
?>
Try the below code
<?php
if(isset($_POST['submit'])){
$required = array('name', 'surname', 'phone');
$error = false;
$message='';
foreach($required as $field) {
if (empty($_POST[$field])) {
$error = true;
}
}
if ($error) {
$message = 'All fields required';
}else{
//Submit process here
}
}
?>
<?php echo $message; ?>
<form method="post" action="process.php" autocomplete="off">
Name: <input type="text" name="name"/>
Surname: <input type="text" name="surname" />
Phone: <input type="text" name="phone" />
<input type="submit" name="submit" value="Submit" />
Easiest and quickest way, You can use HTML5 required.
<form method="post" action="process.php" autocomplete="off">
Name: <input type="text" name="name" required />
<BR>
Surname: <input type="text" name="surname" required />
<BR>
Phone: <input type="text" name="phone" required />
<BR>
Gender: Male <input type="radio" name="gender" value="1" required />
Female <input type="radio" name="gender" value="2" required />
<BR>
<input type="submit" />
</form>
I have n number of text box (n may be any number) with same name. And
I want to access the value of all the text box of that name.
Ex-:
<form method="post" id="create">
<input type="text" name="user[]" />
<input type="text" name="user[]" />
<input type="text" name="user[]" />
<input type="button" id="newFieldBtn"/>
<input type="submit" name="save" value="save"/>
</form>
jQuery
<script>
jQuery(document).ready(function($) {
$('#newFieldBtn').click(function(){
var code='<input type="text" name="user[]" />';
jQuery('#create').append(code);
</script>
or is there any other way to access the value of the text box. Either
by class or any other property..
<script>
jQuery(document).ready(function($) {
$('#newFieldBtn').click(function(){
var count = document.getElementById('count').value;
count++;
var code = '<input type="text" name="user'+count+'" />';
jQuery('#create').append(code);
document.getElementById('count').value = count;
</script>
and your html like...
<form method="post" id="create">
<input type="hidden" id="count" value="0" name="count">
<input type="button" id="newFieldBtn"/>
<input type="submit" name="save" value="save"/>
</form>
and in your php code...
<?php
if(isset($_POST))
{
$count = $_POST['count'];
for($i=1;$i<=$count;$i++)
{
$user.$i = $_POST['user'.$i];
}
}
?>
Try this one, it will show you the values :
<form action="#" method="post">
<input type="text" name="user[]" />
<input type="text" name="user[]" />
<input type="text" name="user[]" />
<input type="submit" value="submit" >
</form>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
foreach($_POST['user'] as $key => $value)
{
echo $key." has the value = ". $value."<br>";
}
}
?>
See this in action: http://wistudat.be/try/array.php
When I submit a form using the attached code, instead of the message appearing in the div, the screen is refreshing itself and it is holding the completed form in the browser cache. I have obviously got it wrong somewhere and would be grateful if someone could point out my error. I have posted the relevant code, but if there is something I have missed, then please let me know.
In firebug, I can see the correct data that is being returned in the post tab.
I wasn't sure of the best place to post, so if this is incorrect, admin, please amend as you see fit. many thanks.
jquery code
//Begin function to submit report form
$(function(){
$(".frmreport").submit(function(){
var formdata = $(this).serialize();
$ajax({
type: "POST",
url: "../frm10010.php",
data: formdata,
dataType: "json",
success: function(msg){
$("#report_result").html("You have succesfully submitted your report. Thank you.");
}
});
return false;
});
});
// End function to submit report form
frm10010.php
<?php
$dept = mysql_real_escape_string($_POST['dept']);
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['email']);
$position = mysql_real_escape_string($_POST['position']);
$feedback = mysql_real_escape_string($_POST['feedback']);
$form = array('dept'=>$dept, 'name'=>$name, 'email'=>$email, 'position'=>$position, 'feedback'=>$feedback);
$result = json_encode($form);
echo $result;
?>
html
<div id="report_result"></div>
<div id="formShow">
<form class=frmreport" method="post" class="webform">
<fieldset>
<legend><span class="subtitle">Submit Technical Report</span></legend>
<label for="dept">Department</label>
<input id="dept" name="dept" class="text" type="text" />
<label for="name">Full Name:</label>
<input id="name" name="name" class="text" type="text" />
<label for="email">Email address:</label>
<input id="email" name="email" class="text" type="text" />
<label for="position">Position:</label>
<input id="position" name="Position" class="text" type="text" />
<label for="feedback">Problem:</label>
<textarea name="feedback" cols="22" rows="5"></textarea>
</fieldset>
<input class="submit" type="submit" name="submit" value="Submit Report" />
<input class="cancel" type="reset" name="cancel" value="Clear Report" />
</form>
</div>
You have couple of errors here
$ajax({ should be $.ajax({
Second you have an error in the form class
<form class=frmreport" method="post" class="webform">
should be
<form class="frmreport" method="post" class="webform">
Don't use
$(".frmreport").submit(function(){
Instead use
$("#sub_btn").click(function(){
And in html
<input class="submit" type="submit" name="submit" value="Submit Report" />
Change it to
<input class="submit" id="sub_btn" type="button" name="submit" value="Submit Report" />
Another way to do it making submit handler false. But above solution will work here. There is also . is missing in ajax call.