No data in response for a ajax action in ZF2 Controller - php

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?

Related

Laravel AJAX put method 405 error

I'm trying to send data through AJAX put method. I don't know what I'm doing wrong.
All code posible code
link
My route file
Route::resource('restaurant', 'RestaurantController');
RestaurantController
public function update(Request $request, $id)
{
$rules = array (
'address_id' => 'required|alpha',
'name' => 'required|alpha',
'description' => 'required',
'phone' => 'required',
'email' => 'required|email',
'homemade' => 'required'
);
$validator = Validator::make ( Input::all (), $rules );
if ($validator->fails ())
return Response::json ( array (
'errors' => $validator->getMessageBag ()->toArray ()
) );
else {
$items = Restaurant::find ($id);
$items->address_id = ($request->address_id);
$items->name = ($request->name);
$items->description = ($request->description);
$items->phone = ($request->phone);
$items->email = ($request->email);
$items->homemade = ($request->homemade);
$items->save ();
return response ()->json ( $items );
}
}
ajax request
$('.modal-footer').on('click', '.edit', function() {
$.ajax({
type: 'PUT',
url: '/restaurant',
data: {
'_token': $('input[name=_token]').val(),
'id': $("#fid").val(),
'address_id': $('#address_id').val(),
'name': $('#name').val(),
'description': $('#description').val(),
'phone': $('#phone').val(),
'email': $('#email').val(),
'homemade': $('#homemade').val(),
'lat': $('#lat').val(),
'lng': $('#lng').val(),
'bank_name': $('#bank_name').val(),
'bank_code': $('#bank_code').val(),
'paypal_email': $('#paypal_email').val(),
'paypal_merchantname': $('#paypal_merchantname').val(),
'zipcode': $('#zipcode').val(),
'easypeisa': $('#easypeisa').val(),
'cod': $('#cod').val()
},
success: function(data) {
if (data.errors){
$('#myModal').modal('show');
if(data.errors.address_id) {
$('.address_id_error').removeClass('hidden');
$('.address_id_error').text("address_id name can't be empty !");
}
if(data.errors.name) {
$('.name_error').removeClass('hidden');
$('.name_error').text("name can't be empty !");
}
if(data.errors.description) {
$('.description_error').removeClass('hidden');
$('.description_error').text("description must be a valid one !");
}

Cakephp form pass upload file to controller via ajax

I have a form which is created using cakephp form builder, this form has a couple of file upload fields as below:
<?php echo $this->Form->create('application', array('type' => 'file', 'url' => array('app' => true, 'controller' => 'jobs', 'action' => 'save_new_application'), 'id' => 'create-application-form'));
echo '<p>'.$this->Form->input('cv', array('type' => 'file', 'label' => "Upload CV (Required)", 'required' => true)).'</p>';
echo '<p>'.$this->Form->input('cover-letter', array('type' => 'file', 'label' => "Upload Cover Letter (optional)")).'</p>';
echo $this->Form->input('campaignid', array('type' => 'hidden', 'class' => 'form-control sendid', 'label' => false, 'value' => $campaignid));
echo $this->Form->input('profileid', array('type' => 'hidden', 'class' => 'form-control sendid', 'label' => false, 'value' => $profileid));
echo $this->Form->submit('Apply', array('class' => 'form-control')); ?>
<?php echo $this->Form->end(); ?>
I however need this form to be submitted via ajax so that the page doesnt refresh, as with other forms on the site I have the below jquery, however the controller only gets the two hidden fields and no information about the upload files.
$('#create-application-form').off().on('submit', function(e){
e.preventDefault();
$.ajax({
url: '/app/jobs/save_new_application/',
dataType: 'json',
method: 'post',
data: $(this).serialize()
})
.done(function(response) {
//show result
if (response.status == 'OK') {
} else if (response.status == 'FAIL') {
} else {
//show default message
}
})
.fail(function(jqXHR) {
if (jqXHR.status == 403) {
window.location = '/';
} else {
console.log(jqXHR);
}
});
});
What do i need to change in the ajax call to be able to pass the actual file data to the controller so the files can be saved on the server?
You have to send New FormData() object to send file using ajax
Updated code
$('#create-application-form').off().on('submit', function(e){
e.preventDefault();
var formdatas = new FormData($('#create-application-form')[0]);
$.ajax({
url: '/app/jobs/save_new_application/',
dataType: 'json',
method: 'post',
data: formdatas,
contentType: false,
processData: false
})
.done(function(response) {
//show result
if (response.status == 'OK') {
} else if (response.status == 'FAIL') {
} else {
//show default message
}
})
.fail(function(jqXHR) {
if (jqXHR.status == 403) {
window.location = '/';
} else {
console.log(jqXHR);
}
});
});

Display Zend Form Validation error in Ajax

There is a Zend Registration Form. Having as input username, email, password and confirm password. Validator for email is following:
$this->add(array(
'name' => 'email_reg',
'required' => true,
'filters' => array(
array(
'name' => 'StripTags',
),
array(
'name' => 'StringTrim',
),
),
'validators' => array(
array(
'name' => 'EmailAddress',
'options' => array(
'domain' => true,
'messages' => array(
\Zend\Validator\EmailAddress::INVALID_FORMAT => 'Email address format is invalid'
),
),
),
array(
'name' => 'Db\NoRecordExists',
'options' => array(
'table' => 'user',
'field' => 'email',
'adapter' => $sm->get ( 'Zend\Db\Adapter\Adapter' ),
'messages' => array(
NoRecordExists::ERROR_RECORD_FOUND => 'E-mail address already exists'
),
),
),
),
));
There are 4 validators: Required Type, e-amil format and if there is someone with following e-mail in database.
Error messages will be:
- E-mail is required
- Email address format is invalid
- E-mail address already exists
Problem Trying to catch error messages and output using ajax. In RegisterController having following function:
public function ajaxAction()
{
if (!$this->request->isPost()) {
return $this->redirect()->toRoute(NULL,
array( 'controller' => 'index'
)
);
}
$form = $this->getServiceLocator()->get('RegisterForm');
$form->setInputFilter(new RegisterFilter($this->getServiceLocator()));
$post = $this->request->getPost();
$form->setData($post);
$response = $this->getResponse();
$hello = 1;
if (!$form->isValid()){
// email is invalid; print the reasons
$json= $form->getMessages();
$response->setContent(\Zend\Json\Json::encode($json));
}
return $response;
}
And jQuery file:
$( document ).ready(function() {
var urlform = "register/ajax";
$("#btnRegister").click( function() {
$("#Register").submit( function() {
return false;
});
$.ajax({
url: urlform,
type: 'POST',
dataType: 'json',
async: true,
data: $(".form-signin").serialize(),
success: function (data) {
$("#rCheck").text(data);
console.log(data);
},
error: function (data) {
$("#rCheck").text(data);
console.log(data);
}
});
});
});
In Console i got something like this https://imagizer.imageshack.us/v2/558x205q90/661/uC09Da.png and in div with id #rCheck getting [Object][Object].
From the image you provided the error messages are correctly returned. The error is that you are trying to write directly an Object into your div.
You should have seached how to read an object with JavaScript. Try with this code :
success: function (data) {
data.forEach(function(datum) {
Object.keys(datum).forEach(function (key) {
$('<p>'+obj[key]+'</p>').appendTo('#rCheck');
});
});
console.log(data);
},
Or you may also do that within your ajaxAction :
$messages = array();
$errors = $form->getMessages();
foreach($errors as $key=>$row)
{
if (!empty($row) && $key != 'submit') {
foreach($row as $keyer => $rower)
{
$messages[$key][] = $rower;
}
}
}
if (!empty($messages)){
$response->setContent(\Zend\Json\Json::encode($messages));
}
return $response;
Here's is a good post on how to use Zend\Form with Ajax validation.

How to save data using ajax request using CGridview in Yii

When I submit button to update it does not save the data.Here in my view.php file ->
`
'id'=>'main-table-grid',
'dataProvider'=>$dataProvider,
'columns'=>array(
array(
'name'=>'section_no',
'type'=>'raw',
'value'=>'CHtml::link($data->section_no)',
),
'section_name',
'sub_sec_no',
'sub_sec_name',
array(
'name'=>'text',
'htmlOptions'=>array('width'=>'150'),
'type'=>'raw',
'value' => 'CHtml::textArea("MainTable[text]",$data->text)',
),
'review_response',
array(
'name'=>'review_comment',
'htmlOptions'=>array('width'=>'default'),
'type'=>'raw',
'value' => 'CHtml::textArea("MainTable[review_comment]",$data->review_comment)',
),
array(
'class' => 'CButtonColumn',
'template' => '{update}{view}{delete}',
'buttons' => array(
'update' => array(
'options' => array('class' => 'save-ajax-button'),
'url' => 'Yii::app()->controller->createUrl("saveModel", array("id"=>$data->id))',
),
'view',
'delete',
),
),
),
));
?>
<script>
$('#main-table-grid a.save-ajax-button').live('click', function(e)
{
var row = $(this).parent().parent();
var data = $('input', row).serializeObject();
$.ajax({
type: 'POST',
data: data,
url: jQuery(this).attr('href'),
success: function(data, textStatus, jqXHR) {
console.log(text);
console.log(textStatus);
console.log(jqXHR);
},
error: function(textStatus, errorThrown) {
console.log(textStatus);
console.log(errorThrown);
}
});
return false;
});
$.fn.serializeObject = function() {
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
</script>`
and in my controller I created an action method.The code is below->
public function actionSaveModel($id) {
$model=$this->loadModel($id);
$this->performAjaxValidation($model);
if(isset($_POST['MainTable']))
{
$model = new MainTable();
$model->attributes = $_POST['MainTable'];
$model->save();
$this->render('admin', array(
'model' => $model,
));
}
}
I have set permission in my controller
array('allow', // allow authenticated user to perform 'create' and 'update' actions
'actions'=>array('savemodel'),
'users'=>array('#'),
),
My problem is data is not saving in the table.Please let me know what is the issue here.
Thank you.
Ok now I have solved the issue.I am getting ajax response by selecting the ID which I need to update and post the data to my controller.
<script type="text/javascript">
$(function() {
$('#MainTable_text').live('click', function(e)
{
var val=this.value;
$.ajax({
type: 'POST',
data: {des:val},
url: "<?php echo $this->createUrl("maintable/save"); ?>",
success: function(data, textStatus, jqXHR) {
console.log(data);
console.log(textStatus);
console.log(jqXHR);
},
error: function(textStatus, errorThrown) {
console.log(textStatus);
console.log(errorThrown);
}
});
return false;
});
});
after that I catch the value in controller and update in database.
public function actionSave() {
$command = Yii::app()->db->createCommand();
$user = $_POST['des'];
if (isset($user)) {
$command->update('main_table', array(
'text' => $user,
), 'id=:id', array(':id' => $id));
$this->render('save', array(
'model' => $model,
));
} else {
echo 'error found';
}
}
Please put your jQuery code inside this code:
<script type="text/javascript">
$(function() {
// put your jQuery code here
});
</script>

How to reload Zend Captcha image on click refresh button?

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>

Categories