javascript does not execute (codeigniter) php script after window.print() - javascript

i have this javascript that checks if payment is equal or greater than total,
a window.print executes likewise a redirect page occurs, but it only print
but does not redirect.
view page:
<script>
function printpage()
{
var
total = parseFloat($(':input[name="total"]').val(),10),
cash = parseFloat($(':input[name="cash"]').val(),10),
charge = parseFloat($(':input[name="charge"]').val(),10),
payment = (cash + charge);
if(payment>= total){
window.print();
}else{
return false;
}
}
</script>
im not good at javascript.
here is some more details:
<form action="bills/settle" method="post">
<input type="text" name="cash">
<input type="text" name="charge">
<input type="text" name="total" value="<?php echo $total">
<input type="submit" onclick="printpage()"
</form>
controller page:
function settle(){
$payment = $this->input->post('cash')+ $this->input->post('charge');
$total = $this->input->post('total');
$data = ('cash'=>$this->input->post('cash'), so on.....)
if($payment >=$total)
{
$this->load->model('process');
$this->process->close_bill($data);
} else {
redirect('msg','refresh');
}
}
*other notes,
if payment is OK:
it prints, inserts data's to database but does not redirect.
the redirect script is in my model after a successful db insert.
if payment is not OK:(no problem on this side)
it redirects to msg page,

This has nothing to do with the javascript; it was an honest mistake on your part:
<input type="text" name="total" value="<?php echo $total">
should instead be:
<input type="text" name="total" value="<?php echo $total; ?>">
Also, it would help if you had display_errors set to on and error_reporting set to E_ALL while you are doing development, so you can see when errors occur.

Related

How can fill the form and return back to modify the records in php

I want to fill the form and able to return back to modify the records. But when I return back I want the form to have the previous values. when I put " />
I got error.
please help
Thank you!
My code
<?php
if (isset($_POST['submit'])) {
$from = 'hello#gmail.com';
$subject = $_POST['subject'];
$text = $_POST['elvismail'];
$output_form = false;
if(empty($subject) && empty($text)) {
echo 'You forgot the email subject and body text.<br />';
$output_form = true;
}
if (empty($subject) && (!empty($text))) {
echo 'You forgot the email subject.<br />';
$output_form = true;
}
if ((!empty($subject)) && empty($text)) {
echo 'You forgot the email body text.<br />';
$output_form = true;
}
if ((!empty($subject)) && (!empty($text))) {
if(isset($_POST['cancel'])) {
echo "cancel";
}
else if(isset($_POST['send'])) {
echo "submit";
}
?>
<form method="post" action="index.php">
<table>
<tr>
<td>Subject of email</td>
<td> <?php echo $subject; ?> </td>
</tr>
<tr>
<td>Body of email</td>
<td><?php echo $text ?> </td>
</tr>
</table>
<input type="submit" name="cancel" value="cancel" />
<input type="submit" name="send" value="Submit" />
</form>
<?php
}
}
else {
$output_form=true;
}
if ($output_form) {
?>
<form method="post" action="index.php">
<label for="subject">Subject of email:</label><br />
<input id="subject" name="subject" type="text" size="30" /><br />
<label for="elvismail">Body of email:</label><br />
<textarea id="elvismail" name="elvismail" rows="8" cols="40"></textarea><br />
<input type="submit" name="submit" value="Submit" />
</form>
<?php
}
?>
In this scenario its much better to use client side resources rather than storing it again on php. Because it is just a temporary value and using Local Storage would benefit you alot.
Javascript or JQuery would be the best approach to accomplish this.
Step 1 : Store the value on LocalStorage after on blur of every input on the form.
Step 2 : When user gets back to page. Simply assign the last data you saved on the localStorage
Because if you refresh the page you will lose the data variables in your php and will require to fetch it again on the database thus resulting on the same data values.
I suggest you read about the LocalStorage and read about controlling inputs with JQuery.
x = $("#form").serialize();
localStorage.setItem("temp_form_data" , x);
// To retrieve it simply convert it to JSON and assign it to each inputs.
var temp = JSON.parse(localStorage.getItem("temp_form_data"));
$("your-input-target").value(temp.id);
$("other-input-target").value(temp.description);
//and so on
This is just what would the implementation look like for setting and getting input data.

Trying to validate a form client and server side

The client side validation looks something like this:
function validateFname() {
var x = document.getElementById('fname').value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
The server side below it:
if(isset($_POST['SubmitForm'])){
if(empty($_POST['fname'])){
echo "First name cannot be empty!<br/><br/>";
return false;
}
and the form itself below that:
<form name = 'checkout' method='post' action="<?php echo $_SERVER['PHP_SELF']; ?>"
accept-charset='UTF-8'>
First Name:<input type="text" name="fname" id="fname" onsubmit="return validateFname()"
class="required" value="<?php echo $fname;?>" />
<input type="submit" name="SubmitForm" value="Send"/>
Ofcourse there is a lot more to it but ive just given one example above. I am trying to figure out why the (clientside)javascript function is not working and instead the (server) php error is coming up. I need to be able to have the client run validation checks before the server to reduce load.
The onsubmit is a event that belongs to the <form> element. You have placed it with the submit button which won't work.
Here's a working fiddle:
Demo
Reference
<form name = 'checkout' method='post' action="<?php echo $_SERVER['PHP_SELF']; ?>" accept-charset='UTF-8'>
First Name:<input type="text" name="fname" id="fname" value="<?php echo $fname;?>" />
<input type="submit" name="SubmitForm" onClick="return validateFname()" value="Send"/>
</form>
try the above code. Instead of using onSubmit in input text field use onClick in submit button.
good luck

Can I call a php file on form submit, and call or echo a JS function from that?

So I'm basically trying to create an HTML form that will
process my login through php POST method
close my login lighbox with javascript, or display an error (right now I'm using JS to change an invisible form value under the login form.
HTML
if (isset($_GET['error'])) {
echo '<p class="error">Error Logging In!</p>';
}?>
<br />
<form action="process_login.php" method="post" name="login_form">
Email: <input class="searchform" type="text" name="email" size="20"/><br />
Password: <input class="searchform" type="password"
name="password"
id="password" size="20"/><br />
<input type="button" class="searchform"
value="Submit" size="40" style="height:45px; width:90px"
onclick="formhash(this.form, this.form.password);" />
<input type="text" id="errorbox" style="height:45px; width:180px" value=""><br>
</form>
here's the php file:
if (isset($_POST['email'], $_POST['p'])) {
$email = $_POST['email'];
$password = $_POST['p'];
if (login($email, $password, $mysqli) == true) {
// Login success
echo "<script>document.getElementById('light').style.display=
'none';document.getElementById('fade').style.display= 'none'</script>";
} else {
// Login failed
echo "<script>document.getElementById('errorbox').value='Error'</script>";
}
} else {
// The correct POST variables were not sent to this page.
echo 'Invalid Request';
}
I know I'm not doing this right, I'm just not sure HOW to do it at all...
Well, yes, technically you can do that, but it is a VERY bad practice, and extremely not clean.
what you'd prefer to do is use Ajax, and do those JS actions in it's success callback:
Note: you will need to include the jQuery lib in your scripts.
Another none: if you don't have PHP 5.4 on your server, just remove the second callback function, and handle all the scenarios in the success callback
!(function($){
$(function() {
$('#submitBtn').on('submit', function(){
$.post('process_login.php', $('form[name="login_form"]').serialize(), function(data){
//data is a json object which contans the reponse
data = $.parseJSON(data);
$("fade").fadeOut();
$("light").fadeOut();
},
function(data){//error callback
data = $.parseJSON(data);
if(data.forbidden){
$("#errorBox").html("Error!");
}
else if(data.error){
$("#errorBox").html("Invalid request!");
}
});
});
});
})(window.jQuery);
HTML:
<form name="login_form">
<div>
<input type="text" name="email" placeholder="email">
</div>
<div>
<input type="password" name="p" placeholder="password">
</div>
<div>
<input type="button" id="submitBtn" value="Login">
</div>
</from>
PHP:
$response = array();
if (isset($_POST['email'], $_POST['p'])) {
$email = $_POST['email'];
$password = $_POST['p'];
if (login($email, $password, $mysqli) == true) {
http_response_code(200);//HTTP OK, requires php 5.4
$response['success'] = true;
} else {
// Login failed
$response['forbidden'] = true;
http_response_code(401);//HTTP forbidden
}
} else {
// The correct POST variables were not sent to this page.
$response['error'] = true;
http_response_code(400);//HTTP bad request
}
echo json_encode($response);
add onsubmit event attribute to the form:
<form onsubmit="return validate();">...
where validate() is a js function that closes lightbox and returns true if form is ok, or displays errors and returns false if form is bad.

Multiple forms onclick event only working for first form

I'm sure this has been asked befor but I can't seem to find it in a search
I have multiple forms on a page generated by php all with onCick event
The problem is it only picks up the first event after that any other clicks produce same result from first click
Here is javascript
function CompareScores(form)
{
var scoreA = document.getElementById("score_A").value;
var scoreB = document.getElementById("score_B").value;
if(scoreA > scoreB){
alert('Score A is Larger ' + scoreA)
}else{
alert('Score B is Larger ' + scoreB)
}
}
And the php generating forms
<?php
while($i<=$numPrelimTeams) {
if($i!=$e) {
?>
<form action="processScores.php" method="post"><p><u><?php echo $prelimTeam[$i]; ?> --> SCORE : <input type="text" class="small" id="score_A" name="score_A" size="1"></u></p>
<input type="hidden" name="team_A" value="<?php echo $prelimTeam[$i]; ?>">
<input type="hidden" name="game" value="<?php echo $game_num; ?>">
<p class="right">Game # <?php echo $game_num; ?> ) <input type="button" value="Enter Scores" onClick="CompareScores(this.form)"></p>
<?php
}else{
?>
<p><u><?php echo $prelimTeam[$i]; ?> --> SCORE : <input type="text" class="small" id="score_B" name="score_B" size="1"></u></p>
<input type="hidden" name="team_B" value="<?php echo $prelimTeam[$i]; ?>">
</form><br><br><br>
<?php
$game_num++;
$e=$e+2;
}
$i++;
}
?>
Without knowing the inputs or seeing the result, it's hard to tell for sure, but it looks like you might be generating multiple instances of this form on the same page, giving you multiple page elements named "score_A" and "score_B". document.getElementById will then become a bit ambiguous.
Since you're already sending the form object, use that instead:
var scoreA = form.score_A.value;
...
There is essentially a single problem with your code. You have multiple instances of the same ID.
To fix it, try something like this.
<input type="text" class="small score_A" name="score_A" size="1" />
Similarly
<input type="text" class="small score_B" name="score_B" size="1" />
Now, you can write a querySelector in your JS
function CompareScores(form) {
var a = form.querySelector('.score_A').value;
var b = form.querySelector('.score_B').value;
//do something
}

onkeyup or onclick JavaScript to auto submit form

Any onkeyup or onclick javascript code which helps me to submit form after 9 characters.
MY HTML CODE. I am using AJAX to get data. I have tried many scripts. None works for me :'(
Enter Your Car No : <input type="text" name="car" maxlength="9" id="carno" value="<?php echo $_REQUEST["carno"]; ?>"/>
Enter Your Car No : <input type="text" name="car" maxlength="9" id="carno" onkeypress="yourFunction()" value="<?php echo $_REQUEST["carno"]; ?>"/>
<script>
function yourFunction(){
var textValue = document.getElementById('carno').value;
if(textValue.length >= 9){
//implement your ajax code
}
}
</script>
Hai here i am calling function on each key press in that text field and i am getting the value using id and checking that length if its >=9 (ur requirement) so write ajax code
Try this :
Enter Your Car No : <input type="text" name="car" maxlength="9" id="carno" value="<?php echo $_REQUEST["carno"]; ?>" onkeypress="submitForm()" onclick="submitForm()"/>
<script>
function submitForm(){
var len = document.getElementById("carno").value.length;
if(len >= 9 ){
//submit form code
}else{
return false;
}
}
</script>

Categories