I apply a zend captcha in my php page now i require to add captcha reload button. Please give answer according to zend.
Just two quick snippets but I think you will get the idea. Adjust the element name and the selectors for your needs.
In your controller add a method to generate a fresh captcha
public function refreshAction()
{
$form = new Form_Contact();
$captcha = $form->getElement('captcha')->getCaptcha();
$data = array();
$data['id'] = $captcha->generate();
$data['src'] = $captcha->getImgUrl() .
$captcha->getId() .
$captcha->getSuffix();
$this->_helper->json($data);
}
In your view script (I'm using mootools for the ajax-request)
document.addEvent('domready', function() {
$$('#contactForm img').addEvent('click', function() {
var jsonRequest = new Request.JSON({
url: "<?= $this->url(array('controller' => 'contact', 'action' => 'refresh'), 'default', false) ?>",
onSuccess: function(captcha) {
$('captcha-id').set('value', captcha.id);
$$('#contactForm img').set('src', captcha.src);
}
}).get();
});
});
Edit: Added pahan's jquery
$(document).ready(function() {
$('#refreshcaptcha').click(function() {
$.ajax({
url: '/contact/refresh',
dataType:'json',
success: function(data) {
$('#contactForm img').attr('src', data.src);
$('#captcha-id').attr('value', data.id);
}
});
});
});
#user236501 Actually it can be any type of Zend Form Element (for example Button). You're even able to put clickable refresh link as Zend_Form_Element_Captcha description option like this:
$captcha = new Zend_Form_Element_Captcha('captcha', array(
'label' => 'Some text...',
'captcha' => array(
'captcha' => 'Image',
'wordLen' => 6,
'timeout' => 300,
'font' => './fonts/Arial.ttf',
'imgDir' => './captcha/',
'imgUrl' => 'http://some_host/captcha/'
),
'description' => '<div id="refreshcaptcha">Refresh Captcha Image</div>'
));
but in that case Description decorator's options should be modified, for example:
$this->getElement('captcha')->getDecorator('Description')->setOptions(array(
'escape' => false,
'style' => 'cursor: pointer; color: #ED1C24',
'tag' => 'div'
));
It can be done in form's init() method.
Sorry for my english. Btw I'm not sure if I put my comment in the right place ;)
#Benjamin Cremer
thanks for the code, works like charm :)
after reading this
I did it using jquery.
$(document).ready(function() {
$('#refreshcaptcha').click(function() {
$.ajax({
url: '/contact/refresh',
dataType:'json',
success: function(data) {
$('#contactForm img').attr('src',data.src);
$('#captcha-id').attr('value',data.id);
}
});
});
});
In config/autoload/global.php add the following
'view_manager' => array(
'strategies' => array(
'ViewJsonStrategy','Zend\View\Strategy\PhpRendererStrategy'
),
),
in YourModule/src/YourModule create a new folder Ajax
Inside Yourmodule/Ajax create a file AjaxController.php
namespace YourModule\Ajax;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\JsonModel;
use YourModule\Forms\SignupForm;
class AjaxController extends AbstractActionController
{
public function refreshSignupCaptchaAction(){
$form = new SignupForm();
$captcha = $form->get('captcha')->getCaptcha();
$data = array();
$data['id'] = $captcha->generate();
$data['src'] = $captcha->getImgUrl().$captcha->getId().$captcha->getSuffix();
return new JsonModel($data);
}
}
Add route inside module.config.php
'yourmodule-ajax' =>array(
'type' => 'segment',
'options' => array(
'route' => '/yourmodule/ajax/:action',
'constraints' => array(
'action' => '\w+',
),
'defaults' => array(
'controller' => 'YourModule\Ajax\AjaxController',
)
),
),
last in your template, I assume you are using jquery
<div class="form-group">
<div id="captcha" class="control-group <?php echo count($form->get('captcha')->getMessages()) > 0 ? 'has-error' : '' ?>">
<?php echo $this->formLabel($form->get('captcha')); ?>
<div class="col-xs-12 col-sm-6">
<a id="refreshcaptcha" class="btn btn-default pull-right">Refresh</a>
<?php echo $this->formElement($form->get('captcha')); ?>
<?php echo $this->formElementErrors($form->get('captcha')); ?>
</div>
</div>
</div>
<script type="text/javascript">
$(function(){
$('#refreshcaptcha').click(function() {
$.ajax({
url: '<?php echo $this->url('yourmodule-ajax', array('action'=>'refreshSignupCaptcha')) ?>',
dataType:'json',
success: function(data) {
$('#captcha img').attr('src', data.src);
$('#captcha input[type="hidden"]').attr('value', data.id);
$('#captcha input[type="text"]').focus();
}
});
return false;
});
});
</script>
Related
The problem is that I don't have data in controller, in filterAction function.
I can see in firebug at Post:
Source: daterange=2015%2F10%2F22+-+2015%2F10%2F22
at Response:
{"daterange":null,"submit":null}
In the response at daterange I want to be the date range which I introduced in interface.
Here is the ajax call
<script type="text/javascript">
$(function(){
$('#incidents').bind("submit",function(event) {
event.preventDefault();
var urlform = '<?php echo $this->url('incidents', array('controller'=>'IncidentsController', 'action'=>'filter')); ?>';
$.ajax({
url: urlform,
type: 'POST',
dataType: 'json',
contentType: "application/json; charset=utf-8",
async: true,
data: ($("#incidents").serialize()),
success: function (data) {
console.log(data);
},
error: function (data) {
console.log(data);
}
});
})
})
</script>
Here's the Form:
<?php
namespace Incidents\Form;
use Zend\Form\Form;
class IncidentsForm extends Form
{
public function __construct($name = null)
{
// we want to ignore the name passed
parent::__construct('incidents');
$this->setAttribute('method', 'post');
$this->add(array(
'type' => 'text',
'name' => 'daterange',
'options' => array(
'label' => 'Start Time'
),
));
$this->add(array(
'name' => 'submit',
'type' => 'Submit',
'attributes' => array(
'value' => 'Filter',
'id' => 'submitbutton',
),
));
}
}
Here is the filterAction() on the controller:
public function filterAction()
{
$form = new IncidentsForm();
$request = $this->getRequest();
$response = $this->getResponse();
if ($request->isPost()){
$form->setData($request->getPost());
if ($form->isValid()) {
$formData = $form->getData();
}
}
return $response->setContent(\Zend\Json\Json::encode($formData));
}
I'm expecting that in $formData to have the date range which I selected in interface from the daterangepicker control.
Can some one help me, plese?
i have been trying to submit a jquery mobile form using ajax in cakephp but the form does not submit, i don't know what could be wrong, here is my controller code:
public function add() {
if ($this->request->is('ajax')) {
$this->request->data['Room']['user_id'] = $this->Session->read('Auth.User.id');
$this->Room->User->updateAll(array("User.room_count"=>'User.room_count+1'),array('User.id'=> $this->Session->read('Auth.User.id') ));
$this->Room->create();
if ($this->Room->save($this->request->data)) {
$this->Session->setFlash(__('The room has been saved.'));
$this->render('AjaxRoom','ajax');
} else {
$this->render('AjaxRoom','ajax');
}
}
$users = $this->Room->User->find('list');
$this->set(compact('users'));
}
and here is my view code:
<div id="sent" style="display:none;">Updating...</div>
<div id="success"></div>
<script type="text/javascript">
//<![CDATA[
$(document).ready(function () {
$("#RoomIndexForm").bind("submit", function (event) {
$.ajax({
async:true,
beforeSend:function (XMLHttpRequest) {$("#sent").show(500)},
complete:function (XMLHttpRequest, textStatus) {$("#sent").hide(500);$("#TalkViewForm").each (function(){this.reset();});
//$("#refresh").load(location.href + " #refresh");
},
data:$("#RoomIndexForm").serialize(),
dataType:"html",
success:function (data, textStatus) { //$("#success").html(data);
},
type:"POST",
url: "<?php echo $this->Html->url(array('controller' => 'rooms', 'action' => 'add')); ?>"});
return false;
});
});
//]]>
</script>
<div data-role="popup" id="popupRoom" data-theme="a" class="ui-corner- all">
<?php echo $this->Form->create('Room',array('role'=>'form','url'=>array('controller'=>'r ooms', 'action'=>'add'))); ?>
<div style="padding:10px 20px;">
<h3>Add Room</h3>
<?php echo $this->Form->input('name', array(
'label' => false,
'placeholder'=>'Room Name'));
?>
<?php
echo $this->Form->input('description', array(
'label' => false,
'type' => 'textarea',
'maxlength'=>"140",
'placeholder'=>'Describe Your room briefly.'));
?>
<?php
$accountValues = array();
foreach ($categories as $key => $value) {
$accountValues[$value] = $value;
}
$categories = $accountValues;
echo $this->Form->select('category',array(
'options' =>$categories), array(
'label' => false,
'empty' => false
));
?>
<?php
//echo $this->Form->input('filename', array('type' => 'file','label'=>'Upload an Image'));
//echo $this->Form->input('file_dir', array('type' => 'hidden'));
?>
<?php
echo $this->Form->input('is_private', array(
'label' => 'Do you want a private Room ? If No, just ignore this field.',
'type'=>'checkbox',
));
?>
<?php echo $this->Form->submit('Create',array('class'=>'ui-btn ui-corner-all ui-shadow ui-btn-b ui-btn-icon-left ui-icon-check')); ?>
</div>
<?php echo $this->Form->end(); ?>
</div>
please how do i achieve this functionality? any help is welcomed.
The Html Helper does not support url i think:
$this->Html->url(array('controller' => 'rooms', 'action' => 'add'))
Try to use this instead:
$this->Html->link(['controller' => 'Rooms', 'action' => 'add'])
Another way is the url builder (http://book.cakephp.org/3.0/en/views/helpers/url.html):
$this->Url->build(['controller' => 'Rooms', 'action' => 'add'])
I want use ajax in yii2 (PHP framework)
I use the following code but it does not work.
My view file (PHP):
<script>
var url1='<?php echo Url::toRoute('Agehi/Ajaxshahr'); ?>';
</script>
<?php
$script= <<<JS
function selectshahr()
{
var ost = $("#ostan").val();
$.ajax(
{
type: "post",
url: url1,
data: ost,
cache: false,
success: function(data)
{
alert(data);
}
});
}
JS;
$this->registerJs($script,View::POS_BEGIN);
$form = ActiveForm::begin([
'id' => 'login-form',
'options' => ['class' => 'form-horizontal','enctype'=>'multipart/form-data'],
]);
echo $form->errorSummary($model,['header'=>'لطفا خطاهای زیر را برطرف نمایید','class'=>'']);
echo \vova07\imperavi\Widget::widget([
'selector' => '#content','name'=>'content',
'settings' => [
'lang' => 'fa',
'minHeight' => 200,
'plugins' => [
'clips',
'fullscreen'
]
]
]);
?>
<?= Html::label('استان','ostan',array()) ?>
<?= Html::dropDownList('ostan', null,
ArrayHelper::map($ostan, 'id', 'name'),array('class'=>'form-control','onchange'=>'selectshahr()','id'=>'ostan')) ?>
<?= Html::label('شهرستان/شهر','shahr',array()) ?>
<?= Html::dropDownList('shahr', null,
array(),array('class'=>'form-control')) ?>
and in my controller :
class AgehiController extends \yii\web\Controller
{
public function actionAjaxshahr($ostan)
{
$data = Shahr::findAll('condition', 'osid=' . $_POST['data']);
if(yii::$app->request->isAjax())
{
return $this->renderPartial('_Ajax_shahr', array('data' => $model));
}
return $this->renderPartial('_Ajax_shahr', array('data' => $model));
}
}
Everything seems okay but it does not respond to any request
I checked with Browser developer tools and it saw AJAX as a 404 error
Controller and action names in a route should be lowercase.
I am new to Yii. I have a dropdown list and a CGridView. The idea is that I want to filter the records shown in the gridview based on what the user selects on the dropdown list. I have read several tutorials, and almost all of them are pretty much like this one.
Unfortunately, the code does not seem to fire the gridview update event.
Here is my code based on the tutorial
Controller
public function actionIndex()
{
$criteria = (isset($_GET['id-dropdown'])) ?
array(
'condition' => 'account = ' . $_GET['id-dropdown'],
): array();
$options = array(
'criteria' =>$criteria,
'pagination' => array(
'pagesize' => 100,
),
);
$modelAccount = new Account();
$dataProvider = new CActiveDataProvider('Jurnal', $options);
$selected_account = (isset($_GET['id-dropdown'])) ? $_GET['id-dropdown']: '101'; //101 is the default
$this->render('index', array(
//'modelCustom'=>$modelCustom,
'modelAccount'=>$modelAccount,
'dataProvider'=>$dataProvider,
'selected_account' => $selected_account ));
}
This is my view
<?php
Yii::app()->clientScript->registerScript('items_update', "$('#id-dropdown').change(function(){
alert('ok'); //this works
$.fn.yiiGridView.update('jurnal-grid', {
type:'GET',
data: $(this).serialize(),
success=>
js:function() { $.fn.yiiGridView.update('jurnal-grid');}
}
}
);
});
return false;",
CClientScript::POS_READY);
?>
<h1>View Per Account</h1>
<div class="form">
<?php
$form=$this->beginWidget('CActiveForm', array(
'id'=>'menu-dropdown-form',
'enableAjaxValidation'=>true,
));
echo $form->labelEx($modelAccount, $selected_account);
$criteria = new CDbCriteria();
$criteria->order = 'id ASC';
$account = Account::model()->findAll($criteria);
$accountlist = CHtml::listData($account, 'id', 'description');
echo CHtml::dropDownList('id-dropdown', '$selected_account', $accountlist);
$this->endWidget();
?>
</div>
<?php
$this->widget('zii.widgets.grid.CGridView', array(
'id' => 'jurnal-grid',
'dataProvider'=>$dataProvider,
'columns' => array(
'tanggal',
'account',
array(
'class' => 'CButtonColumn',
),
),
));
?>
Please help me, thank you in advance
Try to replace
success=>
js:function() { $.fn.yiiGridView.update('jurnal-grid');}
with
success=> "$.fn.yiiGridView.update('jurnal-grid');"
No need to use js:function.
Instead of this:
$.fn.yiiGridView.update('jurnal-grid', {
type:'GET',
data: $(this).serialize(),
success=>
js:function() { $.fn.yiiGridView.update('jurnal-grid');}
}
});
Try this:
$.fn.yiiGridView.update('jurnal-grid', {
data: $(this).serialize()
});
Im a beginner in Laravel. I have two login authentication types; using facebook API and using your own email.
Everytime I upload an image when im logging in with my own email, I got this error
{"error":{"type":"Symfony\Component\Debug\Exception\FatalErrorException","message":"Call to a member function create() on a non-object","file":"C:\base_app_folder\app\controllers\OnboardingController.php","line":133}}
But it's success uploading image when im logging in with Facebook API
Here's my Controller :
if (Input::hasFile('profile_pic')) {
$images = ImageUpload::handle(Input::file('profile_pic'));
$mainImage = $images[0];
$time = time();
$mainImageObj = $this->images->create($this->userId, array(
'entity_id' => $this->currentUser->Entity_Id,
'image_url' => $mainImage['image_url'],
'width' => $mainImage['width'],
'height' => $mainImage['height'],
'created_fb' => $time,
'is_original' => $mainImage['is_original'],
'original_id' => null
));
$this->userDetails->update($this->userId, array(
'Profile_Pic_Url' => $mainImageObj->image_url
));
array_shift($images);
Log::info('images = '.print_r($images, true));
$retImage = "";
foreach ($images as $image) {
$this->images->create($this->userId, array(
'entity_id' => $this->currentUser->Entity_Id,
'image_url' => $image['image_url'],
'width' => $image['width'],
'height' => $image['height'],
'created_fb' => $time,
'is_original' => $image['is_original'],
'original_id' => $mainImageObj->image_id
));
if ($image['width'] == 250) {
$retImage = $image['image_url'];
}
}
return Response::json(array(
'success' => true,
'message' => 'Upload succeeded!',
'image_thumbnail_url' => $retImage,
'image_url' => $mainImage['image_url']
));
} else {
App::abort(404);
}
}
Here's my View :
<form action="{{{ route('postEditProfile', array('profile_id' => Session::get('user_id'))) }}}" class="dropzone" id="profile-pic-upload">
<div class="fallback">
<input name="file" type="file" multiple />
</div>
</form>
And here's the javascirpt:
<script type="text/javascript">
$(window).bind("load", function() {
var pic_height = $('.profile_pic').height();
var pic_width = $('.profile_pic').width();
var height_factor = pic_height/240;
var pic_width = pic_width/height_factor;
$('.profile_pic').css('height','240px');
$('.profile_pic').css('width',pic_width+"px");
});
$(document).ready(function () {
$(function () {
$.ajaxSetup({
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
});
});
var routes = {
postEditProfile: "{{{ route('postOnboardingPhotos') }}}"
};
var onboarding = new Onboarding(routes);
});
</script>
Anyone knows how to solve it ? I've searching for the error message but it seems no one ever found this error message.
Did you forget to inject a dependency and assign $this->images to that dependency? Looks like you have an images repository and you forgot to take care of this.