Codeigniter Callback functions for file validations are not working - codeigniter

I've created validation rules for image uploading as follows.
$this->form_validation->set_rules('display_photo', 'Display Photo', 'callback_file_required|callback_file_size_max[1000]');
In controller I've included callback function as follows.
public function file_required($display_photo) {
if($_FILES[$display_photo]['size'] == 0) {
$this->form_validation->set_message('file_required', 'Upload a file.');
return false;
}
return true;
}
public function file_size_max($display_photo, $max_size) {
if($_FILES[$display_photo]['size'] > $max_size) {
$this->form_validation->set_message('file_size_max', 'This file exceeds max size.');
return false;
}
return true;
}
Only first rule is executing but not second rule. Please help me to find out the solution.

You should pass the file size limit in the config not in the validation rule.
Can u please paste the function or method that performs the upload ?

Not sure if you can use two callbacks on a single field when validation forms in CI. In any case you don't need to check the size to see if a file was uploaded. Use error code '4'
Solutions:
Check if the file was uploaded with if($_FILES[$display_photo]['error'] !== 4) // Error code 4 means no file was uploaded. So if it's not 4 then you have a file.
If you want to do multiple checks you can put them both in one single callback

$this->form_validation->set_rules('display_photo', 'Display Photo', 'callback_file_required_with_validation');
public function file_required_with_validation($display_photo) {
$max_size=1000;
if($_FILES[$display_photo]['size'] == 0) {
$this->form_validation->set_message('file_required', 'Upload a file.');
return false;
}
if($_FILES[$display_photo]['size'] > $max_size) {
$this->form_validation->set_message('file_size_max', 'This file exceeds max size.');
return false;
}
return true;
}

Pretty sure you need double underscore after 'callback' in your validation definition...
$this->form_validation->set_rules('display_photo', 'Display Photo', 'callback__file_required|callback__file_size_max[1000]');

One way - You can validate with JS before uploading the file:
<form method="post" enctype="multipart/form-data" action="upload.php">
<input type="file" name="file" id="file" />
<input type="submit" name="submit" value="Submit" />
</form>
<script>
document.forms[0].addEventListener('submit', function( evt ) {
var file = document.getElementById('file').files[0];
if(file && file.size < 10485760) { // 10 MB (this size is in bytes)
//Submit form
} else {
//Prevent default and display error
evt.preventDefault();
}
}, false);
</script>
Original Question is here
But if you want validate at server side, then server until does't know whenever we upload the file.

Related

How to check user url back redirection in laravel?

I want to check if user redirect back to certain url in laravel ?
can anyone have any idea how to get it ?
like this below for example ?
if(redirect()->back()){
//
}
You can detect this with session parameter.
For example;
public function my_function() {
//your codes here
if($success) {
return redirect()->route('homepage')->with('back', '0');
} else {
return back()->with('back', '1');
}
}
Then you can control on your page with 'session()'.
For example;
views > login.blade.php
#if(session('back') and session('back') == 1)
You are return back!
#else
Welcome, you are here first time.
#endif
And if you want to send this information on a form you can use this;
<form>
<!-- your other input -->
<input type="hidden" name="back" value="{{session('back')}}">
</form>

Inline javascript is getting stripped off from the AJAX response by Prototype JS Ajax.Request method

I am working on a Magento store trying to code a widget's javascript layer with the help of Prototype js framework.
In my grid.js file AJAX call is setup like that:
loadTabContent: function(tab, tabType){
if(tab === undefined || tabType === undefined){
return this;
}
entityId = tab.id.split('-')[3];
request = new Ajax.Request(
this.tabContentLoadUrl,
{
method:'get',
onSuccess: this.onTabContentLoad.bind(tab),
onFailure: this.ajaxFailure.bind(this),
evalJS: true,
parameters: {
id: entityId,
type: tabType
}
}
);
}
Below is the success handler:
onTabContentLoad: function(transport){
if(transport && typeof transport.responseText !== undefined){
try{
response = transport.responseText;
}catch (e) {
console.log('PARSE ERROR', e);
response = {};
}
entityId = this.id.split('-')[3];
tabType = this.id.split('-')[1];
if(response && $('tab-' + tabType + '-' + entityId + '-contents')){
$('tab-' + tabType + '-' + entityId + '-contents').update(response);
}
}
},
The content for the div is getting updated correctly by the AJAX call but there is some inline JS in response which is not working.
I can't even see that javascript snippet in Elements tab(chrome developer tool)
Below is the code that handles the AJAX request on server side:
public function renderTabContentAction()
{
$entityId = Mage::app()->getRequest()->getParam('id');
if( ! $entityId){
$this->getResponse()->setHeader('HTTP/1.0', '400', true);
$this->getResponse()->setBody('Invalid parameters provided.');
}
$tabType = Mage::app()->getRequest()->getParam('type');
if( ! $tabType){
$this->getResponse()->setHeader('HTTP/1.0', '400', true);
$this->getResponse()->setBody('Invalid parameters provided.');
}
Mage::register('current_entity_id', $entityId);
Mage::register('current_tab_type', $tabType);
$tabHtml = $this->_getTabsHtml($entityId, $tabType);
$this->getResponse()->setHeader('HTTP/1.0', '200', true);
$this->getResponse()->setBody($tabHtml);
}
Below is the response that gets passed to onTabContentLoad AJAX handler:
<div class="vertical-tabs">
<div class="tabs">
<div class="tab" id="tab-vertical-137-2441">
<input type="radio" id="label-vertical-product-tab-137-2441" name="product-tab-group-137">
<label class="tabs-label" for="label-vertical-product-tab-137-2441">PG-10ml</label>
<div class="content" id="tab-vertical-137-2441-contents">
</div>
</div>
<div class="tab" id="tab-vertical-137-2442">
<input type="radio" id="label-vertical-product-tab-137-2442" name="product-tab-group-137">
<label class="tabs-label" for="label-vertical-product-tab-137-2442">PG-15ml</label>
<div class="content" id="tab-vertical-137-2442-contents">
</div>
</div>
</div>
</div>
<script type="text/javascript">
bulkOrderGrid.initVerticalTabs();
bulkOrderGrid.activateTab('2441', 'VERTICAL');
</script>
You can see that the SCRIPT tags are there in the response. Its just when the content gets updated using Element.update function it strips off the SCRIPT tags. That's what I can understand so far.
NOTE:
I have also used Ajax.Updater along with evalScripts:true and Ajax.Request along with evalJS:true.
Got stuck here. Any help would be much appreciated.
UPDATES:
Since I am using Element.update function to refresh the section. The source of the problem is this part of the code in prototype.js around line no. 2048. I can see its getting executed in js debugger. It does evaluates the js code but also removes the SCRIPT tags from the source. Commenting out stripScripts works fine.
else {
element.innerHTML = content.stripScripts();
}
content.evalScripts.bind(content).defer();
I think your problem is that
the Ajax response is passed through String#evalScripts() but the context is not the global context so instead of your script block do this
<script type="text/javascript">
window.bulkOrderGrid.initVerticalTabs();
window.bulkOrderGrid.activateTab('2441', 'VERTICAL');
</script>
if that doesnt fix it - than you can directly run transport.responseText.evalScripts() but you still need the window. in your script block to resolve the scope of the variables.
You are correct Element.update() remove script tag. you should use
Element.innerHTML

Saving the page state after choosing filters

I have some filters on a web page (checkboxes) and I modify the result list by ajax POST method. Is there a way that somehow I save the page state and send the URL link to someone so they open it in that state? Any help is appreciated.
By the way I'm using Laravel.
You can use parameters :
test.com/page?checkbox1=checked&checkbox2=checked
In your Laravel controller you can do this :
public function page($request) {
$checkboxes = array();
if ($request->has('checkbox1')) {
$checkboxes[] = true;
}
if ($request->has('checkbox2')) {
$checkboxes[] = true;
}
// ... and so on.
return view('page', compact('checkboxes'));
}
And set your php page like this :
<input type="checkbox" <?php checkboxes[$i++] ? 'checked' : '' ?> >
You can set the checkbox as parameter in the URL, and when the user go to your address, check if there is any of your params.
if so - set the checkboxes as you wish
just to get the general idea..
function getUrlParams(requested_param){
//check for params
return result;
}
if (getUrlParams(myCheckBox)){
$('#checkbox_on_page').prop( "checked", true );
}

ColdFusion ajax validation

in cf9 i have a page where i want to check if field value exist in db (via ajax). If it doesn't exist, i want to stop processing (return false). Everything works fine, except i don't know how to pass back to the main function the result of the ajax call
please help
<cfajaximport tags="cfmessagebox, cfwindow, cfajaxproxy">
<cfajaxproxy cfc="reqfunc" jsclassname="jsobj" />
<script language="JavaScript">
function checkRequired() {
var testVal = document.getElementById('myField').value;
return testAjax(testVal);
/* more processing that should stop if ajaxCallBack returns false */
}
function testAjax(testVal) {
var instance = new jsobj();
instance.setCallbackHandler(ajaxCallBack);
instance.checkProfile(testVal);
}
function ajaxCallBack(returns) {
alert(returns);
// returns correctly "true" if value checks against db, "false" if it doesn't
// HOW DO I PASS THIS VALUE BACK TO checkRequired ???
}
</script>
<form>
<input type="text" name="myField" id="myField" value=""><p>
<input type="button" value="Check with Ajax" onClick="return checkRequired()">
</form>
many thanks
Unless you build your main function to 'wait' for the return, you can't return your result to that instance of the function; it has already exited, so to speak. Using cfajax it is probably possible to tweak the main function to call and wait, but the simple solution is to have the callback subsequently recall your main function and treat the existence of the result/return as the flag as to whether to process or call the ajax.
function checkRequired(return) {
if(return != null) {
/* more processing */
} else {
testAjax(testVal);
}
}
function ajaxCB(return) {
checkRequired(return);
}
I would probably refactor a bit more but you should get the idea.
it's really kind of a hack, not what i was looking for, but for what it's worth: if i put this stanza at the very end of my function, with the callBack collapsed within the main function, it would work
function checkRequired() {
var testVal = document.getElementById('myField').value;
var instance = new jsobj();
var r = instance.setCallbackHandler(
function(returns) {
if(returns == 1) {
document.getElementById('testForm').submit();
} else { alert("Something wrong"); }
}
);
instance.checkProfile(testVal);
}

Validation using Html.Telerik().Upload() with MVC3

I am looking for sample code that would show how to set validation on the Html.Telerik().Upload() function so that the user can only upload .jpg files. I'd like to support just .jpg files.
Does anyone have any good examples or websites that I could use?
Unfortunately, filtering the extensions is not possible using Html.Telerik().Upload() due to the way browsers implement the <input type="file" />.
Source:
http://www.telerik.com/community/forums/aspnet-ajax/upload/how-to-filter-out-unwanted-file-types-radupload.aspx
But, there is an alternative to do that with html and javascript:
HTML
<input name="fileToUpload" type="file" onchange="check_file()" >
javascript
function check_file(){
str=document.getElementById('fileToUpload').value.toUpperCase();
suffix=".JPG";
suffix2=".JPEG";
if(!(str.indexOf(suffix, str.length - suffix.length) !== -1||
str.indexOf(suffix2, str.length - suffix2.length) !== -1)){
alert('File type not allowed,\nAllowed file: *.jpg,*.jpeg');
document.getElementById('fileToUpload').value='';
}
}
Source: https://stackoverflow.com/a/6788623/1304064
Please see the following Code. This code only accept jpeg/jpg, png format image. Also image size is restricted to 100KB.
#(Html.Telerik().Upload()
.Name("EmployeeImageUpload")
.Multiple(false)
.Async(async => async
.Save("SaveEmployeeImage", "Employee")
.AutoUpload(false)
)
.ClientEvents(events => events
.OnLoad("onLoad")
.OnSelect("onSelect")
.OnSuccess("onSuccess")
)
)
<script type="text/javascript">
function onLoad(e) {
$(this).find("input").attr("accept", "image\/jpeg,image\/jpg,image\/png");
}
function onSelect(e) {
if (e.files[0].size > 102400) {
alert('Image Size Should Be <= 100KB');
e.preventDefault();
return false;
}
var ext =e.files[0].extension.toLowerCase();
if ($.inArray(ext, ['.jpeg', '.jpg', '.png']) == -1) {
alert('Only Supported Extension are jpeg/jpg, png');
e.preventDefault();
return false;
}
return true;
}
</script>

Resources