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);
}
});
});
Related
I am submitting a form and AJAX is displaying errors as it should but when everything goes right, it means that when form values are saving in database correctly AJAX is not triggering the success function.
Here's the Laravel product verification code:
public function productVerify(Request $request)
{
$val = $request->validate
(
[
'name' => 'required',
's_description' => 'required',
'l_description' => 'required',
'image_src' => 'required|mimes:jpg,png,jpeg',
'category' => 'required',
'quantity' => 'required|integer|not_in:0|regex:^[1-9][0-9]+^',
'price' => 'required|integer|not_in:0|regex:^[1-9][0-9]+^',
],
[
'required' => 'The :attribute field is required',
'mimes' => 'Image should be a JPG, JPEG, or PNG',
'integer' => 'The :attribute field should be an integer.',
's_descripton.required' => 'The short description is required',
'l_descripton.required' => 'The long description is required',
'image_src.required' => 'The image file is required.'
]
);
if (!$val)
{
return response()->json(['errors']);
}
else
{
return response()->json(['success' => 'Product Added Successfully']);
}
}
Here's the AJAX code:
$(document).ready(function()
{
$("#addForm").submit(function(event)
{
// Store all data from form as object;
var formData = new FormData(this);
$.ajaxSetup({
headers:
{
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
// AJAX implementation error:function() return errors without page reload.
$.ajax(
{
url: '/save_product',
type: "POST",
processData:false,
contentType:false,
cache:false,
dataType: 'json',
data:formData,
success: function(xhr)
{
responseSu = xhr.responseJSON.success;
alert(responseSu);
},
error:function(xhr, status, error)
{
// Errors from the XML Http Request JSON Response
responseER = xhr.responseJSON.errors;
// console.log(responseER);
$("#error").html(" ");
// For Each loop for printing errors from the response
$.each(responseER, function (key, item)
{
console.log(item);
$("#error").append("<li class='text-danger'>"+item+"</li>")
// Hide Errors after 15 seconds with a fadeout animation
$("#error").show().delay(15000).fadeOut();
});
}
});
// Stop form from submitting normally
event.preventDefault();
});
});
After the form is submitted successfully and data is inserted into database it gives the error:
I am trying to save image as a base64 into database. But when I submit form I am getting the image NULL. I couldn't understand what's wrong.
VIEW:
<div class="content">
<?php $form = ActiveForm::begin([
'id' => 'products-add-form',
'action' => ['products/product-add-form'],
'method' => 'post',
'options' => [
'class' => 'products-tbl-style',
'enctype' => 'multipart/form-data',
]
]); ?>
<?= $form->field($model, 'productName'); ?>
<?= $form->field($model, 'cost'); ?>
<?= $form->field($model, 'available')->dropDownList(['Y' => 'Yes', 'N' => 'No']); ?>
<?= $form->field($model, 'image')->fileInput(['class'=>'btn btn-primary']); ?>
<?= Html::submitButton('Save', ['class'=>'btn btn-success products-save-btn']); ?>
<?php ActiveForm::end(); ?>
</div>
Controller:
if($model->load(Yii::$app->request->post())){
$file = UploadedFile::getInstance($model,'image');
var_dump($file->name);
var_dump($file);
var_dump($_FILES);
}
Model:
public function rules()
{
return [
[['productName', 'cost', 'available', 'image'], 'required'],
[['cost'], 'number'],
[['available'], 'string', 'max' => 1],
[['image'], 'string'],
[['productName'], 'string', 'max' => 100]
];
}
Here my JQuery code, I am submitting the form data via ajax, does it cause a problem?
JS:
$("form#products-add-form").on('beforeSubmit', function(e){
var form = $(this);
$.post(
form.attr('action'),
form.serialize()
)
.done(function(result){
if(result == 1){
form.trigger("reset");
$.pjax.reload({container:'#products-table'});
$.notify({
icon: "pe-7s-check",
message: "New product is added"
},{
type: type[2],
timer: 10,
placement: {
from: 'top',
align: 'right'
}
});
}
else {
alert(result);
}
}).fail(function(){
console.log("server error");
});
return false;
});
To send files via AJAX you shoud use FormData. To construct a FormData object that contains the data from an existing <form>, specify that form element when creating the FormData object:
$("form#products-add-form").on('beforeSubmit', function(e){
$.post(
form.attr('action'),
new FormData(this) /* this is a form object */
)
/* your other code here */
});
UPD: As TS mentioned it should be processData set to false. It's impossible to set it for $.post, so we need to use $.ajax
I have tried following :
$.ajax( {
url: 'http://host.com/action/',
type: 'POST',
data: new FormData( this ),
processData: false,
contentType: false
} );
e.preventDefault();
And now it's working, as #SiZE wrote, we need to send file input with FormData() via ajax.
You can try to use FileInput widget it work's perfectly.
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 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.
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>