HTML form on submit and javascript not working - html

I've looked over many threads and can't seem to find a working solution for my problem. I am new to javascript and am looking for assistance in allowing my page to run javascript and submit a form by clicking one submit button.
I am using codeigniter, and am calling a javascript function called uploadEx(); to submit a canvas to a directory. Submitting to the directory works by itself but not as the same button as the submit for the form. If someone could help me make the button share both actions that would be great.
<div>
</div>
<form method="post" accept-charset="utf-8" name="form1">
<input name="hidden_data" id='hidden_data' type="hidden"/>
</form>
<script>
function uploadEx() {
var canvas = document.getElementById("canvasSignature");
var dataURL = canvas.toDataURL("image/png");
document.getElementById('hidden_data').value = dataURL;
var fd = new FormData(document.forms["form1"]);
var xhr = new XMLHttpRequest();
xhr.open('POST', '/inc/img/inspection/upload_data.php', true);
document.forms["form"].submit();
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
var percentComplete = (e.loaded / e.total) * 100;
console.log(percentComplete + '% uploaded');
//alert('Succesfully uploaded');
}
};
xhr.onload = function() {
};
xhr.send(fd);
};
</script
<div align="center">
<?php if( !function_exists('form_open')): ?>
<?php $this->load->helper('form'); ?>
<?php endif;?>
<form id="form" onClick="uploadEx(); return true;" method="post">
<?php echo form_label('Trailer Number','trlr_num'); ?>
<?php echo form_input(array('name'=>'trlr_num','type'=>'text')); ?>
<?php echo form_label('Seal','seal'); ?>
<?php echo form_input(array('name'=>'serial_num','type'=>'text')); ?>
<?php echo form_fieldset_close(); ?>
<br />
<input type="submit" name="submit" value="submit" content="submit"/>
<?php echo form_close(); ?>

I was able to resolve my problem by using Imran Qarner's suggestion by moving the onsubmit event out of the php code that calls codeigniter.

Have u tried onsubmit event instead of onclick? i think so it will work for you.
moreover what is the functionality of your first <form>.......</form> ?

Related

how to Load Text file into HTML, inside <textarea> tag?

how to Load Text file into HTML, inside tag?, I don't have an source to show you.
thanks
You can use PHP to load files from the user's computer. Here is an example.
form.html
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
upload.php
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
if(isset($_POST["submit"])) {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
header("Location: http://example.com/displaymessage.php?filename=" + basename( $_FILES["fileToUpload"]["name"]));
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
displaymessage.php
<?php
$file = $_GET['filename'];
?>
<script>
var client = new XMLHttpRequest();
client.open('GET', '/uploads/<?=$file?>');
client.onreadystatechange = function() {
document.getElementById("#textbox").value = client.responseText;
}
client.send();
</script>
Make sure to change #textbox, to the ID of the textarea tag. (e.g. <textarea id="foo">)
NOTE: I just came up with half of this code, and I am not sure if it will work

Keeping a checkbox checked after refreshing the page

I have some checkboxes in my php page.when ever i check some of them,some divs get hidden,some get visible.but when i refresh the page,checkboxes get unchecked.and all div s are visible then.
How to keep checkboxes checked even after refreshing the page..?
I tried code as below
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.0.min.js"></script>
<script src="http://code.jquery.com/qunit/qunit-1.10.0.js"></script>
<script src=".jquery.cookie.js"></script>
<script src="tests.js"></script>
<script type="text/javascript">
$(function(){
var cookieChecked = $.cookie("cookieChecked");
if(cookieChecked){
$(cookieChecked).trigger("click");
}
})
</script>
</head>
<body>
<label for="sitecheck">
<span style="font-weight:bold;">close site temp:</span>
</label>
<input name="" type="checkbox" id="sitecheck" onclick="validateSitec()" /><span style="font-weight:bold;">close site and add message</span><br>
<input type="text" name="closedmsg" id="closedmsg" style="width:440px;height:120px;display:none;" value="<?php echo $data['csitemsg']; ?>" />
<script type="text/javascript">
function validateSitec(){
if (document.getElementById('sitecheck').checked){
$('#sitecheck').prop('checked', true);
$('#closedmsg').slideDown();
$.cookie("cookieChecked", "#sitecheck");
}else if(document.getElementById('closedmsg').checked){
$('#closedmsg').slideUp();
$("#sitecheck").removeProp("checked").checkboxradio("refresh");
$.cookie("cookieChecked", "#closedmsg");
} else {
$.cookie("cookieChecked","");
}
}
</script>
</body>
</html>
checboxes wont stay ticked on page refresh by default but you can check out the jquery cookie plugin or check out keep checkbox ticked page
Use this Sample code from there
javascript
function validateSitec(){
if (document.getElementById('sitecheck').checked){
$('#sitecheck').prop('checked', true);
$('#closedmsg').slideDown();
$.cookie("cookieChecked", "#sitecheck");
}else if(document.getElementById('closedmsg').checked){
$('#closedmsg').slideUp();
$("#sitecheck").removeProp("checked").checkboxradio("refresh");
$.cookie("cookieChecked", "#closedmsg");
} else {
$.cookie("cookieChecked","");
}
}
and on page load
$(function(){
var cookieChecked = $.cookie("cookieChecked");
if(cookieChecked){
$(cookieChecked).trigger("click");
}
})
well as you are not showing any of your code we actually shouldn't post any answer cause everything is just a guess.
If you don't want to save it in a cookie you could save it in a session, which is better cause it is server side.
So with this solution you have to check the checkboxes and click on the submit button. If you don't like that you could change that to an ajax call. Also you have to change some stuff if you wan't to have it work if your user is leaving your page and coming back....
So this is just to give you an idea how your PHP could be looking:
-lets say your checkboxes come from an array. in the example the array is called $valuesForInput[]
<?php
session_start();
if(isset($_POST['check'])) {
$_SESSION['check'] = $_POST['check'];
} else {
unset($_SESSION['check']);
session_destroy();
}
$valuesForInput[] = "one";
$valuesForInput[] = "two";
$valuesForInput[] = "three";
$html = '
<form action="test.php" method="post">
<div>';
foreach($valuesForInput as $k => $v) {
if(is_array($_SESSION['check'])) {
$check = in_array($v, $_SESSION['check']) ? ' checked' : '';
}
$html.='
<input type="checkbox" name="check[]" value="'.$v.'"'.$check.'>
<label for="check1">'.$v.'</label>
';
} $html.='
</div>
<input type="submit" value="submit" />
</form>
';
echo $html;
?>
have fun coding
Try this one i think this one will work.we can keep the check box after refreshing the page also
<?php
$val= $_POST['checkbox1'];
?>
<li> <input type="checkbox" name="checkbox1[]" value="sradha" <?php if (strpos($val, "sradha") !== false) { ?> checked="checked" <?php } ?> />
<label>sradha</label></li>
It should work

How do I submit a form without refreshing the current page?

I have a fairly basic email form
<form name="contactform" method="post" action="send_email.php" id="email_form">
<div class="ContactHeaders">Name</div>
<input type="text" name="Name" class="ContactBoxes" id="name"/><br/><br/>
<div class="ContactHeaders">Email</div>
<input type="email" name="Email" class="ContactBoxes"/><br/><br/>
<div class="ContactHeaders">Message</div>
<div style="width:100%">
<textarea name="Message" maxlength="1000"></textarea><br/>
</div>
<div style="width: 100%">
<input type="submit" class="Submitbtn" value="Submit">
</div>
</form>
Here's 'send_email.php'
<?php
ob_start();
include 'navbar.php';
ob_end_clean();
if(isset($_POST['Email'])) {
//declare variables
$Name = $_POST['Name'];
$Email = $_POST['Email'];
$Message = $_POST['Message'];
$complete = 0;
$email_to = "someone#example.com";
$email_subject = "Website Contact";
//check all forms are filled in correctly
$email_exp = '/^[A-Za-z0-9._%-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if(preg_match($email_exp,$Email)) {
$complete++;
}
$string_exp = "/^[A-Za-z .'-]+$/";
if(preg_match($string_exp,$Name)) {
$complete++;
}
if(strlen($Message) > 20) {
$complete++;
}
//send email if $complete = 4
if ($complete == 3){
if (get_magic_quotes_gpc()) {
$Message = stripslashes($Message);
}
$Message = $Message . "\n\n" . "From " . $Name;
$headers = 'From: '.$Email."\r\n".
'Reply-To: '.$Email."\r\n" .
'X-Mailer: PHP/' . phpversion();
#mail($email_to, $email_subject, $Message, $headers);
echo '<script>
alert("Thank you for contacting me. I will be in touch shortly");
top.location="index.php";
</script>';
}
else {
echo '<script>
alert("The form you submitted is invalid. Please ensure the following: \n You have provided a valid email address. \n Your phone number is entered correctly. \n The message box contains at least 20 characters.")
history.go(-1)
</script>';
}
}
?>
So my problem is that when the form submits to the php file, the browser loads the php file, runs the code and returns the result (It's not really a problem but it's something I don't want) It is then up to java to display the alert and go back one (in my code anyway). Is there a way to make it run the code in the background so the form runs the php file without having to go to it (if that makes sense) and return the result in the same window. I've obviously looked around and found loads of things about AJAX but I didn't really understand it and couldn't get it to work for me.
The reason for doing this is a little complicated but would make things much easier as far as user-friendliness goes for my site, as well as looking cleaner (going to a blank page and displaying an alert doesn't look very good).
Thanks in advance for any help you can offer me:)
$('.Submitbtn').click(function(e) {
e.preventDefault();
// do some form validation here
if form is valid { // from validation above
var formData = $('#email_form').serialize();
$.post('send_email.php',{data:formData});
} else {
alert('Form no good - fix it!');
return false;
}
});
Here's something you can start with. This is very basic but supplies the necessary foundation for beginning your AJAX adventure.
50 Excellent AJAX Tutorials

DOMPDF not working

I am trying to take some html from a textarea and convert it to a pdf. I donwnloaded DOMPDF from https://github.com/dompdf/dompdf and wrote the code below. When I click submit I get this error: "Internal Server Error". (my webhost doesn't tell me which line it's one)
(the name of this file is test2.php)
<?php
if (isset($_POST['submit'])) {
$content = $_POST['content'];
if (empty($content)){
$error = 'write something';
}
else {
include_once( 'dompdf/dompdf_config.inc.php' );
$dompdf = new DOMPDF();
$dompdf->load_html($content);
$dompdf->render();
$dompdf->stream('example.pdf');
}
}
?>
<!DOCTYPE html>
<head>
</head>
<body>
<?php
if(isset($error)){
echo $error;
}
?>
<form method="post" action="test2.php">
<textarea name="content" id="content">hello world</textarea><br>
<input type="submit" name="submit" value='submit'>
</form>
</body>
</html>
I was struggled for more than one month to solve this. Finally I solved it. the solution is below.
<?php
require_once 'dompdf/autoload.inc.php';
// reference the Dompdf namespace
use Dompdf\Dompdf;
?>
<html>
<head></head>
<body>
<h1>Sucess</h1>
</body>
</html>
<?php
$html = ob_get_clean();
$dompdf = new DOMPDF();
$dompdf->setPaper('A4', 'portrait');
//$dompdf->setPaper('A4', 'landscape');
$dompdf->load_html($html);
$dompdf->render();
//For view
$dompdf->stream("",array("Attachment" => false));
// for download
//$dompdf->stream("sample.pdf");
?>
I had a similar issue on a client's server when using DOMPDF for a project.
It's possible that you do not have the right level of error reporting configured with your installation of PHP.
At the top of your script place the following; error_reporting(E_ALL);
Example:
error_reporting(E_ALL);
if (isset($_POST['submit'])) {
$content = $_POST['content'];
if (empty($content)){
$error = 'write something';
}
else {
include_once( 'dompdf/dompdf_config.inc.php' );
$dompdf = new DOMPDF();
$dompdf->load_html($content);
$dompdf->render();
$dompdf->stream('example.pdf');
}
}
You should now see a more detailed message about the type of error received.
There could be issues with the HTML markup you are passing to the $dompdf->load_html($content); method or alternatively you might be experiencing memory related issues (exceeding your memory allowance).
Typically these errors will report themselves but again depending on your setup, reporting might be limited.

How To Display Error Messages With Wufoo API V3?

I am using the Wufoo API V3 to submit data from a form hosted on my website to my Wufoo account. I followed the example on the [Entries POST API][1] page, and I was able to successfully the data to my account.
I was wondering how I am able to check for error messages, and display the ErrorText for each text input field using PHP?
For example, if someone does not provide their email address in a required email field.
Here is the code I have so far:
<?
function submit() {
$ref = curl_init('https://myname.wufoo.com/api/v3/forms/xxxxxx/entries.json');
curl_setopt($ref, CURLOPT_HTTPHEADER, array('Content-type: multipart/form-data'));
curl_setopt($ref, CURLOPT_POST, true);
curl_setopt($ref, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ref, CURLOPT_POSTFIELDS, getPostParams());
curl_setopt($ref, CURLOPT_USERPWD, 'XXXX-XXXX-XXXX-XXXX');
curl_setopt($ref, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ref, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ref, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ref, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ref, CURLOPT_USERAGENT, 'Wufoo.com');
$response = curl_exec($ref);
echo $response;
}
function getPostParams() {
return array( 'Field4' => "you#company.com");
}
submit();
?>
UPDATE (Nov 12, 2011):
MinisterOfPower,
Thanks for [the reply and advice][2] about the Wufoo PHP API Wrapper. I am now using the API Wrapper and it rocks. I am having some challenges integrating the code you provided with my form.
For example, if I have a form on index.php (see below) with an email required field. How would I be able to set up the API wrapper to display an error next to the appropriate input field after the form is submitted?
Here's the code for index.php:
<? require_once('my-wrapper.php'); ?>
<html>
<head>
<title>Form</title>
</head>
<body>
<form id="form1" name="form1" autocomplete="off" enctype="multipart/form-data" method="post" action="">
<div>
<label id="email" class="icons" for="Field4">Email</label>
<input id="Field4" name="Field4" type="text" class="formreg"/>
</div>
<div>
<label id="name" class="icons" for="Field6">Name</label>
<input id="Field6" name="Field6" type="text" class="formreg"/>
</div>
<input type="submit" name="saveForm" value="Submit" id="submit" class="submit" />
<input type="hidden" id="idstamp" name="idstamp" value="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx=" />
</form>
</body>
</html>
Here's the code for my-wrapper.php:
$wrapper = new WufooApiWrapper('XXXX-XXXX-XXXX-XXXX', 'mysubdomain','wufoo.com');
$postArray = array();
foreach ($this->postValues as $value => $key) {
$postArray[] = new WufooSubmitField($key, $value);
}
try {
$result = $wrapper->entryPost('XXXXXX', $postArray);
if (!$result->Success) {
foreach ($result->FieldErrors as $key => $value) {
echo "Error on $key. Error Text: $value <br />";
}
}
} catch (Exception $e) {
//Read the error message.
}
UPDATE (Nov 20, 2011):
I am now able to display the error messages with the help of MinisterofPower's code and the Wufoo API wrapper. I have a couple of follow up questions:
I was wondering how I do set up the form below with PHP so that it posts the entries upon pressing the submit button?
Is it possible to do this using AJAX so the page does not refresh?
Here's the code:
<?
// API
require_once('WufooApiExamples.php');
// Wufoo
$wrapper = new WufooApiWrapper('XXXX-XXXX-XXXX-XXXX', 'mysubdomain','wufoo.com');
// Post Entries
$postArray = array();
foreach ($this->postValues as $key => $value) {
$postArray[] = new WufooSubmitField($key, $value);
}
try {
$result = $wrapper->entryPost('xxxxxx', $postArray);
if (!$result->Success) {
foreach ($result->FieldErrors as $key => $value) {
$fieldError[$value->ID] = $value->ErrorText;
}
}
} catch (Exception $e) {
//Read the error message.
}
// Add Errors
function addErrors($fieldName, $fieldError, $add){
if($fieldError[$fieldName] != ''){
if ($add == 'message') return '<p class="errors">'.$fieldError[$fieldName].'</p>';
else if ($add == 'class') return 'class ="errors"';
}
}
?>
<!--Begin Form-->
<div <? echo addErrors('Field4', $fieldError, 'class') ?>>
<label id="profile" class="icons" for="Field4">Email</label>
<input id="Field4" name="Field4" type="text" class="formreg" tabindex="1"/>
<? echo addErrors('Field4', $fieldError, 'message')?>
</div>
<div <? echo addErrors('Field6', $fieldError, 'class') ?>>
<label id="profile" class="icons" for="Field6">Name</label>
<input id="Field6" name="Field6" type="text" class="formreg" tabindex="1"/>
<? echo addErrors('Field6', $fieldError, 'message')?>
</div>
<!--End Form-->
The process of retrieving the response is outlined in the API docs. Also, the markup for field errors in found the Dealing With Failure section.
Is is worth nothing that Wufoo offers API Wrappers for PHP and many other languages. I highly suggest using one of those since they make the process so much easier.
Using the Wufoo API, you'd search for a Success value of 0 in the response object and then parse the Field Errors node, as shown here:
$wrapper = new WufooApiWrapper($this->apiKey, $this->subdomain, 'wufoo.com');
$postArray = array();
foreach ($this->postValues as $value => $key) {
$postArray[] = new WufooSubmitField($key, $value);
}
try {
$result = $wrapper->entryPost($this->formHash, $postArray);
if (!$result->Success) {
foreach ($result->FieldErros as $key => $value) {
echo "Error on $key. Error Text: $value <br />";
}
}
} catch (Exception $e) {
//Read the error message.
}
A followup question was posted above, so I'll add my answer here.
You asked how to display an error next to the form in question. You could do this with either javascript or php. I'll show you the PHP way only.
Using PHP, you could redirect back to the form with a value in the GET param of the URL, enumerating the error fields and messages. So, for example, you could do this:
for($result->FieldErrors as $name => $value) {
$str.="$name=$value&";
}
if($str) {
$str = '?errors=true&'.$str;
$host = $_SERVER['HTTP_HOST'];
$uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
header("Location: http://$host$uri/$str");
exit;
}
Then, you'd wrap the above code in this if statement to check for error values on postback, like so:
if($_GET['errors']) {
require_once('my-wrapper.php');
else
//Your HTML HERE
endif
After that, add some PHP conditions which append class names to your fields if they contain errors. For example:
<label id="Field4" class="icons <?php if ($_GET['Field4']) echo 'error'; ?>" for="Field4">Email</label>
Finally, add some CSS to call out the error fields with a color or other indicator.
The other way to do this is with javascript.
Use the same logic as above, but add the following script to your page (grabbed from here and here.)
<script type="text/javascript" charset="utf-8">
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return 'error';
}
}
}
function changeClass (elementID, newClass) {
var element = document.getElementById(elementID);
element.setAttribute("class", newClass); //For Most Browsers
element.setAttribute("className", newClass); //For IE; harmless to other browsers.
}
changeClass('Field4', 'error');
</script>
Then use this markup instead:
<label id="Field4" class="icons" for="Field4">Email</label>
Good luck.
PS: This code was written here in SO, so it will probably contain syntax errors. But you can get the point...