How to save data using ajax request using CGridview in Yii - php

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>

Related

How to pass * as an argument with jQuery to be validated in the Laravel controller?

I've tried passing through using string (teachers_remark.*) from what I searched, but it is not validated in the controller. I expected it to return an error, but it is successfully saved instead.
Need help, I'm a beginner in jQuery.
This is my jQuery:
var students_id = $('#students').val();
var teachers_id = $('#teachers').val();
var teacherArray = $('#my_teachers_remarks input').map(function () {
return {
"value": this.value,
}
}).get();
sessionStorage['teachers'] = JSON.stringify(teacherArray);
var teachers_remark_arr = [];
teachers_remark_arr = sessionStorage['teachers'];
event.preventDefault();
swal({
title: "{{ __('Are you sure?') }}",
text: "{{ __('No further changes allowed.') }}",
icon: "warning",
buttons: true,
dangerMode: true,
})
.then(function(willAssign) {
if (willAssign) {
return axios.post(route('students.report'), {
students: students_id,
teachers: teachers_id,
'teachers_remark.*': teachers_remark_arr,
})
.then(function (response) {
if (response.data.status === 'ERROR'){
swal({
title: "Error",
text: response.data.errors,
icon: "error"
}).then(function(){
location.reload();
});
}
if (response.data.status === 'SUCCESS'){
swal("Success", response.data.message , "success");
}
})
This is my Controller:
$this->validate(
$request,
[
'students' => ['required'],
'teachers' => ['required'],
'teachers_remark.*' => ['required'],
],
[
'students.required' => 'There is no students selected.',
'teachers.required' => 'There is no teachers selected.',
'teachers_remark.*.required' => 'You must include remarks',
]
);

return a view or redirect after ajax request

how i cant redirect o return a view after a ajax request.
i try validate the request and after (if the request are ok) return a view, but this dont work, i try redirect to the new route but dont work too.
this is my controller:
public function searchActivity(Request $request){
$validator = Validator::make($request->all(), [
'search' => 'required',
'date' => 'required_with:search|required|date|date_format:d-m-y|after:yesterday'
]);
if ($validator->fails()){
return response()->json([
'sucess' => false,
'errors' => $validator->errors()->toArray(),
'data' => $request->all()
]);
}else{
$queries = DB::table('activities')->where('name', $request->search)->orWhere('City', $request->search)->paginate(1);
return redirect()->route('ActivitiesResults', ['results' => $queries]);
}
JS code:
function selectDate(){
$(document).ready(function () {
$( "#datepicker" ).datepicker({ dateFormat: 'dd-mm-yy' });
});
}
function searchActivity(event) {
event.preventDefault();
console.log(event);
$.ajax({
type: 'POST',
url: searchRoute,
data: {
search: $('.search').val(),
date: $('#datepicker').val(),
_token: $('#token').val()
},
dataType : "json",
success: function (data) {
if (data.success){
console.log(data)
}else{
console.log(data.errors);
}
}
})
}
thanks for the help!
you need to change your php code
if ($validator->fails()){
return response()->json([
'sucess' => false,
'errors' => $validator->errors()->toArray(),
'data' => $request->all()
]);
}else{
return response()->json([
'sucess' => true,
'what_you_want' => ''
]); }
change your ajax code like this
success: function (data) {
if (data.success){
//console.log(data)
window.location.replace("http://stackoverflow.com");
}else{
console.log(data.errors);
window.location.replace("http://google.com");
}
}
use header("url) or window.location.href="url" in you success funciton.

No data in response for a ajax action in ZF2 Controller

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?

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);
}
});
});

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