samedi 28 février 2015

Android WebView - Choosing a file via html form

i have a web app/Facebook app with a form that requires a user to upload an image. When accessing the site via the Facebook app on android devices, the choose file dialog will not prompt for the file location.


This only happens when using the native WebView from the Facebook app. If I choose to use an external browser (chrome or otherwise) the form works properly. Anyone know a if there is a workaround?


How to validate input file that have been added dynamically using jquery

I create a form that contains a button to add a group of input fields dynamically one of them is an input file "I want to validate its size before uploading"


jQuery:



$('.formLayout .moreSubjects').click(function(){
var box_html = $('<div id="more-subjects"><br><label>Subject</label><input type="text" name="subject['+numberIncrC+']" dir="rtl" class="subject_list"><br><label>Attachment</label><input type="file" name="attachment['+numberIncrC+']" id="subjectToUpload'+numberIncrC+'" class="att_list"><label id="lbSize'+numberIncrC+'"></label><br><label>Status</label><select name="status['+numberIncrC+']" class="status_list"><option value="none">&nbsp;</option><option value="approved">Approved</option><option value="rejected">Rejected</option><option value="underStudy">Under study</option></select><br><label>Date</label><input type="date" name="deadline['+numberIncrC+']"><br><label>Comments</label><textarea rows="4" cols="50" name="comments['+numberIncrC+']" dir="rtl"></textarea><button class="remove-box">Delete</button></div>');

box_html.hide();
$('.more-subjects').append(box_html);
box_html.fadeIn('slow');
$('.subject_list').each(function () {
$(this).rules("add", {
required: true,
messages: {
required: ".."
}
});

});
$('.att_list').each(function () {
$(this).rules("add", {
required: true,
accept: "doc|docx|pdf",
messages: {
required: "..",
accept: "..",
}});

$('select.status_list').each(function () {
$(this).rules('add', {
checkStatus: true
});

jQuery.validator.addMethod('checkStatus', function (value) {
return (value != 'none');
}, ".."); });
});
numberIncrC++;
return false;
});


File size method:



jQuery.validator.addMethod('checkSize', function ()
{
if(!$("#subjectToUpload"+numberIncrC).val() == '')
{
var iSize = ($("#subjectToUpload"+numberIncrC)[0].files[0].size / 1024);
if (iSize / 1024 > 1)
{
if (((iSize / 1024) / 1024) > 1)
{
iSize = (Math.round(((iSize / 1024) / 1024) * 100) / 100);
$("#lbSize"+numberIncrC).html( iSize + " GB");
}
else
{
iSize = (Math.round((iSize / 1024) * 100) / 100)
$("#lbSize"+numberIncrC).html( iSize + " MB");
}
}
else
{
iSize = (Math.round(iSize * 100) / 100)
$("#lbSize"+numberIncrC).html( iSize + " KB");
}
return (iSize<4294967295 ); // 4GB is 4,294,967,295 bytes
}
return true;
}, "..");


Now where should I call this method to check the size of each file ?


Angularjs bind dynamic form bulit in js

I have a form that I want to build at run time via js and use it in a form controller in angularjs.

As you can see in the following example, it is not being thrown as html, and i want it to be binded to the model variable. http://ift.tt/1wBBjYN



<div>
<form ng-controller="TodoCtrl" ng-submit="blabla()">
<div ng-repeat="field in fields">{{field.input}}</div>
</form>
</div>

function TodoCtrl($scope) {
$scope.model = {
'FirstName': 'Test',
'LastName': 'Test Last'
}
$scope.fields = [{
input: '<input type="text" ng-model="model.FirstName">'
}, {
input: '<input type="text" ng-model="model.LastName">'
}, ];
}

Why isn't alert message being printed?

I am currently applying for an Internship Internship Link


One of the things that I noticed right away is that you click on upload cover letter or paste cover letter, you're redirected to the home page of the job invite site Job Invite and sadly you can't upload your cover letter. On the other hand, the upload resume works perfectly fine but paste resume has the same issue.

Does anyone know how to resolve this issue and and be able to submit a cover letter?


I am not a web guru but since I am applying for an engineering position, I am trying to find a way around this. I right clicked the upload cover letter link and inspected the link with the inspect element tool. I found that this function



onclick="jvAddAttachment2('jvcoverletter', 'qLY9Vfwx')


was going to get called when the button is clicked. Now going into the JavaScript file for this html page, Inspect Element -> Sources -> *careers_8.js?v=303, I tried to do a basic alert statement, from alert dialog, to do some debugging to see what the issue is. Here's the code now



function jvAddAttachment2(id, companyId){
alert("I got here");
....
}


I then did control s and the Inspect Element console outputted "Recompilation and update succeeded." so I am assuming the JavaScript file has been updated. However when I click the link(via right click, open new window), no alert box shows up.

Does anyone know how to get the alert dialog to show up? I think I've done as much as I can with my working knowledge from one web development course haha.


Aligning form fields using CSS

I have an advanced search form (click "Advanced search") here in Dupal 7 - http://ift.tt/17H9poa and contact form here - http://ift.tt/1EBhO9q. The search fields are inline, while the contact fields are positioned below the labels.


Is there a way to inline position the fields with the text labels and make the fields aligned vertically with each other without separating the text labels and form fields in two divs?


Python - Logging in to web scrape

I'm trying to web-scrape a page on www.roblox.com that requires me to be logged in. I have done this using the .ROBLOSECURITY cookie, however, that cookie changes every few days. I want to instead log in using the login form and Python. The form and what I have so far is below. I do NOT want to use any add-on libraries like mechanize or requests.


Form:



<form action="/newlogin" id="loginForm" method="post" novalidate="novalidate" _lpchecked="1"> <div id="loginarea" class="divider-bottom" data-is-captcha-on="False">
<div id="leftArea">
<div id="loginPanel">
<table id="logintable">
<tbody><tr id="username">
<td><label class="form-label" for="Username">Username:</label></td>
<td><input class="text-box text-box-medium valid" data-val="true" data-val-required="The Username field is required." id="Username" name="Username" type="text" value="" autocomplete="off" aria-required="true" aria-invalid="false" style="cursor: auto; background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR4nGP6zwAAAgcBApocMXEAAAAASUVORK5CYII=);"></td>
</tr>
<tr id="password">
<td><label class="form-label" for="Password">Password:</label></td>
<td><input class="text-box text-box-medium" data-val="true" data-val-required="The Password field is required." id="Password" name="Password" type="password" autocomplete="off" style="cursor: auto; background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR4nGP6zwAAAgcBApocMXEAAAAASUVORK5CYII=);"></td>
</tr>
</tbody></table>
<div>
</div>
<div>
<div id="forgotPasswordPanel">
<a class="text-link" href="/Login/ResetPasswordRequest.aspx" target="_blank">Forgot your password?</a>
</div>
<div id="signInButtonPanel" data-use-apiproxy-signin="False" data-sign-on-api-path="http://ift.tt/1EBcovl">
<a roblox-js-onclick="" class="btn-medium btn-neutral">Sign In</a>
<a roblox-js-oncancel="" class="btn-medium btn-negative">Cancel</a>
</div>
<div class="clearFloats">
</div>
</div>
<span id="fb-root">
<div id="SplashPageConnect" class="fbSplashPageConnect">
<a class="facebook-login" href="/Facebook/SignIn?returnTo=/home" ref="form-facebook">
<span class="left"></span>
<span class="middle">Login with Facebook<span>Login with Facebook</span></span>
<span class="right"></span>
</a>
</div>
</span>
</div>
</div>
<div id="rightArea" class="divider-left">
<div id="signUpPanel" class="FrontPageLoginBox">
<p class="text">Not a member?</p>
<h2>Sign Up to Build &amp; Make Friends</h2>


Sign Up


^Don't know what that "Sign Up" thing is doing there, can't delete it.


What I have so far:



import cookielib
import urllib
import urllib2

cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))

opener.addheaders = [('User-agent', 'Mozilla/5.0')]

urllib2.install_opener(opener)

authentication_url = 'http://ift.tt/1AVbOUS'

payload = {
'ReturnUrl' : 'http://ift.tt/1sfn0d7',
'Username' : 'usernamehere',
'Password' : 'passwordhere'
}

data = urllib.urlencode(payload)

req = urllib2.Request(authentication_url, data)

resp = urllib2.urlopen(req)
contents = resp.read()
print contents


I am very new to Python so I don't know how much of this works. Please let me know what is wrong with my code; I only get the log in page when I print contents


PS: The login page is HTTPS


Array $_POST without using multiple input fields

I was wondering if it's possible to receive arrays in $_POST but with a single input field in the html and without sending the form with ajax?


Normally I would do this



<input type="hidden" name="array[]" />
<input type="hidden" name="array[]" />
<input type="hidden" name="array[]" />
.............


I was thinking of something like this



<input type="array" name="array" value="1,2,3,4" / >

Form Email Validation in backend PHP

I am using a form to get newsletter sign ups on my website. I am using a contact.php file which works well but there is no validation so I occasionaly and sometimes frequently get blank responses.


I'm not sure why this is, but I believe I need validation.


This is my original code



<?php
/*

Author: Andrew Walsh
Date: 30/05/2006
Codewalkers_Username: Andrew


This script is a basic contact form which uses AJAX to pass the information to php, thus making the page appear to work without any refreshing or page loading time.

*/

$to = "hello@interzonestudio.com"; //This is the email address you want to send the email to
$subject_prefix = ""; //Use this if you want to have a prefix before the subject

if(!isset($_GET['action']))




{
die("You must not access this page directly!"); //Just to stop people from visiting contact.php normally
}

/* Now lets trim up the input before sending it */


$subject = "Newsletter Sign Up"; //The senders subject
$message = trim($_GET['email']); //The senders subject
$email = trim($_GET['email']); //The senders email address

mail($to,$subject,$message,"From: ".$email.""); //a very simple send

echo 'contactarea|Thank you. We promise you won’t regret it.'; //now lets update the "contactarea" div on the contact.html page. The contactarea| tell's the javascript which div to update.
?>


and this is the code I tried to add to validate but it doesnt work.



<?php
/*

Author: Andrew Walsh
Date: 30/05/2006
Codewalkers_Username: Andrew


This script is a basic contact form which uses AJAX to pass the information to php, thus making the page appear to work without any refreshing or page loading time.

*/

$to = "jcash1@gmail.com"; //This is the email address you want to send the email to
$subject_prefix = ""; //Use this if you want to have a prefix before the subject

if(!isset($_GET['action']))




{
die("You must not access this page directly!"); //Just to stop people from visiting contact.php normally
}

/* Now lets trim up the input before sending it */


$subject = "Newsletter Sign Up"; //The senders subject
$message = trim($_GET['email']); //The senders subject
$email = trim($_GET['email']); //The senders email address


/* Validation */
$error=0; // check up variable
$errormsg = '<ul class="errorlist">';

/* get it checking */


if(!check_email($email))
{
$errormsg.= "<li class='errormessage'>ERROR: not a valid email.</li>";
$error++;
}

$errormsg .= '</ul>';


if($error == 0) {


mail($to,$subject,$message,"From: ".$email.""); //a very simple send

echo 'contactarea|Thank you. We promise you won’t regret it.'; //now lets update the "contactarea" div on the contact.html page. The contactarea| tell's the javascript which div to update.

} else {
echo 'error|'. $errormsg;
}

?>


Can anyone offer some insight?


The form action of my html form isn't writing a file on my server

Just a warning, this is my first experience with any kind of html or php, so my apologies for complete oversight on my part.


My problem is that I'm using an html form to trigger an event, and the action script I'm using doesn't seem to write to a file.


Here's the code for my html file:



<html><body>
<form action="action.php" method="post">
<input type="submit" value="Trigger this event.">
</form>
</body></html>


And my php file:



<?php
$file = 'status.txt';
file_put_contents($file, "1");
header('location:/index.html');
?>


So basically I want a file to be rewritten with just a "1" so that another program that loops server-side can read that file, take an action when it reads 1, rewrite the txt back to 0, loop. There's no need for input from the user; I'm mostly using the submit button as a toggle.


When I run the php file from the command line, it rewrites the file just fine. When I click the submit button on the html site, the header function knocks me back to the index page, so I know that the browser is reading the php file. It just doesn't write to the file.


If anyone sees the problem, or has an easier way to accomplish my goal( preferably using php), please tell.


Thanks.


Zend ajax form + first time populate

in my document/detail i have table with some users and on each row i have link to edit this user (form oppened in twitter bootstrap modal). In form submit i have parametr 'onclick' => 'return submitForm();' where submitForm() is an ajax action to resend data back to controller to dynamic zend validation. Problem is when I want to populate to edit form right users data after I open form in modal for first time. Probably i can do it by jquery so when i click on modal open link it will take data from table row and fill form elements...but here is problem that in table row I usually dont have all users data (minimalistic table) so i cannot populate all form elements.


controller:



public function detaillAction() {
$id = $this->_getParam("id", 0); //document id
$document = new Application_Model_DbTable_Document();
$doc = $document->findById($id);
//..and some another models

$this->view->headScript()->appendFile($this->view->baseUrl('/js/document-edit_user.js'));
$form_edit_users = new Application_Form_EditUsers();
if ($this->_request->isXmlHttpRequest()) {
if ($this->getRequest()->isPost()) {
$formData = $this->getRequest()->getPost();
//send json error messages here
}
}
else{
//First time populate form
$users = new Application_Model_DbTable_Users();
$user = $users->findById($user_id); //where to get this id?
$form_edit_users->populate($user);
$this->view->form_edit_users = $form_edit_users;
}
}


So what is best way how to get user_id for first time form render to this controller? Thx


I want to know how to only activate the form submit, not getting value to ajax url in jquery?

I want to submit a form without refresh page. My case is different than most people, I only need to initial the form submit, and then in the php, if $_POST, then gather the value. It is not duplicate question, because most answers are sending the form value to .ajax url and send the value back to html. I just want to initialize the submit.





$.ajax({
url:'member_search.php',
type:'POST',
data:{
search_text: $(".result_tag").text()
}

});



<form action="" method="post" name="form">
<input type="hidden" id="word" value="hello" name="input" >
</form>

<?php
if ($_POST){
$value=$_POST['input'];
echo $value;



?>



Change symfony2 form field but keep relation

So I have a form that is based on an entity that contains a one to many relationship.


The problem is that this field is rendered as a select (or choice). I really don't want to load all the possible ids (there are many) but just want to load the one that is set in the entity (which is the id that appears selected in the select).


Is there any way of doing this and still keep the relationship? If I really have to change the field how can I access, in the form class, the selected entity given to the entity so that I can retrieve the id?


UPDATE


To make this a bit clearer here is my form code:



$this->createFormBuilder()
->add('items', 'collection', array(
'type' => new \MyBundle\Form\ItemsType(),
'allow_add' => true,
'data' => $itemsEntities
)
)
->add('submit', 'submit')


In the $itemsEntities I have 5 entities all of which generate the select with loads of ids. Hakins answer would work I think if this would be just one field but since there are many I don't really know how to handle this.


I have tried to put an eventListner on the \MyBundle\Form\ItemsType for but I can never access any data.


Ruby On Rails Signup: Submitting invalid signup twice with selected "type" radio button

I am working through Mhartl's Ruby on Rails Tutorial on the user signup portion. I am trying to implement Single Table Inheritance, which I did by adding a type column to my BaseUser model.


On my form, I added two radio buttons for the user to specify his desired account type: Property Holder, or Service Provider.


If the user checks off one of the boxes, but makes a mistake in any of the other columns, the page will re-render. If he tries to submit again, I get the following error:



param is missing or the value is empty: base_user


I think the reason that this is happening is because, my controller is sending a post request as a BaseUser the first time, but is sending a post request as a PropertyHolder the second time and sends "type" twice in the second request. Here is the relevant server log:



"property_holder"=>{"name"=>"",
"email"=>"",
"password"=>"[FILTERED]",
"password_confirmation"=>"[FILTERED]",
"type"=>"PropertyHolder"},
"commit"=>"Create my account",
"type"=>"PropertyHolder"}


Am I correct in my understanding of this problem? How should I go about fixing this?


First Time



Started POST "/base_users" for 127.0.0.1 at 2015-02-28 15:38:58 -0800
Processing by BaseUsersController#create as HTML
Parameters: {"utf8"=>"✓",
"authenticity_token"=>"+e5APfbWVfLCeqh1/n/05u49b+rKdGD1JJ9Vwga/y5T9uspUqmlCOioeCNCgs8x1A3RhJio+noxUjwYBG/jBUQ==",
"base_user"=>{"name"=>"",
"email"=>"",
"password"=>"[FILTERED]",
"password_confirmation"=>"[FILTERED]",
"type"=>"ServiceProvider"},
"commit"=>"Create my account"}

(0.1ms) begin transaction BaseUser Exists (0.2ms) SELECT 1 AS one FROM "base_users" WHERE LOWER("base_users"."email") = LOWER('') LIMIT 1
(0.1ms) rollback transaction
Rendered shared/_error_messages.html.erb (5.1ms)
Rendered base_users/new.html.erb within layouts/application (9.0ms)
Completed 200 OK in 110ms (Views: 92.5ms | ActiveRecord: 0.3ms)


Second Time



Started POST "/property_holders" for 127.0.0.1 at 2015-02-28 14:59:19 -0800
Processing by BaseUsersController#create as HTML
Parameters: {"utf8"=>"✓",
"authenticity_token"=>"VABbJX6ubQM885FNbX5Zip9MFXmTWEb3XyKzwOYbkMZQVNFMIhF6y9SXMegzsmEZcgUbtXMSuI4vMuAD+1yaAw==",
"property_holder"=>{"name"=>"",
"email"=>"",
"password"=>"[FILTERED]",
"password_confirmation"=>"[FILTERED]",
"type"=>"PropertyHolder"},
"commit"=>"Create my account",
"type"=>"PropertyHolder"}

Completed 400 Bad Request in 1ms


ActionController::ParameterMissing (param is missing or the value is empty: base_user):
app/controllers/base_users_controller.rb:28:in `user_params'
app/controllers/base_users_controller.rb:15:in `create

PHP Self-referencing script

I am trying to embed a self-referencing PHP script inside an HTML form with following code:


Undefined index: conv



<form action = "<?php $_SERVER['PHP_SELF'] ?>" method = "post">
<input type = "number" id = "temp2" name = "temperature2" placeholder = "28">
<label for = "temp2"> degrees </label>

<select>
<option name = "conv" value = "f"> Fahrenheit </option>
<option name = "conv" value = "c"> Celsius </option>
</select>

<input type = "submit" value = "equals">

<?php
$type = $_POST["conv"];
$tmp = $_POST["temperature2"];
if ($type == "f") {
$newTmp = (9/5 * $tmp) + 32;
echo $newTmp . " degrees Celsius.";
}
elseif ($type == "c") {
$newTmp = (5 * ($tmp - 32)) / 9;
echo $newTmp . " degrees Fahrenheit.";
}
?>

</form>


And I am getting this messages: Notice: Undefined index: conv Notice: Undefined index: temperature2


Everything worked fine when the php script was in another file. Anyone knows what am I doing wrong?


Is applying ::before to input[type=submit] possible? [duplicate]


This question already has an answer here:




Let's say you have a form input button that you want to style with CSS, but you also want to use "::before" to append text before the styling. How would you do that? Is that even possible?


input[type=submit]::before {} (this doesn't work)


Is editing "value='blahblahbuttontext'" in the form the only way to achieve this?


Thanks,


-- MP


HTML: control form submission by pressing enter from text input [duplicate]


This question already has an answer here:




I have noticed that when I am with my cursor in a text input and I press enter the form will submit.



<!DOCTYPE html>
<html>
<body>

<form action="action_page.php">

<input type="radio" name="sex" value="male">Male<br>
<input type="radio" name="sex" value="female">Female<br>

First name:<br>
<input type="text" name="firstname" value="Mickey">
<br>
Last name:<br>
<input type="text" name="lastname" value="Mouse">
<br><br>
<input type="submit" value="Submit">
</form>

<p>If you click "Submit", the form-data will be sent to a page called "action_page.php".</p>

</body>
</html>


I found that slightly confusing for the user, because a hit on enter from within a text input could simply notify "I am done with this input". How do I control (prevent) that?


Send emails from several email forms to several email addresses

I have a email system on my website, people can send me emails by completing a form. On the website i have 2 different forms and the JS (contact_me.js) and the PHP (contact_me.php) that make those email forms work. Now i receive emails from both email forms on the same email address but i want to change that, when someone send me a email from the 2nd email form i want to receive that email on the 2nd email address. I am planning to copy/paste the JS and the PHP and call them contact_her.js and contact_her.php and than connect the 2nd email form to the 2nd email address. I am new at JS, can someone identify the things that i have to modify in the JS and HTML to make this happen? Here is the code:


HTML:



<form name="sentMessage" id="contactForm" novalidate>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<input type="text" class="form-control" placeholder="Your Name *" id="name" required data-validation-required-message="Please enter your name.">
<p class="help-block text-danger"></p>
</div>
<div class="form-group">
<input type="email" class="form-control" placeholder="Your Email *" id="email" required data-validation-required-message="Please enter your email address.">
<p class="help-block text-danger"></p>
</div>
<div class="form-group">
<input type="tel" class="form-control" placeholder="Your Phone *" id="phone" required data-validation-required-message="Please enter your phone number.">
<p class="help-block text-danger"></p>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<textarea class="form-control" placeholder="Your Message" id="message" required data-validation-required-message="Please enter a message and the delivery address."></textarea>
<p class="help-block text-danger"></p>
</div>
</div>
</div>


</div>
<div class="clearfix"></div>
<div class="col-lg-12 text-center">
<div id="success"></div>
<button type="submit" class="btn btn-xl">Send Message</button>
</div>
</div>
</form>


JS:



$(function () {

$("input,textarea").jqBootstrapValidation({
preventSubmit: true,
submitError: function ($form, event, errors) {
// additional error messages or events
},
submitSuccess: function ($form, event) {
event.preventDefault(); // prevent default submit behaviour
// get values from FORM
var name = $("input#name").val();
var email = $("input#email").val();
var phone = $("input#phone").val();

// this is where you're getting your message text
var message = $("textarea#message").val();

// add in the childNodes code
var tags = document.getElementsByClassName('tag');
var tagText = '';
for (var i = 0; i < tags.length; i++) {
tagText += tags[i].childNodes[0].nodeValue + ' ';
}
// trim the trailing whitespace
tagText = tagText.trim();

// add the message body and the tag text together:
message = message + '\n\nOrdered products codes: ' + tagText;






var firstName = name; // For Success/Failure Message
// Check for white space in name for Success/Fail message
if (firstName.indexOf(' ') >= 0) {
firstName = name.split(' ').slice(0, -1).join(' ');
}
$.ajax({
url: "././mail/contact_me.php",
type: "POST",
data: {
name: name,
phone: phone,
email: email,
message: message,
},
cache: false,
success: function () {
// Success message
$('#success').html("<div class='alert alert-success'>");
$('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;")
.append("</button>");
$('#success > .alert-success')
.append("<strong>Your message has been sent. </strong>");
$('#success > .alert-success')
.append('</div>');


//clear all fields
$('#contactForm').trigger("reset");
$('.tag').remove();



},
error: function () {
// Fail message
$('#success').html("<div class='alert alert-danger'>");
$('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;")
.append("</button>");
$('#success > .alert-danger').append("<strong>Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later or send a email yourself at order@o-p-a-l.eu");
$('#success > .alert-danger').append('</div>');
},
})
},
filter: function () {
return $(this).is(":visible");
},
});

$("a[data-toggle=\"tab\"]").click(function (e) {
e.preventDefault();
$(this).tab("show");
});
});


/*When clicking on Full hide fail/success boxes */
$('#name').focus(function () {
$('#success').html('');
});


PHP:



<?php
// Check for empty fields
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['phone']) ||
empty($_POST['message']) ||
!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
{
echo "No arguments Provided!";
return false;
}

$name = $_POST['name'];
$email_address = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];

// Create the email and send the message
$to = 'email1@gmail.com'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to.
$email_subject = "Website Contact Form: $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers = "From: email1@gmail.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com.
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>


Thanks.


Codeigniter:Set validation rules inside the function

I am very new to codeigniter and i am facing a issue with following senario.


i have two forms and validate both by setting the rules inside a function validate_form()



Ex:function validate_form() {
if (isset ($_POST['next'])) {
//Set rules for first form.
if($this->form_validation->run()===false){
//first form wrong
}
else { //first form is correct }
}
else if (isset ($_POST['register'])){
//Set rules for second form.
if($this->form_validation->run()===false){
//second form wrong
}
else { //second form is correct }
}
}


The problem is i am calling the validate_form() as below
public function index()
{
$data = array();
$this->validate_form();
//other stuff here
}


So my form is only not rendering because both $_post['next'] and $_POST['register'] are not set. how to solve this??


InitialisingComponent Error being thrown (Visual Studio C#)

I have asked this question a couple of days ago and really did not get any help on it. So i am going to re-ask the question in a more better sense. I am doing a fully automated speech recognition program. I have the program complete but one error. This error happens to be the InitializingComponent(). see code below:





public frmMain()
{
InitializeComponent();



in the program i have 2 winforms (using C#) that uses the same events and methods. Once i do the Form frmEdit, I then can change the class name to all the same for example this is the breakdown:


public partial class frmMain : Form public partial class AlarmClock : Form public partial class Commands : Form


ok i originally changed Form1 : Form to frmMain : Form. this form contains all the events, methods, constructors etc., etc.,


With the Form Edit option i can edit the form names. So i changed the other two with the same public partial class name. So now all three are frmMain : Form.


However i have no errors anywhere in the program except this error that is on the frmMain (Form1) and the error says:


Error 1 The call is ambiguous between the following methods or properties: 'Ivan.frmMain.InitializeComponent()' and 'Ivan.frmMain.InitializeComponent()' C:\Users\Ian\Desktop\Ivan Assistant\Ivan\Ivan\Form1.cs


I have pasted the exact error. So i have done this program before, then scratched it and started over and so forth.


What do i need to do to correct this error. If you need to see more code then i can make a video and post it on youtube for you to see. I really don't want to start all over again but that is neither there nor here. This program is eventually going to be going out for testing once i can get this error resolved and see if it will debug.


This is about as plain as i can explain this with out the ability to post pictures at the moment. But like i said i can do a video and explain what i am doing. If that would help anyone.


jQuery handle button click inside a form

i don't understand why a button inside my form can't be reached with my jQuery code.



<form action="">
<div class="field">
<label for='username'>Insert username</label>
<input type="text" id="username" name="username">
</div>

<button type='submit' class='btn btn-lg btn-primary buttonRegister'>Register</button>
</form>


Here are my jQuery on click try codes:



$('.buttonRegister').submit(function(){
//action inside function
});


--------------OR----------------------



$('.buttonRegister').click(function(){
//action inside function
});


--------------OR----------------------



$('.buttonRegister').on("click", function(){
//action inside function
});


None of them worked. I'm SURE that code inside click function works because i tried to take button outside the form and it worked well.


what is wrong with this code it is passing just "1" in the form handling

im making admin panel so user can edit text of the page by this helppppp please... the data on webpage is displayed through the database here im giving him option to edit data and update it this will open data in textbox and when user clicks botton update it will update data in database but problem is that when click on update the form is not passing values in the text feild it is passing value "1" i dont know from where it is getting "1" if i echo posted veriable it shows 1



<?php
$query2 = mysqli_query($con, "SELECT * FROM home");
$row = mysqli_fetch_array($query2);
$pic1 =ucfirst($row['pic1']);
$pic2 =ucfirst($row['pic2']);
$pic3 =ucfirst($row['pic3']);
$pic4=ucfirst($row['pic4']);
$pic5 =ucfirst($row['pic5']);
$pic6 =ucfirst($row['pic6']);
$pic7 =ucfirst($row['pic7']);
$pic8 =ucfirst($row['pic8']);
$par1 =ucfirst($row['par1']);
$par1pic =ucfirst($row['par1pic']);
$par2 =ucfirst($row['par2']);
$side_pic1 =ucfirst($row['side_pic1']);
$side_pic2 =ucfirst($row['side_pic2']);
?>
<form method="POST" action="update_home.php">
Paragraph no 1: <textarea name="comment" rows="5" cols="40"><?php echo $par1;?></textarea>
First name: <input type="text" name="fname"><br>
<input type="submit" name="nw_update" value="Update_1" /><br><br>
</form>
<form method="POST" action="update_home.php">
Paragraph no 2: <textarea name="comment1" rows="5" cols="40"><?php echo $par2;?></textarea>enter code here
<input type="submit" name="nw_update" value="Update_2"/><br><br>

</form>
_____________________________________________________________________________




<?php
include("dbconnection.php");
$value = isset($_POST["nw_update"]);
$fname = isset($_POST["fname"]);
echo $fname;
echo $value;
if($value=="Update_1")
{
$par = isset($_POST["comment"]);
$query2 = mysqli_query($con, "UPDATE home SET par1='$par' where id='1'");
}
if($value=="Update_2")
{
$par2 = isset($_POST["comment1"]);
$query2 = mysqli_query($con, "UPDATE home SET par2='$par2' where id='1'");


}

header("location : edit_home.php");
?>

simplest method to clear text field after submit


I've been searching all over the place to try and get my text field to clear after submit. Keep in mind that I want to stay on the same page when data is being submitted (I have a jquery code for staying on the same page after submission). I figured that it would be a lot easier if I just posted my code so that I can get help in my specific case. The following is what I tried, the .reset(), java onclick, onsubmit, jquery and ajax methods and none of them have produced the result that I am looking for. The closest I have gotten was a form getting cleared before submit and this leaves a blank submission.




Here's my form code for getting test info from the user. Here I tried the onclick, onsubmit methods without much luck:



<form id=\"msg\" method=\"post\" action=\"topage.php\" style=\"text-align: center; font-size: 26px; font-weight: bold; color: white; position: relative; top: -45px\">
MESSAGE<br><input type=\"text\" style=\"font-size: 22px;width:90%; height:50px; resize: none; \" name=\"msg\" >
<input class=\"submit\" type=\"submit\" value=\"Send\" style=\"width:90%; height: 40px; \">
<div id=\"message\"></div>
</form>



Here's my stay on page after submit code. I am using a script include to allow my stay on the same page after submit to work. It took me awhile to find a way to stay on same page after submit. If there is a better method for staying on the same page that works with clearing a form after submission by all means please share:




<script src=form.js></script>

<script type="text/javascript" >
$(document).ready(function() {
$('#msg').ajaxForm({
target: '#message',
success: function() {
$('#message').fadeIn('slow');
}
});
});


</script>

php contact form - explanation required

I was writing my personal website and thought about creation of contact form. Not a big deal....


But I would like to protect me somehow from auto generated requests by malicious scripts.


Captcha is not an option because it would discourage potential senders to contact me.


I tried to look how others handled this problem.


Among many unprotected forms I found pretty interesting example:


enter image description here


I can't explain the purpose of hidden input fields and I guess they have something to do with filtering malicious users from good users.


But. Am I right? How are they used?


Website where I picked this form website


yii2 email form not working

I have created a form which displays correctly and the validation works in terms of required fields and captcha however when clicking submit nothing happens not fail message or success message and the email is not being sent. I have set it up similar to the default contact form.


I am unsure on what the problem is as no error are being thrown and I have compared it to the way the contact form is setup.


Review form model



<?php
namespace frontend\models;

use yii\base\Model;
use Yii;


/**
* ContactForm is the model behind the contact form.
*/
class SubmitReviewForm extends Model
{
public $name;
public $email;
public $title;
public $subtitle;
public $summary;
public $description;
public $legit;
public $fake;
public $brand;
public $department;
public $verifyCode;

/**
* Returns the validation rules for attributes.
*
* @return array
*/
public function rules()
{
return [
[['name', 'title', 'subtitle', 'summary', 'description', 'legit', 'fake', 'brand', 'department', 'verifyCode', 'email'], 'required'],
['email', 'email'],
['verifyCode', 'captcha'],
];
}

/**
* Returns the attribute labels.
*
* @return array
*/
public function attributeLabels()
{
return [
'name'=> Yii::t('app', 'Name'),
'email'=> Yii::t('app', 'Email'),
'title'=> Yii::t('app', 'Title'),
'subtitle' => Yii::t('app', 'Sub Title'),
'summary' => Yii::t('app', 'Summary'),
'description' => Yii::t('app', 'Description'),
'legit' => Yii::t('app', 'Legit'),
'fake'=> Yii::t('app', 'Fake'),
'brand'=> Yii::t('app', 'Brand'),
'department'=> Yii::t('app', 'Department'),
'verifyCode'=> Yii::t('app', 'Verification Code'),
];
}

/**
* Sends an email to the specified email address using the information
* collected by this model.
*
* @param string $email The target email address.
* @return bool Whether the email was sent.
*/
public function submitreview($email)
{
return Yii::$app->mailer->compose()
->setTo($email)
->setFrom([$this->email => $this->name])
->setSubject($this->title)
->setTextBody($this->description)
->send();
}
}


Controller



public function actionSubmitreview()
{
$this->layout = 'submitreview';

$model = new SubmitReviewForm();

if ($model->load(Yii::$app->request->post()) && $model->validate())
{
if ($model->submitreview(Yii::$app->params['adminEmail']))
{
Yii::$app->session->setFlash('success',
'Thank you for contacting us. We will respond to you as soon as possible.');
}
else
{
Yii::$app->session->setFlash('error', 'There was an error sending email.');
}

return $this->refresh();
}
else
{
return $this->render('submitreview', [
'model' => $model,
]);
}
}

Symfony2, submitting form with additional dynamically created fields

I am using Symfony2 to submit some form data. I want to submit my form but I am creating some dynamic form elements and it is not working which is understandable.


Here is my form builder:



$builder->add('email','email',
array(
'attr'=>array(
'class'=>'form-control'
),
)
);


On my page I am creating additional fields with the name 'name="additionalEmails[]"'. There can be several of these fields because I want the user to be able to add multiple emails.


Now of course my form is not working because this element is not in the form builder, so on submission this "$form->isValid()" == false and the submission fails.


How can I add these form elements and actually get my form to have $form->isValid() == true?


Thanks.


Zend form in ajax action

Hello is posible to render and validate zend form in some individual ajax action?


Eg. now I have document controller with many forms (files, cost, contacts ...) in twitter bootstrap modal and if I want to edit eg. contact I have in my document controller if ($this->_request->isXmlHttpRequest())...$this->_helper->json($form_edit_contact->getMessages());... and ajax is working with it. So in my case, document controller is very large and messy.


Can I have some other ajax action with view where I´ll render and validate this form and ajax will be called by jquery after click on edit_contact button? Hope you understand my question. Thx


How to find elements that are not deeper than a selector?

I am building a jQuery plugin to manage form collections. The plugin aims to add add, remove, move up and move down buttons to alter that collection.


A collection's root node always contains a selector, such as .collection.


I implemented min and max options, so add and remove buttons disappear accordingly. My problem comes up when I try to manage a collection of form collections: how to select only the add buttons that refers to the right collection?


To simplify the problem, look at the following HTML code:



<div class="collection">
<div>something</div>
<div>something</div>
<div>
<div class="add">+</div>
</div>
<div>something</div>
<div class="collection">
<div>something</div>
<div>something</div>
<div>
<div class="add">+</div>
</div>
<div>something</div>
</div>
</div>


Keep in mind that the button can be arbitrary deep: collection is built by an user and I don't know where can be the button in the dom. BTW, it is deeper than the .collection, that's all I know.


How to select all add buttons until the second .collection, but not further?


Enforce numerics only in input text field with dashes (serial key, credit card number)

I have a field that takes in numerics in the following format XX-XXXX-XXXX-XXXX and I was wondering what would be the best modern approach to enforce the user only enters numbers?


My current solution consists of four input fields with dashes in between them to guide the user but this seems a little outdated, I want to use what HTML5 has to offer.


A good example I can think of is the old CD keys when installing software. As you enter enough digits it will focus on the next group. Is there any way I can do this without breaking out a JS solution?


EDIT: When I say "enforce" what I mean is when the user enters anything other than numerics nothing will happen.


Braintree drop-in auto-reload despite paymentMethodNonceReceived

So I have a single-page app, and a braintree drop-in located on the register page. There is an option for a free account, so I do not have the form that the drop-in is inside as the main form of the page.


So I have a form like this:



<form id="payment-form">
<div id="payment-box"></div>
<input type="submit" tabindex="-1" style="visibility:hidden;position:absolute;"/>
</form>


I have a handler on the form to prevent the form from submitting, and in my braintree setup, I've defined a paymentMethodNonceReceived handler, but when I trigger the form, the page reloads, depending on the url. If you watch the log, paymentMethodNonceReceived is not triggered.


For instance, my url for register is http://ift.tt/1Dm1vsL but when the form is triggered, it reloads to http://ift.tt/1Dm1vsL which I understand is usually the same page, but not with a single-page app like this. this triggers page reload and resets all my registration fields. If you run this again from the ?#! version of the url, then it works as expected, no reload and the handler is triggered. I do not want to add a ? to my url just for this.


I really like the drop-in and feel like this should work, but it sounds like I'm going to have to do a custom implementation. Is there something I'm missing?


Update SQL data via PHP/HTML form

I've got the following form which is a select with options, where the user selects an option such as email, address etc.. enter new data to update existing field which is done by selecting the field by matching it to a name.



<form action="sUpdateResponse.php" method="post">

<select id="sRetrieveUpdate" name="sRetrieveUpdate" onchange=";">
<option value='' disabled selected style='display:none;'>Select Field To Update</option>
<option value="address">Address</option>
<option value="email">Email</option>
</select><br>

<div id="box-1"><input type="text" id="address" name="sUpdateAddress" placeholder="Enter New Address..."
onClick="$(this).removeClass('placeholderclass')" class="dateclass placeholderclass"></input></div>

<div id="box-2"><input type="text" id="email" name="sUpdateEmail" placeholder="Enter New Email..."
onClick="$(this).removeClass('placeholderclass')" class="dateclass placeholderclass"></input></div>

For the staff entry
where the name matches...<br>
<input type="text" placeholder="Enter Forename..." name="sUpdateFN">
<input type="text" placeholder="Enter Surname..." name="sUpdateSN">
<input type="submit" value="Update Record" name="sRetrieveUpdate">
</form>


The response then checks to see if address or email was to selected and updates where the firstname and surname match the ones entered.



if(isset($_POST['sUpdateEmail']) && isset($_POST['sUpdateFN']) && isset($_POST['sUpdateSN']))
$query = "UPDATE staffData SET sEmail = '".$_POST['sUpdateEmail']."' WHERE sFN = '".$_POST['sUpdateFN']."' AND sSN = '".$_POST['sUpdateSN']."'";
$result = mysql_query($query);


if(isset($_POST['sUpdateAddress']) && isset($_POST['sUpdateFN']) && isset($_POST['sUpdateSN']))
$query = "UPDATE staffData SET sAddress = '".$_POST['sUpdateAddress']."' WHERE sFN = '".$_POST['sUpdateFN']."' AND sSN = '".$_POST['sUpdateSN']."'";
$result = mysql_query($query);


The only problem here is, when updating one field for some reason the other field goes empty, any idea where its going wrong?


Prevent a form from being submitted javascript why is there an obvious false statement returning true?


<script>
function someFunc() {
if (1==2) {
return true;
} else {
alert("Not submitting");
return false;
}
}
</script>


This is from stackoverflow here


prevent form submission (javascript)


I want to know what the purpose of the obvious false statement 1==2 returns true is for?


Access violation when opening form 2th time on Android in Delphi XE7

When I open my form for the first time I get no violation, but when I first select a TEdit field and then close the form and then recreate the form and open it I get the Violation.


Code for creating the form:



procedure TfrmNocoreDKS.actConfigExecute(Sender: TObject);
var
confForm: TConfiguratie;
begin
confForm := TConfiguratie.Create(nil);
confForm.ShowModal(
procedure(ModalResult: TModalResult)
begin
confForm.DisposeOf;//Also tried confForm.Free;
end);
end;


I've also tried this for creating the form:



procedure TfrmNocoreDKS.actConfigExecute(Sender: TObject);
var
confForm: TConfiguratie;
begin
confForm := TConfiguratie.Create(nil);
try
confForm.ShowModal(
procedure(ModalResult: TModalResult)
begin
end);
finally
confForm.free;
end;
end;


Code for Closing the form:



procedure TConfiguratie.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := TCloseAction.caFree;
end;


Because the violation only appears when you click on any TEdit and then close the form I think it has something to do with the virtual keyboard, but i'm not sure. I don't have any methods that use the virtual keyboard itself.


Moving form elements into a position where they look stacked

I have a login form I'm creating... The problem is, I can't align the text boxes and text correctly.


It looks like this at the moment:


Align fail


But i need it to look like:


Correctly aligned, Text is all different sizes but text and textboxes are stacked up and not further to the left


This is very hard to explain. What I really want is for the text and text boxes to stay on the same X axis but the Y axis can be changed.


I think it requires a table, however I do not know how to use those. If it does require one, an explanation of how to use a table to align these forms would be great.


Thank you for your help.


Javascript (Adobe Acrobat XI) populate 2nd page form from inputted answers from 1st page in form

I want to start by saying I'm NOT fluent in javascript, however, I am learning and can read the code and comprehend it. I make professional fillable PDF forms, using javascript to perform actions and calculations, but I've never had to do this before. My request is specifically for Adobe Acrobat XI Pro javascript.


I have an order form I created. I've added a button (called 'Create Invoice')on the page to adds a page (using:var a = this.getTemplate("Invoice"); a.spawn();) after the order form that presents the information that was entered or calculated from the first page. I ONLY want to show fields on the invoice that were selected on the first page.


Here's a screen shot [link] of a portion of the Order Form (pg 1): [IMG]http://ift.tt/1zjZ47Y] (I can't post images until 10 reputation)


So on the Invoice (pg 2) I want ONLY the (2) items chosen above to show, in immediate succession: [IMG]http://ift.tt/1JSJGuk] (I can't post images until 10 reputation)


The DESCRIPTION column will ideally concatenate the "Saddle Name" + "Color". The rest of the columns should be obvious (fill in with the associated fields for each item ordered).


So, what should the code look like for this? And should the Javascript be put onto a field or Document Javascripts?


(This is my first stackoverflow post, I apologize if I did anything wrong!)


Prevent form being submitted until final button - avoid edit page

I know there are a lot of similar questions on SO but I haven't found one that fits what I'm trying to do...(because I'm not 100% sure it is even possible to do what I am trying to do!!)


At the moment I have a page that creates several form_tags based on how many 'questions' there are in the 'test', like this:



<div class="jumbotron">
<% @test.questions.each do |question| %>
<div class="panel panel-info">
<div class="panel-heading">
<h3 class="panel-title">Question <%= question.question %></h3>
</div>
<div class="panel-body">
<p>
<%= image_tag question.image.url(:medium) %>
</p>
<%= form_tag edit_test_testsession_path(@test, question.testsessions), id: 'submit_answer' do %>
<%= radio_button_tag :answer, "A" %> A
<%= radio_button_tag :answer, "B" %> B
<%= radio_button_tag :answer, "C" %> C
<%= radio_button_tag :answer, "D" %> D
<%= submit_tag 'Submit', class: "btn btn-success", id: 'single_submit' %>
<% end %>
</div>
</div>
<% end %>
<br/>
<%= link_to "See Test Results!", results_path(@test), class: "btn btn-lg btn-info btn-block", id: "submit_all" %>
</div>


At the moment I have disabled the 'submit' buttons because I don't want the forms to actually be submitted until all of them are completed so I have this Javascript:



$(document).ready(function() {
$('.btn.btn-success').click(function(e) {
e.preventDefault();
this.value="Resubmit";
});

$('#submit_all').click(function(){
$('#submit_answer').each(function(){
$(this).submit();
});
});
});


It does attempt to submit the answers but still tries to take the user to an edit page, but of several [:id], which obviously doesn't work...


In my TestsessionsController I have this:



class TestsessionsController < ApplicationController

def new
@test = Test.find(params[:test_id])
@testsession = Testsession.new
redirect_to action: :create
end

def create
@test = Test.find(params[:test_id])
@test.questions.each do |question|
@test.testsessions.create user: current_user, question: question
end
redirect_to action: :index
end

def index
@test = Test.find(params[:test_id])
@questions = @test.questions
# @testsession = Testsession.find(params[:id])
end

def show
@testsession = Testsession.find(params[:id])
@test = Test.find(params[:test_id])
@questions = @test.questions
end

def update
@testsession = Testsession.find(params[:id])
# @question = Question.find(params[:question_id])
@testsession.update(params.require(:testsession).permit(:answer))
redirect_to action: :results
end

def edit
@testsession = Testsession.find(params[:id])
@question = Question.find(params[:question_id])
@testsession.update(params.require(:testsession).permit(:answer))
redirect_to action: :results
end

def results
@test = Test.find(params[:id])
@testsession = Testsession.find(params[:id])
end

end


Is there any way to force the last link to take it directly to the results page, but still submit the information from the form_tags?


At the moment it is just giving me this error:



No route matches [POST] "/tests/1/testsessions/%23%3CTestsession::ActiveRecord_Associations_CollectionProxy:0x007fe197a72e40%3E/edit"


and only when I hit the back button it takes me to the results page...


Form gets submitted even if the required fields are left empty in angular JS

I am newbie to angular JS and i have created a form which is


HTML



<div data-ng-controller="ReservationController"
<form class="form-horizontal" role="form">
<div class="form-group">
<div class="col-sm-10">
<label>Guest Name</label>
<input type="text" class="form-control" placeholder="" ng-model="res_guest_name" required>
</div>
</div>

<div class="form-group">
<div class="col-sm-10">
<label>Phone</label>
<input type="phone" class="form-control" ng-model="res_member_phone">
</div>
</div>
<div class="form-group">
<div class="col-sm-10">
<label>FAX</label>
<input type="phone" class="form-control" ng-model="res_member_fax">
</div>
</div>
<div class="form-group">
<div class="col-sm-10">
<label>Email</label>
<input type="email" class="form-control" ng-model="res_member_email" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-8 col-sm-10">
<button type="submit" class="btn btn-success" ng-click="res_save()">Save Changes</button>
</div>
</div>
</form>
</div>


CONTROLLER



function ReservationController($scope, $http, $cookieStore,$location,$filter) {
$scope.res_save = function()
{
var save_res ="http://ift.tt/1vFFwiT"+conId+"&token="+token+"&id="+$scope.resId+"&page=edit&guest_name="+$scope.res_guest_name+"&phone="+$scope.res_member_phone+"&fax="+$scope.res_member_fax+"&email="+$scope.res_member_email;
$http.get(save_res).success(function(response) {
alert('success');
});
}
}


My form gets submitted even after the required fields are left empty. it shows the error, then it gets submitted.


How do I find all input fields inside a form and copy their values into textarea using Javascript?

I want to add a couple of input fields (name, age, location, status, etc...) to my form.


When I click submit button, how do I get all the values inside a form and place them into a single textarea element, so that it's easy to copy? Thanks for the help!


My current code:



<form>
<input type="text" id="txt">
<button type="button" onclick="ShowText();">Submit</button>
</form>
<span id="show"></span>
<script>
function ShowText(){
var txt = document.getElementById('txt');
var show = document.getElementById('show');
show.innerHTML = txt.value;
}
</script>

contact form JS not sending but displaying success

Hi there im having some issues as i cant get my contact form to work at all ive been all over forums and even rebuilt the form several time stripping options to see where the issue is occurring - the success message is displayed but nothing arrives at the destination email address



any idea?

**HTML**
<form id="contactForm" action="php/contact.php" method="post">
<div class="row">
<div class="col-md-6">
<input name="senderName" id="senderName" type="text" placeholder="Company Name" required="required" />
<input name="contactName" id="contactName" type="text" placeholder="Contact Person" required="required" />
<input name="contactNumber" id="contactNumber" type="text" placeholder="Contact Number" required="required" />
<br>
<input type="email" name="senderEmail" id="senderEmail" placeholder="Email address" required="required"/>
</div>

<div class="col-md-6">
<textarea rows="4" name="message" id="message" placeholder="Message"></textarea>
</div>
</div>
<div class="row">
<div class="col-md-6">
<p>*Note: Details will not be shared with any 3rd parties.</p>
</div>
<div class="col-md-6">
<button type="submit" class="btn-main pull-left">Send</button>
</div>
</div>
</form>

**PHP**
<?php

// Define some constants
define( "RECIPIENT_NAME", "Clear View Services" );
define( "RECIPIENT_EMAIL", "gjd1982@gmail.com");
define( "EMAIL_SUBJECT", "New Message" );

// Read the form values
$success = false;
$senderName = isset( $_POST['senderName'] ) ? preg_replace( "/[^\.\-\' a-zA-Z0-9]/", "", $_POST['senderName'] ) : "";
$senderEmail = isset( $_POST['senderEmail'] ) ? preg_replace( "/[^\.\-\_\@a-zA-Z0-9]/", "", $_POST['senderEmail'] ) : "";
$message = isset( $_POST['contactName'] ) ? preg_replace( "/(From:|To:|BCC:|CC:|Subject:|Content-Type:)/", "", $_POST['contactName'] ) : "";
$message = isset( $_POST['contactNumber'] ) ? preg_replace( "/(From:|To:|BCC:|CC:|Subject:|Content-Type:)/", "", $_POST['contactNumber'] ) : "";
$message = isset( $_POST['message'] ) ? preg_replace( "/(From:|To:|BCC:|CC:|Subject:|Content-Type:)/", "", $_POST['message'] ) : "";



// If all values exist, send the email

if ( $senderName && $senderEmail && $message ) {
$recipient = RECIPIENT_NAME . " <" . RECIPIENT_EMAIL . ">";
$headers = "From: " . $senderName . " <" . $senderEmail . ">";
$success = mail( $recipient, $subject , $message, $headers );

}

// Return an appropriate response to the browser
if ( isset($_GET["ajax"]) ) {
echo $success ? "success" : "error";
} else {
?>
<html>
<head>
<title>Thanks!</title>
</head>
<body>
<?php if ( $success ) echo "<p>Thanks for sending your message! We'll get back to you shortly.</p>" ?>
<?php if ( !$success ) echo "<p>There was a problem sending your message. Please try again.</p>" ?>
<p>Click your browser's Back button to return to the page.</p>
</body>
</html>
<?php
}
?>


JS



function init(){$("#contactForm").show().submit(submitForm).addClass("positioned"),$('a[href="#contactForm"]').click(function()
{return "#contactForm").fadeTo("slow",.2),$("#contactForm").fadeIn("slow",function()
{$("#senderName").focus()}),!1})}function submitForm(){var e=$(this);return $("#senderName").val()&&$("#contactName").val()&&$("#contactNumber").val()&&$("#senderEmail").val()&&$("#message").val()?
($("#sendingMessage").fadeIn(),e.fadeOut(),$.ajax({url:e.attr("action")+"?ajax=true",type:e.attr("method"),data:e.serialize(),success:submitFinished})):($("#incompleteMessage").fadeIn().delay(messageDelay).fadeOut(),e.fadeOut().delay(messageDelay).fadeIn()),!1}function submitFinished(e)
{e=$.trim(e),$("#sendingMessage").fadeOut(),"success"==e?($("#successMessage").fadeIn().delay(messageDelay).fadeOut(),$("#senderName").val(""),$("#senderEmail").val(""),$("#contactNumber").val(""),$("#contactName").val(""),$("#message").val(""),$("#contactForm").delay(messageDelay+500).fadeIn()):($("#failureMessage").fadeIn().delay(messageDelay).fadeOut(),$("#contactForm").delay(messageDelay+500).fadeIn())}var messageDelay=2e3;$(init);

CakePHP Master/Detail Form - simple Issue

I'm building a simple master/detail edit form using Cake, but can't get the values from the details records to populate the form.


Workorder -> Master WorkorderIssues -> Detail


DebugKit tells me the data is being returned properly from both the master and detail tables.


I can populate the form with master data just fine using:


Form->input('workorder_ref');?>

..but the same approach doesn't work for the detail data:


Form->input('WorkorderIssues.issue_owner');?>

Post data:


Workorder(array) workorder_id 1 workorder_ref 9212


WorkorderIssues(array) 0(array) issue_id 1 issue_workorder_id 1 issue_owner shaun


I would appreciate some help..it's probably something simple I'm overlooking.


Many Thanks, Shaun


How can I clear h:messages in an ace:dialog after an ajax event?

I have a button (Make Popup Visible) which makes a pop-up visible. When the form is submitted (Submit The Form), an error message can sometimes appear in the h:messages field, which is expected.


My problem is that, when I close the pop-up (Make Popup Invisible) and then re-open it (Make Popup Visible) the h:messages field is still populated with the old error message.


Is there a way I can clear the messages when the (Make Popup Visible) is pushed? I don't want to do a full page submit to do this.


Button visibility:



<h:form id="mainForm">
<h:commandButton value="Make Popup Visible">
<f:ajax listener="#{controller.prepareDelete(item)}" render=":deleteItemPopup"/>
</h:commandButton>
</h:form>


Pop-up:



<ace:dialog id="deleteItemPopup" visible="#{controller.deleting}">
<h:panelGroup rendered="#{controller.deleting}" layout="block">
<h:messages for="deleteItemPopupForm"/>
<h:form id="deleteItemPopupForm">

<ui:insert name="content">
This contains a form which, when submitted, can cause
an error message to be created and populate the h:messages
field
</ui:insert>

<h:commandButton value="Submit The Form" action="#{controller.delete}"/>
<h:commandButton value="Make Popup Invisible">
<f:ajax listener="#{controller.cancel}" render=":deleteItemPopup"/>
</h:commandButton>

</h:form>
</h:panelGroup>
</ace:dialog>


Commands:



public void prepareDelete(Item item) {
deleting = true;
}

public void cancel() {
deleting = false;
}

public void delete() {
.
.
.
} catch (MyException ex) {
FacesUtils.sendMessage("deleteItemPopupForm", ex);
}


}


Symfony 2: How to build a really simple form, with just one field and use it in controller

I'm building a get started procedure. It is really very simple: just one field for the email and a submit button.


HOW DOES THE PROCEDURE WORKS I simply have one controller with two methods: indexAction() and endAction() The indexAction simply set the route using annotations and displays the twig template with an handmade form:



namespace AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Request;

class GetStartedController extends Controller
{
/**
* @Route("getstarted")
* @Template()
*/
public function indexAction()
{
return array(
// ...
);
}

/**
* @Route("getstarted/end", name="getStartedEnd")
* @Template()
*/
public function endAction(Request $request)
{

// ... other code


As you can see, currently the method really does nothing as the form is handmade directly in the twig template.


Here is the code to render the form (handmade in the twig template):



{% extends "::base.html.twig" %}

{% block title %}AppBundle:GetStarted:index{% endblock %}

{% block body %}
<form id="getStarted" action="{{ path('getStartedEnd') }}" method="post">
<div class="form-group">
<input type="email" name="userEmail" class="form-control input-lg" placeholder="Enter your e-mail (es.: your.name@example.com">
</div>
<button type="submit" name="submit" class="btn btn-default btn-lg">Submit</button>
</form>
{% endblock %}


I know Symfony 2 can handle the creation of the form and its rendering on the page, but this is a very simple form and I know it never will be more complicate, so an handmade one is the simplest and fastest solution.


Now, what's the problem? The problem is I don't understand how to get the form and its submitted values in my controller, in the other method, endAction().


The form has as action the path to the other method, endAction() where, in my intentions, I will retrieve the submitted values and do some stuff with them.


Following the instructions in paragraph Using a Form without a Class, i came up with the following code for the method endAction() that, in my intentions, will retrieve the submitted email and do something with it - will create a user, obviously - (note the exit to simply print the results of the if)



/**
* @Route("getstarted/end", name="getStartedEnd")
* @Template()
*/
public function endAction(Request $request)
{
$form = $this->createFormBuilder()
->add('userEmail', 'email')
->add('submit', 'submit')
->getForm();

$form->handleRequest($request);

if ($form->isValid()) {
$data = $form->getData();
print_r($data);
} else {
echo 'no data submitted';
}

exit;


return array(
// ...
);
}


The problem is that if ($form->isValid()) { ever returns false and I ever obtain as result the printing of echo 'no data submitted';


Clearly there is something wrong with my implementation of the form handling, but... What?


This is my question: what am I doing wrong? Why the form isn't "intercepted" in the controller?


Dropdown Form doesn't work unless i delete all the content

This problem is driving me crazy, i have the following drop-down form: Sign in

User Name --> Password Sign in


For some reason the button when i click it, it doesn't do ANYTHING. I don't know how to debug to be honest if any action is triggered and can't be performed. But the odd thing is if i remove everything inside the form but the login button it works, like this:


Sign in



<div class="form-group">
<button type="submit" class="btn btn-success btn-block">Sign in</button>
</div>
</form>
</div>
</div>
</ul>
</li>


So to be honest i have no idea what is going wrong, i tried a lot of things and nothing seems to be working. Any idea?


THanks. BTW im using Bootstrap and Jquery.


enctype="multipart/form-data" is not supported to send simple text?

when i m using enctype="multipart/form-data" in jsp form the simple text,date,number are not send to servlet it show null values , when i remove enctype="multipart/form-data" then form work fine....why...how.....


my jsp code....



<form method="post" action="<%=request.getContextPath()%>/ProfileServlet" enctype="multipart/form-data" >
<div class="form-group">
<label class="control-label">First Name</label>
<input type="text" placeholder="John" name="txtfname" class="form-control"/>
</div>
<div class="form-group">
<label class="control-label">Last Name</label>
<input type="text" placeholder="Doe" name="txtlname" class="form-control"/>
</div>
<div class="form-group">
<label class="control-label">Birth day</label>
<input type="date" placeholder="Doe" name="txtdate" class="form-control"/>
</div>


Photo

it show null values in servlet using enctype in jsp ,other wise it work fine.....


Select insert form in ApEx

I have page ,where I have one select list, which is placed in Region area(Body1) and it serves as a selector of insert forms. In anothers bodies (Body2 and Body3) I have two form which serve as insert form for data in tables. Then I have one dynamic action which serve to show/hide the form for insert. The problem is when I select one of the form and type data in form and then click on CREATE button, it throw this:


1 error has occurred ORA-06550: line 1, column 151: PL/SQL: ORA-00957: duplicate column name ORA-06550: line 1, column 13: PL/SQL: SQL Statement ignored


Maybe the problem is that I have two forms on one page.


Can anyone help how to fix ? Thanks


Keep form values when redirect back in Laravel 4

I'm trying to keep the values of a form when Redirect::back on Laravel 4, but I can't find a way to do this.


This is my form:



{{ Form::open(array('route' => 'generate', 'files' => true)) }}

{{ Form::radio('myType', '1', true); }}
{{ Form::label('myType', '1'); }}

{{ Form::radio('myType', '2'); }}
{{ Form::label('myType', '2'); }}

{{ Form::radio('myType', '3'); }}
{{ Form::label('myType', '3'); }}

{{ Form::text('myName'); }}

{{ Form::file('uploadImage'); }}

{{ Form::submit('Go'); }}

{{ Form::close() }}


And my controller:



$validator = Validator::make(Input::all(), array('uploadImage' => 'required|image', 'myName' => 'required'));

if ($validator->fails()){
return Redirect::back()->withErrors($validator);
}


I tryed something like:



return Redirect::back()->withErrors($validator)->with('nameValue', Input::get('myName'));


And then in the view:



{{ Form::text('myName', $nameValue); }}


But it still doesn't work. Any help will be appreciated.


symfony1 doctrine form submit - where to inject logic

I've got a simple form that includes an input that will take money, i.e. float. So far it can accept a well-formed decimal only, e.g. 12768.56. The task to inject some server-side logic (no javascript here) that would intercept the input value, like 12 768,56, replace it with 12768.56 and let symfony/doctrine do its work. The transformation is just an example and I'ev got what I need, but the question is - where should I put the intercepting function? I guess it should be somehwere in the XxxForm.class.php. But I don't know which method. doSave? processData? I'm pretty sure there is a special place for that...


How to display data from one single column into multiple inputs?

I work on an application and I have a model with a 'movies' attribute (top 5 movies). When a user tries to edit the top 5 movies I want to display each movie in a different input, but I don't know how to do it (because all 5 movies represent one single attribute)


In my controller



def show
@user = User.find(params[:id])
@user.movies = @user.movies.split(',')
end


In my model



<%= form_for @user do |f| %>
<%= f.label :movies %>
<%= f.text_field :movies[0] %>
.
.
.
<%= f.label :movies %>
<%= f.text_field :movies[4] %>
<% end %>


Of course, this doesn't work!


upload file inside a form html

I want to create a form to submit a product which has a features to upload images inside the form.


my difficulties are :



  1. I find it hard to upload files without losing data that already fill by user in the form.

  2. I want the user upload the file first then user presses the submit button


this is the sequence :


user open addProduct.php-> then the user fill the form -> the user upload picture -> finally the user press submit button to save their data


how to validate a from before submit in codeigniter

i want to validate a from before submit using jquery in codeigniter but i am confused how to validate a form before submit. I know the validation class in codeigniter but i want validate a form in front end.


Won't run ajax if I change input type..?

I have a form for user to update their info using jquery + Ajax. Everything is working great so far, but WHen i change input type="email" to input type="text" in the fullname section of the form and click update. It got error??? It won't run the php file in ajax. I don't see any connection which causes this error? Anyone please sugguest why? But if I change input type in the fullname section back to "email". It works! This is so weird!


Here is my form:



<div id="changeuserinfo_result"></div>
<form role="form" method="post">
<div class="form-group">
<label>Fullname</label>
<input type="text" class="form-control" id="changename" name="changename" value="<?php echo $_SESSION['name'] ?>">
</div>
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" id="changepass" name="changepass" value="<?php echo $_SESSION['pass'] ?>">
</div>
<button class="btn btn-default" id="changeuserinfo">Update</button>
</form>


Here is my jquery code:



$(document).ready(function(){
$('#changename').focus();
$('#changeuserinfo').click(function(){
var changename = $('#changename');
var changepass = $('#changepass');
var changeuserinfo_result = $('#changeuserinfo_result');
changeuserinfo_result.html('loading...');
if(changename.val() == ''){
changename.focus();
changeuserinfo_result.html('<span class="errorss"> * Empty fullname</span>');
return false;
}
else if(changepass.val() == ''){
changepass.focus();
changeuserinfo_result.html('<span class="errorss">* Empty password</span>');
return false;
}
else {
var UrlToPass = {changename:changename.val(),changepass:changepass.val()} ;
$.ajax({
type : 'POST',
cache: false,
data : UrlToPass,
url : 'changeuserinfo.php',
success: function(responseText){
if(responseText == 1){
$('#changeuserinfo_result').html('<span style="color:green"> Update OK</span>');
}
else{
$('#changeuserinfo_result').html('<span class="errorss"> Update fail. Try again</span>');
}
}
});
}
});
});

vendredi 27 février 2015

This form should not contain extra fields. on multile submite button

I have a two part form in symfony2 of a single table db. On my edit page i display whole form with two save buttons. when i edit some field and try to save it that shows the extra field error my controller code is



$form = $this->createForm(new PatientfullType(), $test, array());
$formadd = $this->createForm(new PatientfulladdType(), $test, array());
.
.
if ($form->get('save')->isClicked()) {

return $this->render('AdminBundle:FormsController:patientformfull.html.twig', array('formadd' => $formadd->createView(),'form' => $form->createView() ));
// probably redirect to the add page again
}

else
{


return $this->render('AdminBundle:FormsController:patientformfull.html.twig', array('formadd' => $formadd->createView(),'form' => $form->createView() ));
}


my twig file has two object


form and formadd



<div class="row" style="margin-bottom: 15px;">
<div class="col-xs-3">
{{ form_label(form.sex) }}
</div>
<div class="col-xs-9 col-sm-4 col-md-3">
{{ form_widget(form.sex, {'attr': {'class': 'form-control'}}) }}
</div>
</div>
<div class="row" style="margin-bottom: 15px;">
<div class="col-xs-3">
{{ form_label(formadd.ChronicDiseases) }}
</div>
<div class="col-xs-9 col-sm-4 col-md-3">
{{ form_widget(formadd.ChronicDiseases, {'attr': {'class': 'form-control'}}) }}
</div>
</div>
</div><div class="col-xs-9 col-sm-5">
{{ form_widget(form.save , {'attr': {'class': 'btn btn-success'}}) }}

{{ form_widget(form.cancel , {'attr': {'onclick': 'cancelRedirect()','class': 'btn btn-default'}}) }}

</div>


</div><div class="col-xs-9 col-sm-5">
{{ form_widget(formadd.save1 , {'attr': {'class': 'btn btn-success'}}) }}


</div>