I have an issue. I'm working on the following code. In it, there's a calculator function made with JavaScript. I don't get jQuery yet. It works, but it only does so when I refresh the page. The page is a .php file. I don't know if it's got to do with that or the fact that there is php or database queries in the page, or whatsoever really.
The page is organized in the following fashion:
<div>
<div>
<?php -> catch $_POST values from another page -> some database query(select->echo selected item->turn item into $var) ?>
<div style="background: white; box-shadow: 1px 1px 2px; width: 200px; padding: 10px; float: right; margin-top: -125px; margin-right: -10px; height: 150px;">
<input type="radio" name="opcao" id="opCart" >Cartão<br>
<input type="radio" name="opcao" id="opDin">Dinheiro<br>
<input type="text" id="cholerie" style="width: 70px;" required>
<input type="submit" id="calcular" onclick="calcula()" value="calcular"> Resultado: <p id="resultado"></p>
</div>
<script>
var preco = <?php echo $array[preco]; ?> ;
var pagamento = document.getElementById("cholerie").value;
var troco = Number(preco) + Number(pagamento);
function calcula(){
document.getElementById("resultado").innerHTML = troco;
}
</script>
< some form to catch $_POST values from the database query >
<div> </div>
mysqli_close($conn);
I think the issue is the javascript and its related form.
php only runs when you reload the page. if you need to update page without reloading, you need to use ajax to send asynchronous query to a php page and update your data.
I too feel Dmitry's answer is right, how will you get your live data without reloading the page? You can use AJAX though as he suggested, so go ahead and read on AJAX on google
Related
I am creating a simple HTML login page, but if I enter data into the fields it stays there when I refresh the page. I have tried
function pageInit(ID) {
this.browserbot.getCurrentWindow().document.getElementById(ID).value = '';
}
but this doesn't do anything (I placed it into onLoad on the inputs of the login.)
HTML:
`
<title>Login</title>
</head>
<body>
<form>
<fieldset>
<legend><h3>Please Login:</h3></legend>
<input type="text" placeholder="Username" name="userId" id="userId" onLoad="pageInit('userId');"><br>
<input type="password" placeholder="Password" name="passwd" id="passwd" onLoad="pageInit('passwd');"><br>
</fieldset>
</form>
</body>
CSS:
<style>
html {
font-family: sans-serif;
text-align: center;
}
a {
font-weight: normal;
}
a:hover {
font-weight: bold;
}
#userId, #passwd {
width: 30%;
height: 40px;
text-align: center;
}
</style>
JS:
<script>
function pageInit(ID) {
this.browserbot.getCurrentWindow().document.getElementById(ID).value = '';
}
</script>
As far as I can tell, the previous answers to not cover the full extent of the question. The original question requests a function to be called to clear the field. However, I'm going to address this in several different ways.
This can be achieved with no JavaScript at all, but simply setting the value attribute as below:
<input type="text" placeholder="Username" name="userId" id="userId" value="" />
<input type="password" placeholder="Password" name="passwd" id="passwd" value="" />
The above will ensure that the fields are clear when the page is loaded, but using only HTML. To do this via JavaScript, multiple things have to be taken into consideration. First, a function should be defined, which needs to be called when the page is loaded.
function clearValue(id) {
document.getElementById(id).value = "";
}
This will simply set the value to blank. However, this gets us back to the original issue. Setting onload for each element does not work, instead we must use window.onload.
window.onload = function() {
clearValue("userID");
clearValue("passwd");
}
This will clear each value one-by-one. However, there is an even better way to do this. JavaScript has built-in functions that make it easy to clear the entire form, or access the elements of the form by their name, even if they are the child of another element within the form. However, keep in mind that only valid input (includes textarea, etc...) fields can be accessed in this way.
So, assuming that the form's ID is myform, this would clear the entire form, no matter how many fields:
document.getElementById("myform").reset();
It's that simple. Using the form element, you can also access the fields by name, as mentioned above.
var f = document.getElementById("myform").elements;
f["userId"].value = "";
f["passwd"].value = "";
Using the above code makes it much quicker, especially if you have more fields.
Putting the JS together, it might look like this:
window.onload = function() {
// using function
clearValue("userID");
clearValue("passwd");
// or, reset entire form
document.getElementById("myform").reset();
// or, clear each field one-by-one
var f = document.getElementById("myform").elements;
f["userId"].value = "";
f["passwd"].value = "";
}
May be it will help you.
<input type="text" value="initial" id="field">
<button id="reset">reset</button>
<script type="text/javascript">
document.getElementById('reset').onclick= function() {
var field= document.getElementById('field');
field.value= field.defaultValue;
};
</script>
Set the input value to " " - in other words, nothing.
This way, the value will be cleared when the page loads.
Implment this like so:
<input value="">
If you'd rather use JS, add this to your onload event:
window.onload = myOnloadFunc;
function myOnloadFunc() {
document.getElementById('userId').value = ''
}
In my HTML, I have a normal form. The form takes inputs and submits. The user will then click a button called "#addOne". This button, using jQuery, appends a cloned form to the previous form. Each form is numbered, and each form is one less than its previous. The numbers will be used in my SQL WHERE clause. I want the cloned forms to be separate forms, For example, if I enter values for form 9 and click submit, and then enter values for form 8 the information won't collide with each other. Form 8's button should not submit for all the other forms.
Here's my jsFiddle: https://jsfiddle.net/2c2xL0cz/
HTML:
<div class="article_properties">
<form class="article_properties_form" action="" method="POST" enctype="multipart/form-data">
<p style="display: inline">Page Number</p><div style="background-color: #FF355E; padding: 5px; display: inline; margin-left: 5px"<p class="pageNumber"></p></div>
<textarea style="display: none" class="inputNumber" name="pageNumber"></textarea>
<p>Image</p>
<input type="file">
<p>Subtitle</p>
<input type="text" name="subtitle">
<p>Text</p>
<textarea name="text" rows="4"></textarea>
<input id="properties_btn" type="submit" value="Submit/Update">
<hr style="border: 1px dotted lightgray; margin-bottom: 50px">
</form>
<div id="addOne" style="width: 25px; height: 25px; background-color: orange; border-radius: 50%"><p style="text-align: center; line-height: 25px">+</p></div>
</div> <!--End of article properties div-->
jQuery/Ajax:
var numPages = 10;
$('.pageNumber').text(numPages);
$('.inputNumber').text(numPages);
$('#addOne').click(function()
{
numPages--;
var articlePropsTemplate = $('.article_properties_form:last').clone();
$('.article_properties_form').append(articlePropsTemplate);
$('.pageNumber:last').text(numPages);
$('.inputNumber:last').text(numPages);
});
$('.article_properties_form').on('submit', function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '',
data: $(this).serialize(),
success: function(data) {
}
});
});
Also, I do not wish to refresh the page when the form submits. For some reason, the dynamically created forms are creating page refresh when the submit button is clicked. There's also a solution in creating a div outside of the form elements, but this technique is making the forms think they're one form, but they should be separate forms all submitting to their respective pageNumbers.
Change this line
$('.article_properties_form').append(articlePropsTemplate);
To the below one
$('.article_properties').append(articlePropsTemplate);
Right now you are appending the new form with in the old form. So the data will get collide. You have to append the form outside the old form. So append the new form to the old form's parent
For prevent page reload of new forms
$('body').on('submit','.article_properties_form', function(e) {
//Your code
});
Or
$(document).on('submit','.article_properties_form', function(e) {
//Your code
});
first post. PHP noob. I'm surprised at how difficult this has been...
I have an html form (index.html) with a submit button that posts to a php file (sendemail.php).
The php file is set to collect form data and send it via email to an address I specify.
I would like to display a success icon next to the submit button when this email is sent. (Honestly, there is no fail condition, so I would be happy with just displaying the success icon when the user clicks Submit, so they know not to keep clicking Submit).
I have tried a number of approaches after reading this and many other forums. I've been at this for two days and could use some help.
Here's some snippets below. I'm basically just trying to detect the email being sent in the php file, then sending a flag ($val) using echo json_encode back to the HTML page. I'm trying to capture it using the javascript with an onload trigger, and then trying to use the javascript to manipulate the DIV visbility when the page is refreshed after the submit action is completed.
It processes the php but it doesn't seem to reach the Header line to reload the html page. It just refreshed the screen and shows the word "inline" and nothing else.
I'm stumped. Please help! Thanks
sendmail.php
// Check, if message sent to your email
// mark success or fail then refresh page
if($send_contact){
$val="inline";
echo json_encode($val);
}
else {
echo "Error";
}
if($send_contact){
header('location:index.html');
}
else {
echo "Error";
}
?>
javascript in html
<script type="text/javascript">
function success(){
var val = <?php echo json_encode($val); ?>;
document.getElementById('success').setAttribute('display', val);
}
window.onload = success;
</script>
HTML DIV I'm trying to control
<div style="text-align: left; font-weight: bold; color:#000000; display:val;"
class="success" id="success" name="success"><img src="success.png"
height="25px">Event added! It may take 20 minutes to appear on
the calendar. </div>
UPDATE:
Ok I tried manRo's suggestion and was able to get the behavior I wanted out of the green checkmark...it would be hidden on page load and then appear when it received the 200 status message from the PHP file.
However when I try to build this logic into my ajax something is breaking and the form data is no longer submitting, and the green checkmark logic stops working.
Allow me to run through my updates:
Currently my script header looks like this:
<script type="text/javascript" src="util-functions.js"></script>
<script type="text/javascript" src="clear-default-text.js"></script>
<script src="https://code.jquery.com/jquery-2.2.2.min.js"></script>
I've got an onload in the body to call a function to set the green checkmark to "hidden", just to keep things tidy:
<body onload="setdisplay()">
Calling this function:
<script>
function setdisplay();
document.getElementById("success").style.display = "none";
</script>
I get my form started like this now:
<form id="main" name="main" action="">
Here's an example input:
<td style="text-align: right; "> <br>
</td>
<td><input id="title" name="title" value="Event title" class="cleardefault rounded"
required="true" type="text"> </td>
The form submit button, which currently is type=button
<input style="background-color: #99d6ff; text-align:center;
font-weight: bold;" value="Add event" id="addevent" name="addevent" onclick="processmain();"
class="button" type="button">
This is the DIV I need to make visible or hidden depending on success:
<div style="text-align: left; font-weight: bold; color:#000000; display:none;"
class="success" id="success" name="success"><img src="success.png"
height="25px"></div>
Now the beefy part....I've tried integrating your manRo's suggestions into my main form processing script, as part of the ajax "success" state:
<script>
}
function processmain()
{
// event.preventDefault();
var title = $("input#title").val();
var location = $("input#location").val();
var startdate = $("input#startdate").val();
var starttime = $("input#starttime").val();
var enddate = $("input#enddate").val();
var endtime = $("input#endtime").val();
var other = $("input#other").val();
$.ajax({
url: "sendemail.php",
type:'POST',
data:
{
title: "title",
location: "location",
startdate: "startdate",
starttime: "starttime",
enddate: "enddate",
endtime: "endtime",
other: "other"
},
success: function(event)
{
$.get('sendmail.php', function(data) {
document.getElementById("success").style.display = "inline";
})
}
});}
</script>
At the moment:
The form data is not passed to the php
The green checkmark does not show
The screen is no longer refreshing (because button type=button now, instead of submit).
I feel like I am close. I need to get the form data sent to the php so the email is sent. I need the page to not refresh so I can properly introduce the green checkmark.
Please take a look at how I'm implementing your solution in my code and let me know what I'm doing wrong. Thank you!!
What you want is HTML form with ajax call to php script that will return 200 http status code on success.
I will try to explain you that on very simple example.
Please take a look at below html file:
<html>
<head>
<script src="https://code.jquery.com/jquery-2.2.2.min.js"></script>
</head>
<body>
<form action="sendmail.php">
<input type="email" name="email"/>
<input type="submit"/>
</form>
<script>
$(document.forms[0]).submit(function(event) {
event.preventDefault();
$.get('sendmail.php', function(data) {
alert('all good');
});
});
</script>
</body>
</html>
sendmail.php in that case should contain code responsible for sending email eg:
<?php
//code here...
if ($email_sent) {
http_response_code(200);
} else {
http_response_code(400);
}
at the moment I am trying to add some functionality for a user to be able to submit an anonymous suggestion. I am trying to clear a textbox that contains the users name when the user checks the checkbox. However my code does not clear the checkbox when checked. is there a way to clear the checkbox before the form is submitted?
Thanks
<div>
<label style="display: inline-block; margin-left: 10px; letter-spacing: 2px; color: #007A8E;">
<div align="left"><b>Name:</b> </div>
</label>
<div align="left">
<input type="checkbox" style=" margin-left: 110px; outline: 1px solid #0078AE; " name="Anonymous" value="Anonymous" onClick="CheckAnon">
</div>
<label style="margin-left: 2px; color: #0078AE;">
<div align="left">Anonymous</div>
</label>
<div align="left">
<?
function CheckAnon()
{
if(isset($_POST['Anonymous']) == 'Anonymous')
{
$anonFirstName="Anon";
$anonLastName="Anon";
}
else if (isset($_POST['Anonymous']) != 'Anonymous')
{
$anonFirstName = $firstName;
$anonLastName= $lastName;
}
}
?>
</div>
</div>
<div align="left">
<input name="firstname" style="height: 34px; width: 268px; margin-left: 10px; margin-top: 5px; color: #007A8E;
border: 1px solid #dedede; -moz-border-radius: 5px; -webkit-border-radius: 5px; border-radius: 5px;" type="text"
value="<? echo $anonFirstName?> <? echo $anonLastName?>">
</div>
You can do this at client side using jquery or javaScript.
Assume this text box:
<input type="text" id="fname" />
JavaScript Method:
<script type="text/javascript">
function clearTextBox() {
// Code to clear textbox on Checkbox tick
var textname = document.getElementById("fname"); //get textbox id
textname.value = ""; // clear the textbox
}
</script>
You can do it in PHP as you want.
But, doing it in jQuery is quite simple.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(function(){
$("#Anonymous").change(function(){
if ($(this).is(':checked')) {
$("#firstname").val('');
}
});
});
</script>
You are confusing clientside scripting (JavaScript in your case) with what the server receives (PHP).
The function you call:
onClick="CheckAnon"
Does not exist on the client. Also use: onClick="CheckAnon();"
There are more problems in your code. I advice you to use Firefox and look in the errorlog of javascript. This will help you a lot to trace the bugs.
Also make sure you understand what happens in the client (browser), and the server (after you post a form)
I think you need to clear that up first before you start clearing textboxes with JavaScript)
When i enter new values to form input field and submit them, then twice page reload needed to get the new values.
like you can see the $balance_2 in the 7th line. This line sum all row values of every row and and record the value in Balance column of every row and after pressing submit button then it goes to update_2.php file to update the database and when in click on
<a style='left: -18%; top: 100%; position: absolute; color: white; font-family: Roboto, helvetica, arial, sans-serif; width: 170px; font-weight: 600;' href='index_2.php'>Click here to go back</a>
button in update_2.php file and go back to the main page then the form values are not updated till i reload it again.
I want that when i click on Click here to go back button then new values should be shown and there must not be need to reload the page twice.
This is my codes
$id_2 = $row['ID'];
$Budget_2 = $row['Budget'];
$Availed_in_Regions_2 = $row['Availed_in_Regions'];
$Requested_in_KBL_2 = $row['Requested_in_KBL'];
$Received_in_KBL_2 = $row['Received_in_KBL'];
$Availed_in_KBL_2 = $row['Availed_in_KBL'];
$balance_2 = $Availed_in_Regions_2 + $Requested_in_KBL_2 + $Received_in_KBL_2 + $Availed_in_KBL_2;
$con2->query("UPDATE Office_Operations f1, (SELECT SUM(balance) AS bal FROM Office_Operations ) f2 SET ytotal6_2 = bal WHERE f1.id = 1;");
$con2->query("UPDATE Office_Operations SET Balance = $balance_2 WHERE id = $id_2");
echo "<div class='calc_container'"; if($row['ID']==1) echo " style='margin-bottom:40px;'"; echo ">
<input type='hidden' class='id_3' name='id[]' value='".$row['ID']."'>
<input type='text' class='budget_3' name='Budget[]' value='".$row['Budget']."'>
<input type='text' class='avail_region_3' name='Availed_in_Regions[]' value='".$row['Availed_in_Regions']."'>
<input type='text' class='req_kbl_3' name='Requested_in_KBL[]' value='".$row['Requested_in_KBL']."'>
<input type='text' class='rec_kbl_3' name='Received_in_KBL[]' value='".$row['Received_in_KBL']."'>
<input type='text' class='avail_kbl_3' name='Availed_in_KBL[]' value='".$row['Availed_in_KBL']."'>
<input type='text' class='balance_3' name='Balance[]' value='".$row['Balance']."'>
</div>";}
From my perspective:
Put all the input tags inside of form tag that uses action="" (to the same URL)
OR
Process the request with AJAX. When clicked on anchor a use onclick then define the listener function that makes the AJAX call and updates the input fieldS on successful response (parse the response accordingly). See using JS or jQuery
Also, it would be better if you escape the query input values. For MySQL see some posts here, here and here.
Your list page or your main page is the index_2.php and your update_2.php is where the Click here to go back button is located.
Summary:
index_2.php
List of data
Also where the form is
update_2.php
where the Click here to go back button is located
When the data is submitted from your index_2.php, it will go to update_2.php, but does nothing but offers only the back button.
The only time the UPDATE query will run is when the user clicks the Click here to go back button.
SOLUTION:
Put your UPDATE query in your update_2.php
Use the header() function to redirect the user back to index_2.php after the query
Sample Code:
index_2.php:
<form action="update_2.php" method="POST">
<!-- INSERT HERE YOUR INPUT FIELDS -->
<input type="submit" name="submit">
</form>
update_2.php:
<?php
if(isset($_POST["submit"])){
/* INSERT HERE YOUR UPDATE QUERIES */
header("LOCATION:index_2.php"); /* REDIRECT USER BACK TO index_2.php */
} /* END OF ISSET SUBMIT */
?>