Been scratching my head for too long on this: Using jquery.form, (http://malsup.com/jquery/form) with PHP ... my $_FILES['someimage'] gets set but the error number is always UPLOAD_ERR_NO_FILE, size is also 0.
The JavaScript:
$('form input[type=file]').change(function () {
$(this).clone().appendTo('#imgform');
$('#imgform').ajaxForm();
$('#imgform').ajaxSubmit({
type: 'POST'
});
});
Which appends to:
<form id="imgform" method="POST" action="/api/images.php" enctype="multipart/form-data"></form>
From another form which has bog-standard file inputs.
PHP logs are clean, but var_dumping $_FILES always shows that the index is set to the name of the form element ... but no data.
Thanks guys!
(Sorry, I know jQuery-like questions are too frequent round these parts).
EDIT
I found Clone a file input element in Javascript which contains further information and suggested alternatives.
What I decided to do is have a single form for non JavaScript browsers, and JavaScript/jQuery breaks the single form into three forms:
Head form -> File upload form -> tail form
Then I can post the file upload async, and when the tail's submit is clicked, glue the form together into a POST as they are just text fields.
Two things I see when I try to run this. Since you are cloning then appending, I wonder if your file input exists within the context of the form. If not, then $('form input[type=file]') will never find the element to be cloned.
Perhaps the biggest problem, though, is in the way browsers handle file upload controls. You cannot programmatically set a value on a file input control - otherwise it would be trivial as a web developer to automatically set the file upload value to "c:\Files\MyPasswordFile.txt" and automatically submit the form invisibly to the user.
When I changed your code to this:
<input type="file" name="imageFile" />
<form id="imgform" method="POST" action="/api/images.php" enctype="multipart/form-data">
</form>
<script>
$('input[type=file]').change(function() {
alert("ACTION");
$(this).clone().appendTo('#imgform');
//$('#imgform').ajaxForm();
//$('#imgform').ajaxSubmit(
// {
// type: 'POST'
// }
// );
});
</script>
I can see the behavior as above - the field is cloned and appended - but it has no value. Since part of the clone process involves setting the field value - this would violate that security restriction and thus fails.
You can't post files using ajax as javascript cannot access any local hard drive for security reasons.
There are ways to mimic ajax posting using iFrames. This link is a good example.
http://www.ajaxf1.com/tutorial/ajax-file-upload-tutorial.html
Related
Is there a way to make a field required for form submission?
I can use HTML, Javascript or PHP to do this - whichever works.
I want to ensure that a form is not submitted with a blank value. Also it would be nice if I could make it so that users HAD to input values into certain fields.
EDIT: I don't really want to use jQuery at the moment as I'm not sure that my boss wants me to use jQuery.
Tried to do this:
<script type="text/javascript">
$('addorg').submit(function(){
if($('orgname').val()==""){
alert("Organization Name must be Filled");
return false;
}
})
</script>
And here's the HTML it is working on:
<form name="addorg" action="addorg.php" enctype="multipart/form-data" method="POST">
<div id="orgdiv"> <fieldset><label for="orgname">Organization Name</label>
<input type="text" name="orgname" id="orgname"/>
</fieldset>
</div>
This is for client-side validation. I can handle server-side validation, my PHP is far better than my Javascript or jQuery.
The client-side validation did not seem to work.
Nothing will ever prevent a form from being submitted to your web server. You can submit anything you like using tools like Curl. Therefore, you must always validate on the server. For normal users, you can put JavaScript in your page that blocks submitting invalid forms.
Therefore:
Is there a way to make a field required for form submission?
No.
I want to ensure that a form is not submitted with a blank value. Also it would be nice if I could make it so that users HAD to input values into certain fields.
You cannot. However, #Nicolas's answer shows how you can add client-side validation to block typical users from submitting the form and server-side validation to block everything else. His approach is correct.
You can do this in either JavaScript or PHP. JS is more user friendly and easier to code, but can be bypassed by determined users. It also may not function on some browsers or with some settings allowing users to continue as if there were no validation, but those cases are usually rare. I would recommend a JS solution unless this is a corporate website or has no room for error.
You can do this by modifying your form tag with an onSubmit function:
<form action="whatever" method="post" onSubmit="checkStuff();">
<input id="field_1" name="field_1"...>
You then need to create that function and place it in the head of your page. It should read something like:
function checkStuff() {
// By default, we plan to submit the form.
var formOkay = 1;
// Check to see if field_1 has a value. If not, we note that by changing our variable.
if (document.getElementById('field_1').value == '') formOkay = 0;
...
// Let the user know something is wrong somehow. An alert is easiest.
alert('fill out everything, ya goof!');
// If you return true the form will submit. If you return false it will not.
if (formOkay == 1) {
return true;
} else {
return false;
}
}
Note that your inputs must have an id attribute for this approach to work (though it's possible to modify my code to work with names too). I would make the id the same value as the field name. You can add additional checks for more fields where I placed the ellipsis. This code could be written more efficiently and cleanly, but I thought this approach would be easiest to understand and modify.
This is off the top of my head and hasn't been tested, but should get you working down the right track. If you have additional questions, please let me know.
EDIT:
I just wanted to follow up to agree with others that if you have the time and inclination, or this is a work related issue, you should validate both ways. JS provides a better, more user friendly method, while PHP insures nobody can just circumvent the JS to break your rules.
I don't know PHP, but your pseudo code would be something like this:
if field_1 = "" then
// Option 1
Print("Please press back and fill out field 1!")
AbortPage()
// Option 2
Redirect("form.php?error=Please fill out field 1&[other form values]")
end if
In the case of option 2 you would modify the form page to detect url variables and place them into the inputs. You would also modify it to look for a url variable called 'error' and display the contents if found.
Javascript should do it easily. Here's an example in jquery.
<input id="required" type="text />
Then, in your javascript library, you have something like:
if($("#required").val().length!=0)
{
formsubmit();
}
else
{
alert("You left the required field blank");
}
$('form').submit(function(){
if($('thisemptyfield').val()==""){
//do stuff
return false; //will cancel form submission
}
})
Makes that if thisemptyfield is empty, the submission of the form is cancelled. I encourage putting up a flag telling your user to fill in the field before submitting. Because with that code only, nothing will happen on the page. It just wont submit until the form is submitted with a value in the field.
Edit: This is using jQuery.
I have this form and I would like to read the uploaded file and then fill out the form using this read information without refreshing the page.
For example the first word might be "Bob" and so I would want that to go in my input text "First_name." I've been trying to searching online for a way to do this using JQuery or Ajax but I can't seem to find a solution.
Can this be done using the two methods previously mentioned? If so and if not can someone point me to a link or to where I can learn how to do this? The instances I have found include where one uses JQuery to upload the file and display the size without refresh (which is not exactly what I want).
I have also found how one can use an iFrame but this again is not what I want. I suppose I could always just submit the part of the page containing the textfile related information and show the same form but with the filled out information. But I feel as if this is kind of sloppy and I want to know if there is a better way.
Thanks.
Firefox has a method to do this, the File and FileList API provide a way to get at the files selected by a file input element and have a text retrieval method.
A very basic example:
NB. Not all browsers support this code.
[I think Chrome, Firefox and Opera do at time of writing.]
HTML:
<form>
<input type="file" name="thefile" id="thefile" />
</form>
<div id="text"></div>
JS (using jQuery):
$(document).ready(function() {
$('#thefile').change(function(e) {
if (e.target.files != undefined) {
var reader = new FileReader();
reader.onload = function(e) {
$('#text').text(e.target.result);
};
reader.readAsText(e.target.files.item(0));
}
return false;
});
});
Demo: http://jsfiddle.net/FSc8y/2/
If the selected file was a CSV file, you could then process it directly in javascript.
.split() will be useful in that case to split lines and then fields.
the only way I know would be to submit the form to a hidden iframe. this will upload teh file without refreshing the page. you can then use any returned info using javascript. this is what they use for fake ajax style image uploads that let you preview an image before uploading. the truth is it already has been uploaded via a hidden iframe. unfortunately however iframes are not xhtml 1.0 compliant.
something like this article may help:
http://djpate.com/2009/05/24/form-submit-via-hidden-iframe-aka-fake-ajax/
The question you might ask is :
why should I use this method instead of real ajax ?
Well they’re is numereous answer to that but one good reason it that
is doesnt require any type of ajax libs and you can start using it
even if you never used ajax before.
So here it goes.
<form method=”post” action=”formProcess.php” target=”hiddenIFrame”>
<input type=”text” name=”test” /> </form>
<iframe style=”width:0px;height:0px;border:0px;” name=hiddenIFrame />
This is just a normal form but you’ll notice the target in the form
tag, this tells the form to submit in the iframe instead of the
current page.
It’s works exactly as the target attribut on the A tag.
Also the iframe is hidden from the user using
style=”width:0px;height:0px;border:0px;”
now the file formProcess.php is not different from your normal form
processing file but if you want do something on the main page you have
to use JS like that :
window.parent.whatEverYouWannaDoInParentForm();
You can also upload file with this method !
Please checkout the formphp for full example.
Cheers !
Nb : You will see the status bar acts like the page is reloading but
it’s really not.
I am using the project 'ModalBox' from http://okonet.ru/projects/modalbox/index.html in order to generate my modal.
I am also using this overall script that persists e-mails submitted via form into a basic text file as a simple/quick solution. http://www.knowledgesutra.com/forums/topic/25586-php-simple-newsletter-script/
I have a dilemma though.
In order to keep the modal and display my 'mailing_thankyou.php' my form has to have 'onsubmit="return false"' but in order for my php script to work, I have to remove that return false, but then it changes to a new page in order to persist that information.
Does anyone have any ideas?
This is the main part in question:
myModal.html
<div id="signUp">
<form action="mailer/mailing.php" id="myForm" method="post" class="style16">
<input type="text" name="email" size="30" value="your email here!">
<input type="submit" value="Send link" name="submit" onclick="Modalbox.show('mailer/mailing_thankyou.php', {title: 'Form sending status', width: 500, params:Form.serialize('myForm') }); return false;">
or Cancel & close
<!-- ><input type="submit" value="GO!" name="submit"> -->
</form>
</div>
You may pull my files from my git repo:
https://github.com/jwmann/Modal-Sign-up
I'm not good at Mootools, so I will give you an example in jQuery - if you get the idea, I'm pretty sure you will find the right syntax for Mootools too.
The idea is to use AJAX call for form submission (and keep the onsubmit="return false;" so that browser window isn't reloaded):
var $form = $('#myForm');
$.post($form.attr('action'), $form.serialize(), function(response) {
$('div#signUp').html(response);
});
What this does is:
Stores jQuery wrapped form element into $form
Uses form's action attribute value as a request target address
Serializes and transfers all form elements' values
Executes callback function, which takes returned HTML code and replaces contents of <div id='signUp'>...</div> with this HTML.
Note: make sure that the script at forms action only returns html for the contents of the sign up box (meaning no <head>, <body>, etc. - only what should be in the box afterwards)
EDIT/AMENDMENT
This is what I've just found out on MooTools Docs page for Ajax/Request:
The equivalent of my jQuery snippet in MooTools would be
new Request.HTML({ // Creates an AJAX request
'url': $('myForm').get('action'), // Sets request address to the form's action
'update': $('signUp') // Indicates that results should be auto-loaded into element with id='signUp'
}).post($('myForm')); // Indicates that this form has to be serialized and transferred; also starts the request process
This requires that the form's action returns the result to display (a thank you message). One could achieve that by making redirect from the server-side after form data has been successfully processed, e.g. in PHP header('Location: mailer/mailing_thankyou.php'); exit;
After looking longer at your code I realized, that this is not entirely what you want (as I see you don't want the form replaced with the thank-you message - you want it to be shown in the modal). Hence the updated solution for your case:
new Request.HTML({ // Creates an AJAX request
'url': $('myForm').get('action'), // Sets request address to the form's action
'onSuccess': function() { // Defines what to do when request is successful (similarly you should take care of error cases with onFailure declaration
Modalbox.show('mailer/mailing_thankyou.php', {
title: 'Form sending status',
width: 500
// I have removed params from here, because they are handled in the .post() below
});
}
}).post($('myForm')); // Indicates that this form has to be serialized and transferred; also starts the request process
Pardon me if any of this doesn't work (as I said, I'm more of a jQuery guy - just trying to help here)
Have the form submit to a hidden iframe on the page. Give the iframe a name value and then set a target propery on the form. You can make the iframe 1x1 pixel and set the visibility to hidden (if you hide via display: none it might not work in all browsers.)
See this question for details:
How do you post to an iframe?
I removed the 'return false' from the input submit's 'onsubmit' (duhhh facepalm) because it was trying to serialize it in the first palce with prototype.js
Then I changed the php script so it would grab with $_GET instead of $_POST
no added functionality or hacks needed. Thank you for all the help though.
In PHP, in a particular CMS I am using a custom field, which works like google suggest.
As in, for each letter I type an SQL query is performed and matching records are displayed. When clicking on a record it fills the field with that record.
I am fairly certain this is all done with JavaScript.
I need to know how I can access the resultant content of that field, with the text placed through JS, before it is submitted so I can explode() it.
The CMS I am using is using mootools, so a solution relying on mootools would be ideal.
(This answer assumes that you have control over the markup of your forms (the form that requires a string "explosion" before submit) and/or you feel comfortable tinkering with whatever plugins you're using.)
first, make sure that you aren't submitting your form using an actual submit button (). We'll need to submit the form using javascript after fiddling with the field's contents.
next, make sure that your input box (the one you're grabbing text from) and your hidden inputs have unique ids. This will make it easier to query the DOM for the data we need.
Inside your form, in place of a "real" submit button, create a form button:
<form action="something.php" name="myform">
<input type="hidden" id="hiddenItem">
// SOME STUFF
<input type="text" id="autocomplete_field" value="whatever"/>
// SOME OTHER STUFF
<input type="button" value="Submit" onclick="processForm(this)"/>
</form>
Then, write a javascript function to process the string and submit the form:
processForm = function(el){
text = $('autocomplete_field').get('value');
// Lets assume the strings separates words (what you're exploding apart) using spaces
// something like 'DOGS CATS BIRDS PETS'
var array = text.split(' ');
// returns ['DOGS','CATS','BIRDS','PETS']
$('hiddenItem').set('value',array[0]);
// #hiddenItem now has the value 'dogs'
//SUBMIT THE FORM
el.getParent('form').submit();
};
Hope this helps!
You could try to use JS to send the field on some event (onkeyup?) to your php script. After it does it's part, store the result as a session variable and you can retrieve that later.
Try using jquery's get function.
Was that your question?
Im looking for a way to have a form in cakephp that the user can add and remove form fields before submitting, After having a look around and asking on the cake IRC the answer seems to be to use Jquery but after hours of looking around i cannot work out how to do it.
The one example i have of this in cake i found at - http://www.mail-archive.com/cake-php#googlegroups.com/msg61061.html but after my best efforts i cannot get this code to work correctly ( i think its calling controllers / models that the doesn't list in the example)
I also found a straight jquery example (http://mohdshaiful.wordpress.com/2007/05/31/form-elements-generation-using-jquery/) which does what i would like my form to do but i cannot work out how to use the cakephp form helper with it to get it working correctly and to get the naming correct. (obviously the $form helper is php so i cant generate anything with that after the browser has loaded).
I an new to cake and have never used jQuery and i am absolutely stumped with how to do this so if anyone has a cakephp example they have working or can point me in the right direction of what i need to complete this it would be very much appreciated.
Thanks in advance
I would take the straight jquery route, personally. I suppose you could have PHP generate the code for jquery to insert (that way you could use the form helper), but it adds complexity without gaining anything.
Since the form helper just generates html, take a look at the html you want generated. Suppose you want something to "add another field", that when clicked, will add another field in the html. Your html to be added will be something like:
<input type="text" name="data[User][field][0]" />
Now, to use jquery to insert it, I'd do something like binding the function add_field to the click event on the link.
$(document).ready( function() {
$("#link_id").click( 'add_field' );
var field_count = 1;
} );
function add_field()
{
var f = $("#div_addfield");
f.append( '<input type="text" name="data[User][field][' + field_count + ']" />' );
field_count++;
}
Of course, if a user leaves this page w/o submitting and returns, they lose their progress, but I think this is about the basics of what you're trying to accomplish.
This was my approach to remove elements:
In the view, I had this:
echo $form->input('extrapicture1uploaddeleted', array('value' => 0));
The logic I followed was that value 0 meant, not deleted yet, and value 1 meant deleted, following a boolean logic.
That was a regular input element but with CSS I used the 'display: none' property because I did not want users to see that in the form. Then what I did was that then users clicked the "Delete" button to remove an input element to upload a picture, there was a confirmation message, and when confirming, the value of the input element hidden with CSS would change from 0 to 1:
$("#deleteextrapicture1").click(
function() {
if (confirm('Do you want to delete this picture?')) {
$('#extrapicture1upload').hide();
// This is for an input element that contains a boolean value where 0 means not deleted, and 1 means deleted.
$('#DealExtrapicture1uploaddeleted').attr('value', '1');
}
// This is used so that the link does not attempt to take users to another URL when clicked.
return false;
}
);
In the controller, the condition $this->data['Deal']['extrapicture1uploaddeleted']!='1' means that extra picture 1 has not been deleted (deleting the upload button with JavaScript). $this->data['Deal']['extrapicture1uploaddeleted']=='1' means that the picture was deleted.
I tried to use an input hidden element and change its value with JavaScript the way I explained above, but I was getting a blackhole error from CakePHP Security. Apparently it was not allowing me to change the value of input elements with JavaScript and then submit the form. But when I used regular input elements (not hidden), I could change their values with JavaScript and submit the form without problems. My approach was to use regular input elements and hide them with CSS, since using input hidden elements was throwing the blackhole error when changing their values with JavaScript and then submitting the form.
Hopefully the way I did it could give some light as a possible approach to remove form fields in CakePHP using JavaScript.