Hi I am using codeigniter for file uploading and I am using this code
echo form_open_multipart('controller_a');
echo form_upload('userfile');
echo form_submit('Upload','upload');
echo form_close();
I store the pointer to the uploaded file in the database,
My question is how do I make sure that the user has selected a file before clicking on upload button because as of now the code submits even if the user clicks directly on upload without selecting a file
Along with client side verification, you should use server side verification, too. Currently, CodeIgniter does not provide a function, so one can use native PHP function is_uploaded_file:
if (is_uploaded_file($_FILES['myfile']['tmp_name']))
{
$this->load->library('upload');
$this->upload->do_upload('myfile');
}
You can't, not in CodeIgniter at least. You'll need to have JS overwrite the onsubmit property of the form and then test the userfile input's value.
use JS
very basic code, but it works.
<script type="text/javascript">
<!--
function validate_form ( )
{
valid = true;
if ( document.upload_form.something.value == "" )
{
alert ( "Please select a file before clicking upload ! " );
valid = false;
}
return valid;
}
//-->
</script>
and use onsubmit even in the form
onSubmit="return validate_form ( );"
when a user click on upload button without selecting any file, it will alert the user .
Your best bet is to use a jQuery plugin like the following:
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
This will allow you to select what input values will need to be selected, and customize a message to inform the user what field(s) they are missing.
Related
Is there a way to check in a blade view if an image is really there or not?
I need to show results from a search box.
The results are many boxes with infos and a picture for each box.
The point is in my DB I store links to images that are on remote servers and also name of images that are stored locally.
So what I am doing is check if the file exists locally and if so use it and if not look on the remote server (if the picture data is not NULL it's either there or in a remote server).
I was trying to check if file exists using curl and it works but for big collections it takes too much time to finally spit the data to the view (every link has to be checked).
So what I want to do, if possible, is check directly in the blade view if the picture is not broken (404) and if so replace with an "image-not-found.png" I store locally. How can I do that?
I usually handle this with JavaScript using the img tag's onerror event. Typically I add a few more bells and whistles to the solution but this is it in a nutshell.
Plan JavaScript
function loadNextImage(id,uri){
document.getElementById(id).src = uri;
}
Plain HTML
<img src="http://local/image.jpg"
onerror="loadNextImage('image1', 'http://remote/imae.jpg'));"
id='image1' />
VueJS and Webpack
<template>
<img :src="local_url" #error="imgOnError()" ref="image"/>
</template>
<script>
export default{
name: 'Thumbnail',
props: {
local_url: String,
remote_url: String
},
methods: {
imgOnError: function (e) {
this.$refs.image.src = this.remote_url
}
}
}
</script>
You can use the func "file_get_contents" inside a try-catch block. I know i not the best way, but i could work for you.
Tray this (no the best way):
<?php
try{
$img = 'myproject.dev/image.jpg';
$test_img = file_get_contents($img);
echo "<img src='{$img}'>";
}catch(Exception $e){
echo "<img src='img/no-img.jpg'>";
}
?>
I have written a Joomla component which is working well. I now want to add a button to an admin list view that when clicked automatically starts a CSV download of only the items selected in the list.
I'm OK with the model logic, the problem I've got is passing the selected cids or presenting raw output without the template.
If I use JToolBar's appendButton function to add a 'Link' type button, then I can send the user to a URL with 'format=raw', but I can't send information about which items were checked.
If I use JToolBarHelper::custom to add a custom list button, then I can send the information about which buttons were checked, but I can't send format=raw
As far as I can see there are two solutions, but I don't know how to implement either of them. Option one would be to force templateless raw output without a URL parameter of format=raw. Option two would be to set a hidden variable with format=raw in the admin form.
Any help would be appreciated
I've solved this as follows:
I added this hidden field to the admin form
<input type="hidden" name="format" value="html" />
Then subclassed JToolbarButtonStandard overriding the _getCommand with
protected function _getCommand($name,$task,$list)
{
JHtml::_('behavior.framework');
$message = JText::_('JLIB_HTML_PLEASE_MAKE_A_SELECTION_FROM_THE_LIST');
$message = addslashes($message);
if ($list)
{
$cmd = "if (document.adminForm.boxchecked.value==0){alert('$message');}else{document.getElementById('adminForm').format.value='raw'; Joomla.submitbutton('$task')}";
}
else
{
$cmd = "document.getElementById('adminForm').format.value='raw'; Joomla.submitbutton('$task')";
}
return $cmd;
}
So that when the button was clicked it changed the format parameter from html to raw.
I'm not going to mark this as solved in case anyone has any better ideas
I am incorporating Fine Uploader into a form that already exists.
I've added three Fine Uploader file upload fields. I have one script that controls all three of the boxes. I looked at the inputName attribute and attempted to change that, but it changed the name of all of the fine upload fields to what i set as the inputName (in this case it was photo1). That's not exactly what i want. I want to set the inputName for each field to something different.
In my case, it is important that I have 3 individual boxes because I have a message box that goes with each photo.
I mainly just want to use Fine Uploader for its ability to allow iphone users to select a photo if they are on the phone and also for the thumbnail preview after the photo is selected. All that stuff is great.
The rest of the form I have is already functioning and I can submit it using standard input file fields.
Questions:
Is there a way to use multiple fields on a single page? Do I need to
write a seperate $('#photo1').fineUploader(){...}); per input box?
Is there a way to change the input name for each file upload field?
I assume i can achieve this with seperate script blocks, but is
there a better/cleaner than repeating all that code?
I downloaded the PHP Server Handler files and when i submit my test form with interceptSubmit: true, I see the images upload to my server. That works. (i kinda made a simple form just to test it out). When i change to interceptSubmit: false, add a page called thankyou_post.php as my post action page and in that page I'm just seeing what the form is sending by print_r($_POST); and all i get is Array ( [submit] => submit ) as the response.
I suppose my next step will be to try to write custom blocks per file field and see if the form can process that better.
$(document).ready(function () {
$('#photo1, #photo2, #photo3').fineUploader({
debug: true,
template: "qq-dav-photo-with-thumb",
thumbnails: {
placeholders: {
waitingPath: "placeholders/waiting-generic.png",
notAvailablePath: "placeholders/not_available-generic.png"
}
},
form: {
interceptSubmit: false
},
camera: {
ios: true
},
request: {
endpoint: 'thankyou.php',
paramsInBody: true,
inputName: 'photo1'
},
messages: {
emptyError: 'File is empty',
noFilesError: 'No files attached.',
onLeave: 'We are still uploading your files...Please wait.'
},
validation: {
allowedExtensions: ['jpeg', 'jpg', 'gif', 'png'],
itemLimit: 3,
stopOnFirstInvalidFile: true
}
}).on('progress', function (id, fileName, uploadedBytes, totalBytes) {
console.log('progress...');
}).on('complete', function(event, id, fileName, responseJSON) {
if (responseJSON.success){
file_name = responseJSON.name;
console.log('hoorah! File name: '+file_name);
};
}).on('allComplete', function(event, id, fileName, responseJSON) {
console.log('hoorah! All complete!');
});
});
Any thoughts on what i can do to make this work?
UPDATE #1
LINK: http://ijwebsites.com/fineuploader/
This is the HTML on my form page.
<form action="thankyou_post.php" method="post"
id="qq-form" name="webform" enctype="multipart/form-data" >
<!-- Fine Uploader DOM Element
====================================================================== -->
<div id="photo1"></div>
<br>
<br>
<div id="photo2"></div>
<br>
<br>
<div id="photo3"></div>
<input type="submit" name="submit" value="submit">
</form>
And my thankyou_post.php page for my test page is very basic, i just want it to tell what values were submitted to the page so i am doing on that page:
<?php
if ($_FILES["photo1"]["error"] > 0) {
echo "Error: " . $_FILES["photo1"]["error"] . "<br>";
} else {
echo "Upload: " . $_FILES["photo1"]["name"] . "<br>";
echo "Type: " . $_FILES["photo1"]["type"] . "<br>";
echo "Size: " . ($_FILES["photo1"]["size"] / 1024) . " kB<br>";
echo "Stored in: " . $_FILES["photo1"]["tmp_name"];
}
?>
When I submit the form, i get a message "Error: 4". What do you think the problem is?
If you'd like to have multiple uploaders on the same page, and have varying options for each uploader (in this case, a differing request.inputName option), you'll need to initialize each instance separately. You can combine initialization into a common function that takes the input name as a parameter, if you'd like.
If you want Fine Uploader to send the entire contents of your form, including the selected files, ensure the form.interceptSubmit option is set to true (this is the default anyway). If you do not want this to happen, and you want to upload selected files in a separate request, then you should not enable form support at all in Fine Uploader. Form support was created for those who want Fine Uploader to completely manage a form.
It's not clear from your question what your form or forms look like, as you have left out your markup. If you are expecting Fine Uploader to control multiple file input elements in a single form, then you will need to make use of the extraButtons option.
I am using Yii-user extension in the main layout i have a sign up link which is common to all the Cmenu
view/main layout
echo CHtml::link('Signup','#',array('id'=>'regi'));
$("#regi").click(function(){
$.ajax({
type:'GET',
url:'<?php echo Yii::app()->request->baseUrl;?>/index.php/user/registration',
success:function(res){
$("#dispdata").show();
$("#dispdata").html(res);
}
});
});
<div id="dispdata"><div>
**yii user extension **renders this perfectly and even submit its correctly if form values a re valid.
but if the values are incorrect and blank it redirect to url .../user/registration
which is not what my need .I need guidance what do i do such that if the values are incorrect or blank it should not redirect and display the errors in model window.
I did tried but hardly could get the satisfied results
if i place the following the model window itself doesnt appear what do i do
module registrationController i placed
....//some code here (**in yiiuser register controller**)
if ($model->save()) {
echo CJSON::encode(array(
'status'=>'success',
));
}
....//some code here...
Yii::app()->clientScript->scriptMap['jquery.js'] = false;
$this->renderPartial('registration',array('model'=>$model,),false,true);
in module view registration
<?php echo CHtml::ajaxSubmitButton(Yii::t('registration'),CHtml::normalizeUrl(array('user/registration','render'=>false)),array('dataType'=>'json',
'success'=>'function(data) {
if(data != null && data.status == "success") {
$("#registration-form").append(data.data);
}
}')); ?>
can anyone please guide me am working past 10 ten days tried every hook or crook method but could not obtain the results......how can the model window with client side validation be done appear..... Please guide me or let me know something better can be done
rules in registration model
if (!(isset($_POST['ajax']) && $_POST['ajax']==='registration-form')) {
array_push($rules,array('verifyCode', 'captcha', 'allowEmpty'=>!UserModule::doCaptcha('registration')));
as well was not with attributes for reqired field
have changed to
array_push($rules,array('verifyCode', 'captcha','message' => UserModule::t("captcha cannot be blank.")));
and added the verifycode to required field
yet not working,
The simple way is using render method in your Ajax action and creating empty layout for this action. If you do so, validation scripts will be included in the server response. Also you need to exclude jquery.js and other script with Yii::app()->clientScript->scriptMap and include them in main layout always.
I am generating my own Wordpress template and would like to give users a front-end form (so they don't have to log in to the wordpress dashboard) to submit some post content. I've got everything working, thanks to this tutorial - but I'd like to make one enhancement. Currently when the user presses submit the data is stored in wordpress and they are then redirected to a fixed URL of my choosing. Rather than this I would like to simply clear the form data and display a confirmation message - I guess via AJAX? I know there are built in AJAX capabilities in wordpress, but I've never really used it. Can anyone help me out?
The part of the code that submits the data to Wordpress and provides the URL to be redirected is copied below. I assume I wil need to make a change here?
$post_id = wp_insert_post($post_information);
if($post_id)
{
wp_redirect( '/thanks' );
exit;
}
You could simply redirect to the current page with get_permalink():
if ( $post_id )
{
wp_safe_redirect( add_query_arg( array( 'thanks' => '1' ), get_permalink() ) );
exit;
}
To display a message in the template, check the query arg:
if( isset( $_GET['thanks'] ) && '1' == $_GET['thanks'] )
echo '<p class="success">Thanks!</p>';
if you need more featuredone means, try this,
http://kvcodes.com/2014/02/front-end-post-submission-wordpress/