Instant search with Ajax and Symfony2 - javascript

I have create a search filter that works nicely without ajax and javascript, but to get the result the user have to click on the search button. I would like to get the result while the user type.
This is what I have done:
Routing.yml
searchFlight:
path: /search_flight
defaults: { _controller: FLYBookingsBundle:Post:searchtabflightResult }
Controller
/**
*
* #Route("/search_flight", name="searchFlight")
* #Method("POST")
*/
public function searchtabflightResultAction(Request $request)
{
$form = $this->createForm(new SearchflightType());
$request->request->get('query');
$form->handleRequest($request);
dump($form);
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('FLYBookingsBundle:Post')->searchflight($form);
if ($request->isXmlHttpRequest()) {
$jsonArray = json_encode(array(
'status' => 'success', 'entities' => $form
));
$response = new Response($jsonArray);
return $response;
}
return $this->render('FLYBookingsBundle:Post:searchtabflightResult.html.twig', array(
'form' => $form->createView(),
'entities' => $entities,
));
}
searchtabflightresult.html.twig
<form id="myForm" action="{{ path ('searchFlight') }}" method="POST">
{{ form_widget(form.from, { 'attr': {'class': 'form-control auto',} }) }}
{{ form_errors(form.from) }}
{{ form_widget(form.to, { 'attr': {'class': 'form-control auto1',} }) }}
{{ form_errors(form.to) }}
{{ form_widget(form.departuredate) }}
{{ form_errors(form.departuredate) }}
{{ form_widget(form.arrivaldate) }}
{{ form_errors(form.arrivaldate) }}
{{ form_widget(form.price) }}
{{ form_errors(form.price) }}
<button style="height: 43px" type="submit" class="full-width icon-check">SEARCH NOW</button>
</form>
<div class="reloadproducts">
<i id="spinner" style="display:none; font-size: 20px" class="fa fa-spinner fa-pulse fa-2x fa-fw"></i>
{% if entities|length != 0 %}
{% for entity in entities %}
{{ entity.from }}
{{ entity.to }}
{{ entity.price|tva(entity.tva.multiplicate) }}
{% if entity.departuredate %}{{ entity.departuredate|date('Y-m-d H:i:s') }}{% endif %}
{% if entity.arrivaldate %}{{ entity.arrivaldate|date('Y-m-d H:i:s') }}
{% endif %}
{% endfor %}
{% else %}
<h1 style="color: #707070">The product you loking for doesn't exist</h1>
{% endif %}
</div>
.
<script>
$(document).ready(function() {
$("#myForm").submit(function(e) {
$('#spinner').show();
e.preventDefault();
var $form = $('#myForm');
$.ajax({
type: "POST",
dataType: "json",
data: $form.serialize(),
cache: false,
success: function(response) {
$('.reloadproducts').load(window.location + ' .reloadproducts > *');
$('#spinner').hide();
console.log(response);
},
error: function(response) {
console.log(response);
$('#spinner').hide();
}
});
});
});
</script>
ADD:
class SearchflightType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('from', 'genemu_jqueryselect2_entity', array(
'class' => 'FLYBookingsBundle:ListDeparturesArrivals',
'property' => 'name',
'placeholder' => 'Departure city',
'query_builder' => function(EntityRepository $er) {
return $er->createQueryBuilder('u')
->where('u.mode_transport = :mode')
->setParameter("mode", "AIRPLANE")
->groupBy('u.code')
->orderBy('u.name', 'ASC');
},)
)
->add('to', 'genemu_jqueryselect2_entity', array(
'class' => 'FLYBookingsBundle:ListDeparturesArrivals',
'property' => 'name',
'placeholder' => 'Arrival city',
'query_builder' => function(EntityRepository $er) {
return $er->createQueryBuilder('u')
->where('u.mode_transport = :mode')
->setParameter("mode", "AIRPLANE")
->groupBy('u.code')
->orderBy('u.name', 'ASC');
},)
)
->add('departuredate', DateType::class, array(
'required' => false,
'label' => 'Departure date',
'format' => 'y/M/d',
'widget' => 'single_text',
'attr' => [
'class' => 'form-control date_timepicker_start input-inline',
'placeholder' => 'dd/mm/yyyy',
]
))
->add('arrivaldate', DateType::class, array(
'required' => false,
'label' => 'Arrival date',
'format' => 'y/M/d',
'widget' => 'single_text',
'attr' => [
'class' => 'form-control date_timepicker_end input-inline',
'placeholder' => 'dd/mm/yyyy',
]
))
->add('price', TextType::class, array(
'required' => false,
'attr' => [
'class' => 'range',
"data-slider-min" => "5",
"data-slider-max" => "1000",
"data-slider-step" => "0.5",
"data-slider-value" => "[5,1000]"
]
));
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
parent::setDefaultOptions($resolver);
$resolver->setDefaults(array(
// avoid to pass the csrf token in the url (but it's not protected anymore)
'csrf_protection' => false,
'data_class' => 'FLY\BookingsBundle\Entity\Post'
))
;
}
public function getName()
{
return 'fly_bookingsbundle_searchtabflight';
}
}

Just want to give you some advices.
First of all, if you want to get the result while the user typing, use 'keyup' method.
Don't use
if ($this->get('request')->getMethod() == 'POST')
If you want to use this method only for POST, use annotation #Method, example here
And if you use
dataType: "json",
return JsonResponse from controller, for example:
return JsonResponse::create('status' => 'success', 'entities' => $form);
You don't need to set headers and do json_encode in this case.
Last point maybe helps you with your problem. Good luck!
UPDATE:
$('#myForm > input').change(function(e) {
$('#spinner').show();
e.preventDefault();
if (xhr) {
xhr.abort();
xhr = null;
}
var xhr = $.ajax({
type: "POST",
dataType: "json",
data: $form.serialize(),
cache: false,
success: function(response) {
$('.reloadproducts').load(window.location + ' .reloadproducts > *');
$('#spinner').hide();
console.log(response);
},
error: function(response) {
console.log(response);
$('#spinner').hide();
}
});
});

Related

Unable to post the data from view to controller in Yii2

I am working on Yii2. I have a gridview with checkbox and on a button click I am redirecting it to an action controller using ajax.
<?= Html::a('Disconnect', ['dco'], ['class' => 'btn btn-success', 'id'=>'dco']) ?>
<?php Pjax::begin(); ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\CheckboxColumn', 'checkboxOptions' => function($d) {
return ['value' => $d['msn']];
}],
'ref_no',
'dept_code:ntext',
'dept_name:ntext',
'allowed_units',
'msn',
'units_consumed',
[
'label' => 'Disconnected',
'attribute' => 'disconnected',
'format'=>'raw',
'contentOptions' => ['style'=>'text-align:center'],
'value' => function($model){
return $model->disconnected == 1 ? '<span class="glyphicon glyphicon-ok text-success"></span>' : '<span class="glyphicon glyphicon-remove text-danger"></span>';
},
'filter' => Html::activeDropDownList($searchModel, 'disconnected', [''=>'All','1'=>'Yes','0'=>'No'], ['class' => 'form-control']),
],
'diconnected_at',
'reconnected_at',
'active_energy_total_m',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
<?php Pjax::end(); ?>
JS
<?php
$DCOurl = Url::toRoute(['/hecolog/dco']);
$script = <<< JS
$(document).ready(function () {
//DCO
$('#dco').on('click',function(e) {
e.preventDefault();
var strValue = "";
$('input[name="selection[]"]:checked').each(function() {
if(strValue!=="")
{
strValue = strValue + " , " + this.value;
}
else
strValue = this.value;
});
$.ajax({
url: '$DCOurl',
type: 'POST',
dataType: 'json',
data: {data:strValue},
success: function(data) {
alert(data);
}
});
});
});
JS;
$this->registerJs($script, static::POS_END);
?>
But when I click on the disconnect button it doesn't redirect to my controller. In console it gives me Not Found (#404): Page not found.
Update 1
I have updated the ajax call like below
$.ajax({
url: $DCOurl, // removed the inverted commas ''
type: 'POST',
dataType: 'json',
data: {data:strValue},
success: function(data) {
alert(data);
}
});
Controller
public function actionDco()
{
if(Yii::$app->request->isAjax && Yii::$app->request->post())
{
$data = explode(',',$_POST['data']);
var_dump($data);
die();
}
else{
$this->redirect('index');
}
}
After updating the code as suggested I am able to go into my controller but still not able to get the data
In console I am getting error Uncaught SyntaxError: Invalid regular expression flags
Update 2
Below is the code for my view
<?php
use yii\helpers\Html;
use yii\grid\GridView;
use yii\widgets\Pjax;
use yii\helpers\Url;
use yii\web\JqueryAsset;
/* #var $this yii\web\View */
/* #var $searchModel common\models\HescologSearch */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'DCO / RCO';
$this->params['breadcrumbs'][] = $this->title;
?>
<section class="content-header">
<h1>DCO / RCO List</h1>
</section>
<section class="content">
<div class="box">
<div class="box-body">
<p>
<?= Html::a('Disconnect', ['dco'], ['class' => 'btn btn-success', 'id'=>'dco']) ?>
<?= Html::a('Re-Disconnect', ['rco'], ['class' => 'btn btn-info','id'=>'rco']) ?>
</p>
<?php Pjax::begin(); ?>
<div class="pre-scrollable">
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\CheckboxColumn', 'checkboxOptions' => function($d) {
return ['value' => $d['msn']];
}],
'ref_no',
'dept_code:ntext',
'dept_name:ntext',
'allowed_units',
'msn',
'units_consumed',
[
'label' => 'Disconnected',
'attribute' => 'disconnected',
'format'=>'raw',
'contentOptions' => ['style'=>'text-align:center'],
'value' => function($model){
return $model->disconnected == 1 ? '<span class="glyphicon glyphicon-ok text-success"></span>' : '<span class="glyphicon glyphicon-remove text-danger"></span>';
},
'filter' => Html::activeDropDownList($searchModel, 'disconnected', [''=>'All','1'=>'Yes','0'=>'No'], ['class' => 'form-control']),
],
'diconnected_at',
'reconnected_at',
'active_energy_total_m',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
</div>
<?php Pjax::end(); ?>
</div>
</div>
</section>
<?php
$DCOurl = Url::toRoute(['/hescolog/dco']);
$RCOurl = Url::toRoute(['/hescolog/rco']);
$script = <<< JS
$(document).ready(function () {
//DCO
$('#dco').on('click',function(e) {
e.preventDefault();
var strValue = "";
$('input[name="selection[]"]:checked').each(function() {
if(strValue!=="")
{
strValue = strValue + " , " + this.value;
}
else
strValue = this.value;
});
$.ajax({
url: $DCOurl,
type: 'POST',
dataType: 'json',
data: {data:strValue},
success: function(data) {
alert(data);
}
});
});
$('#rco').on('click',function(e) {
e.preventDefault();
var strValue = "";
$('input[name="selection[]"]:checked').each(function() {
if(strValue!=="")
{
strValue = strValue + " , " + this.value;
}
else
strValue = this.value;
});
$.ajax({
url: '$RCOurl',
type: 'POST',
dataType: 'json',
data: {data:strValue},
success: function(data) {
alert(data);
}
});
});
});
JS;
$this->registerJs($script, static::POS_END);
?>
I must be doing something wrong which I am not understanding
Any help would be highly appreciated.
first of all url:'$DCOurl' is correct and url must be in single or
double quotation. so you have a not found problem:
is your project in htdocs or www followed by /inventory-web/backend/ or there are some more directories? you use relative url so the url would be for ex: localhost/inventory-web/backend/web/ ...
ajax type 'POST' should match with behaviors['verbs']['actions'] if you have set it
check controller file name, class name and namespace
First, if you're serving an Ajax request you cannot do a redirect:
public function actionDco()
{
Yii::$app->response->format = Response::FORMAT_JSON;
$rv=[];
if(Yii::$app->request->isAjax && Yii::$app->request->post())
{
$data = explode(',',$_POST['data']);
$rv["infos"]=$data;
$rv["status"]='gotData';
}
else{
$rv["url"]=Url::to('index');
$rv["status"]='redirect';
}
return $rv;
}
About the JS error, instead of:
$.ajax({
url: $DCOurl,
type: 'POST',
dataType: 'json',
data: {data:strValue},
success: function(data) {
alert(data);
}
});
Add the quotes aroun the $DCOurl and to manage the return value from the ajax call
$.ajax({
url: "$DCOurl",
type: 'POST',
dataType: 'json',
data: {data:strValue},
success: function(data) {
if(data.status=='gotData'){
alert(data.infos);
}
if(data.status=='redirect'){
window.location.href=data.url;
}
}
});

Laravel sending data by ajax

I am trying to send data from my form to back-end by ajax but it doesn't send all my data.
preview of sent data
array:6 [
"title" => "xxxxxxxxxxxx"
"slug" => "xxxxxx"
"description" => """xxxxxxxxxxxxxxxxx"""
"publish" => "1"
"user_id" => "1"
"thumbnail" => null
]
Issues
my description is in triple double qoute """ xxxx """ (not sure if it's ok)
Image (thumbnail) didn't send
Categories didn't send
code
form
{{ Form::model($post, array('route' => array('quickedit', $post->id), 'method' => 'POST', 'files' => true)) }}
<div class="modal-body text-left">
{{-- show success message --}}
<div class="msg"></div>
<input type="hidden" name="user_id" id="user_id" value="{{Auth::user()->id}}">
<div class="row">
<div class="col-md-12 mt-3">
{{ Form::label('title', 'Title') }}
{{ Form::text('title', null, array('class' => 'form-control')) }}
</div>
<div class="col-md-12 mt-3">
{{ Form::label('slug', 'Slug') }}
{{ Form::text('slug', null, array('class' => 'form-control')) }}
</div>
<div class="col-md-12 mt-3">
{{ Form::label('description', 'Description') }}
{{ Form::textarea('description', null, array('class' => 'form-control editor')) }}
</div>
<div class="col-md-6 mt-3">
<div class="row">
#if(!empty($post->thumbnail))
<div class="col-md-3">
<img class="img-thumbnail" src="{{url('/images')}}/{{$post->thumbnail}}" alt="{{$post->title}}">
</div>
<div class="col-md-9">
{{ Form::label('thumbnail', 'Thumbnail') }}
{{ Form::file('thumbnail', array('class' => 'form-control')) }}
</div>
#else
<div class="col-md-12">
{{ Form::label('thumbnail', 'Thumbnail') }}
{{ Form::file('thumbnail', array('class' => 'form-control')) }}
</div>
#endif
</div>
</div>
<div class="col-md-6 mt-3">
{{ Form::label('publish', 'Publish') }}
<select name="publish" id="publish" class="custom-select">
<option value="">Select</option>
<option value="1" {{ $post->publish == '1' ? 'selected' : '' }}>Publish</option>
<option value="0" {{ $post->publish == '0' ? 'selected' : '' }}>Draft</option>
</select>
</div>
<div class="col-md-6 mt-3">
{{ Form::label('categories', 'Categories') }}
<select name="categories[]" id="categories" class="custom-select selectbox" multiple>
#foreach($categories as $category)
<option value="{{$category->id}}">{{$category->title}}</option>
#if(count($category->children) > 0)
#foreach($category->children as $children)
<option class="pl-2" value="{{$children->id}}">{{$children->title}}</option>
#if(count($children->children) > 0)
#foreach($children->children as $child)
<option class="pl-4" value="{{$child->id}}">{{$child->title}}</option>
#if(count($child->children) > 0)
#foreach($child->children as $childf)
<option class="pl-5" value="{{$childf->id}}">{{$childf->title}}</option>
#endforeach
#endif
#endforeach
#endif
#endforeach
#endif
#endforeach
</select>
</div>
</div>
</div>
<div class="modal-footer">
<div class="msg"></div>
</div>
{{Form::close()}}
<button class="btn btn-primary updatepost" data-id="{{$post->id}}" type="submit">Update</button>
JavaScript
<script>
$(document).ready(function() {
$('.updatepost').click(function (event) {
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }
});
event.preventDefault();
var title = $('input[name="title"]').val();
var slug = $('input[name="slug"]').val();
var description = $('.editor').val();
var publish = $('#publish option:selected').val();
var user_id = $('input[name="user_id"]').val();
var thumbnail = $('input[name="thumbnail"]').val();
var categories= $('#categories option:selected').val();
// $(this).attr("disabled", "disabled");
var prdfoId = $(this).data('id');
$.ajax({
url: '{{url("/admin/quickedit")}}/'+encodeURI(prdfoId),
type: "POST",
dataType: "json",
data: {
title: title,
slug:slug,
description: description,
publish: publish,
user_id: user_id,
thumbnail: thumbnail,
categories: categories
},
success:function(data) {
$('.msg').empty().append("Updated Successfully");
}
});
});
});
</script>
route
Route::post('quickedit/{id}','BlogController#quickedit')->name('quickedit');
controller
public function quickedit(Request $request, $id)
{
dd($request->all());
$this->validate($request, array(
'title' => 'required',
'slug' => 'required',
'description' => 'required',
'user_id' => 'required|numeric',
'thumbnail' => 'nullable|image',
'publish' => 'required|numeric',
));
$post = Post::find($id);
$post = Post::where('id',$id)->first();
$post->title = $request->input('title');
$post->slug = $request->input('slug');
$post->description = $request->input('description');
$post->user_id = $request->input('user_id');
$post->publish = $request->input('publish');
if ($request->hasFile('thumbnail')) {
$thumbnail = $request->file('thumbnail');
$filename = 'Post' . '-' . time() . '.' . $thumbnail->getClientOriginalExtension();
$location = public_path('images/' . $filename);
Image::make($thumbnail)->resize(850, 565)->save($location);
$post->thumbnail = $filename;
$oldFilename = $post->thumbnail;
$post->thumbnail = $filename;
Storage::delete($oldFilename);
}
$post->save();
$post->tags()->sync($request->tags);
$post->categories()->sync($request->categories);
}
Any idea?
Update
Based on answer and comments the last code I ended up is:
$(document).ready(function() {
$('.updatepost').click(function (event) {
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }
});
event.preventDefault();
var title = $('input[name="title"]').val();
var slug = $('input[name="slug"]').val();
var description = $('.editor').val();
var publish = $('#publish option:selected').val();
var user_id = $('input[name="user_id"]').val();
var thumbnail = $('input[type=file]')[0].files[0];
var categories= [];
$("#categories option:selected").each(function(){
categories.push($(this).val());
});
categories = JSON.stringify(categories);
//new
var formData = new FormData();
formData.append('thumbnail', thumbnail);
formData.append('title', title);
formData.append('slug', slug);
formData.append('description', description);
formData.append('publish', publish);
formData.append('user_id', user_id);
formData.append('categories', categories);
//new
var prdfoId = $(this).data('id');
$.ajax({
url: '{{url("/admin/quickedit")}}/'+encodeURI(prdfoId),
type: "POST",
dataType: "json",
data: formData,
contentType: false,
processData: false,
success:function(data) {
$('.msg').empty().append("Updated Successfully");
}
});
});
});
The result of this code is:
array:7 [
"thumbnail" => "undefined"
"title" => "xxxxxxx"
"slug" => "xxxxxxxxx"
"description" => """
xxxxx
"""
"publish" => "1"
"user_id" => "1"
"categories" => "[]"
]
issues
image is undefined
categories are not passed
description is in triple double qoutes """ xxxxx """
any idea?
Your quickedit method calling dd(), what dump data, then just die. Also, quickedit returns void. In must to be an object or array if you going to use AJAX+JSON.
If you send image file you need has to base64 if you need handle in json, Or need use FormData like this:
var formData = new FormData();
formData.append('image', $('input[type=file]')[0].files[0]);
$.ajax({
url: 'Your url here',
data: formData,
type: 'POST',
contentType: false, // NEEDED, DON'T OMIT THIS (requires jQuery 1.6+)
processData: false, // NEEDED, DON'T OMIT THIS
// ... Other options like success and etc
});
I think, a has a simplest way make two call firs send just json data, and then secound call is send the image.
var title = $('input[name="title"]').val();
var slug = $('input[name="slug"]').val();
var description = $('.editor').val();
var publish = $('#publish option:selected').val();
var user_id = $('input[name="user_id"]').val();
var thumbnail = $('input[name="thumbnail"]').prop('files');
var categories= $('#categories option:selected').val();
var formData = new FormData();
//Add a the file to fomr data
formData.append('image', thumbnail[0]);
//And need add data like this
formdData.append('title',title );

Multiselect dropdown listbox code using cakephp

i have two dependent select box in my form for selecting country and state.
when i select country India then it should populate its dependent state.upto this my code working fine...
bit i want to make this multiselect listbox.
Ex - if i select two countries from county dropdown then it populates states from two countries....not of single selected country.
below is my code...
HTML Select list box code
<?php
echo $this->Form->input('service_area_category_id', array(
'id' => 'shipping_type',
'required' => false,
'multiple' => 'multiple',
'type' => 'select',
'class' => 'form-control drop-arrow',
'label' => false,
'options' => $serviceCategory,
'empty' => '--Select--'
));
?>
<?php
echo $this->Form->input('ship_category', array(
'class' => 'form-control drop-arrow',
'required' => false,
'id' => 'state',
'label' => false,
'options' => '$states',
'empty' => '--Select--'
));
?>
Controller function
public function getServiceArea(){
$this->loadModel('ServiceAreaCategory');
$serviceCategory = $this->ServiceAreaCategory->find('list', array(
'conditions' => array(
'is_active' => 1
),
'fields' => array(
'ServiceAreaCategory.id',
'ServiceAreaCategory.name'
),
'order' => 'name ASC'
));
$this->set('serviceCategory', $serviceCategory);
}
public function loadSkills() {
$this->loadModel('Skill');
$states = array();
if (isset($this->request['data']['id'])) {
$states = $this->Skill->find('list', array(
'fields' => array(
'Skill.id',
'Skill.skill_name'
),
'conditions' => array(
'Skill.service_area_category_id' => $this->request['data']['id']
)
));
}
echo json_encode($states);
exit();
}
Ajax Script
<script type="text/javascript">
$(document).ready(function() {
$("#shipping_type").on('change', function() {
var id = $(this).val();
if (id) {
var dataString = 'id=' + id;
$.ajax({
type: "POST",
url: '<?php echo Router::url(array("controller" => "Profiles", "action" => "loadSkills")); ?>',
data: dataString,
dataType: 'JSON',
cache: false,
beforeSend: function() {
$('.spinicon').show();
},
complete: function() {
$('.spinicon').hide();
},
success: function(html) {
$("#loding1").hide();
$.each(html, function(key, value) {
$('<option>').val('').text('select');
$('<option>').val(key).text(value).appendTo($("#state"));
});
$('#state').selectpicker('refresh');
}
});
}
});
});
</script>
in your cakephp side function should be
public function loadSkills() {
$exploded_ids=explode(",",$this->request['data']['country_ids']);
$ids= "IN ('".implode(",",$exploded_ids).")";
$this->loadModel('Skill');
$states = array();
if (isset($this->request['data']['id'])) {
$states = $this->Skill->find('list', array('fields' => array('Skill.id','Skill.skill_name'),'conditions' => array(
'Skill.service_area_category_id '.$ids )));
}
echo json_encode($states);
exit();
}
And your Javascript and AJAX code Should be
<script type="text/javascript">
$(document).ready(function() {
$("#shipping_type").on('change', function() {
var ids = $(this).val();
if (id) {
$.ajax({
type: "POST",
url: '<?php echo Router::url(array("controller" => "Profiles", "action" => "loadSkills"),true); ?>',
data: {country_ids: ids}
dataType: 'JSON',
cache: false,
beforeSend: function() {
$('.spinicon').show();
},
complete: function() {
$('.spinicon').hide();
},
success: function(html) {
$("#loding1").hide();
$("#state").html("");
$.each(html, function(key, value) {
$('<option>').val('').text('select');
$('<option>').val(key).text(value).appendTo($("#state"));
});
$('#state').selectpicker('refresh');
}
});
}
});
});
</script>

Create a show FormType With Ajax and Jquery

I want to create a new form and show it directly in the view when i click into a button,
http://snapplr.com/snap/xbn2
This is my view
Ive already prepared my action in controller, and my new formType
class AttributOptionType extends AbstractType
{
private $type;
public function __construct($type){
$this->type = $type;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('translations', 'a2lix_translations', array(
'label' => 'formType.translations',
'fields' => array(
'name' => array(
'label' => 'Titre',
'field_type' => 'text',
'required' => false,
'attr' => array(
'class' => 'form-control input-circle-right'
)
),
'description' => array(
'label' => 'Titre',
'field_type' => 'text',
'required' => false,
'attr' => array(
'class' => 'form-control input-circle-right'
)
),
)
));
switch ($this->type) {
case 'radio' || 'checkbox':
$builder
->add('image', new MediaType(), array(
'label' => 'Image',
'attr' => array(
'class' => 'form-control input-circle-right',
),
'required' => false,
))
->add('code', 'text', array(
'label' => 'Image',
'attr' => array(
'class' => 'form-control input-circle-right',
),
'required' => false,
));
break;
case 'color':
$builder
->add('optionValue', 'text', array(
'label' => 'Image',
'attr' => array(
'class' => 'form-control input-circle-right',
),
'required' => false,
));
break;
}
}
My action :
public function createOptionAction($type){
$entity = new AttributOption();
$form = $this->createForm(new AttributOptionType($type), $entity);
}
Switch $type i will create my FormType, so all what i want to do, is to create this form from the view directly using AjaxRequest and display my new form type in the view,
How can i do this ?
Thanks
I have never done this myself, but in theory you can just create a seperate action that returns the form's html. Something like
public function createOptionAction($type){
$entity = new AttributOption();
$form = $this->createForm(new AttributOptionType($type), $entity);
return $this->render('AppBundle:AttributOption:form.html.twig', array('form' => $form));
}
Of course you have to create the corresponding template that only renders the form, without html or body tags.
Then call the route of that action via ajax from your main view with jQuery or whatever you are using. (I found the ajax stuff here, hope it works)
{% block javascripts %}
{{ parent() }}
$('#yourButton').on('click', function(event){
$.ajax({
type: "GET",
url: "{{ path('your_route') }}",
data: dataString,
success: function( returnedData ) {
$( '#container' ).html( returnedData );
}
});
}
{% endblock %}
Then of course you need an action that handles the submitted form. But that's nothing special there, just do it like with a normal form.
I have updating my code :
My Ajax Function
<script type="text/javascript">
var id_select = $('#products_productsbundle_attribut_type').val();
$('.ajaxOption').on('click', function(event){
$.ajax({
type: "get",
data: {'id': id_select},
dataType: 'json',
url: "{{ path('admin_products_attribut_optionAdd') }}",
success: function( returnedData ) {
$( '.container' ).html( returnedData.form );
}
});
});
</script>
And My action :
public function createOptionAction(){
$entity = new AttributOption();
$form = $this->createForm(new AttributOptionType($_POST['id']), $entity);
$response = new JsonResponse(array(
'message' => 'Error',
'form' => $this->renderView('ProductsBundle:Administration:Attribut/form.html.twig',array(
'entity' => $entity,
'form' => $form->createView(),
)
)), 400);
return $response;
}
And this my route :
admin_products_attribut_optionAdd:
pattern: /addOption
defaults: { _controller: "ProductsBundle:BackEnd/Attribut:createOption" }
The error is :
GET http://ispace/app_dev.php/admin/products/attribut/addOption?id=text 500 (Internal Server Error)m.ajaxTransport.send # jquery.min.js:4m.extend.ajax # jquery.min.js:4(anonymous function) # new:1083m.event.dispatch # jquery.min.js:3m.event.add.r.handle # jquery.min.js:3

How to submit form ajax in symfony2?

I am about to submit my form Using Ajax,i have successfully submit my form using POST but don't know how to use Ajax with Symfony
builform
$builder->add('name', 'text', array('constraints' => array(new NotBlank()), 'attr' => array('placeholder' => 'Name')))
->add('gender', 'choice', array('empty_value' => 'Select Gender', 'constraints' => array(new NotBlank()), 'choices' => \AppBundle\Entity\Records::$gender_list, "required" => true))
->add('dateOfBirth', 'birthday', array('label' => 'Date Of Birth','required'=>true))
->add('image_path', 'file', array('label' => ' ','required'=>false, 'data_class' => null, 'constraints'=>array(new Assert\File( array('mimeTypes'=>$mime_types, 'maxSize'=>'2048k' )))))
->add('country_of_birth', 'entity', array('empty_value' => 'Country of Birth',
'class' => 'AppBundle\Entity\Location',
'property' => 'country',
'label' => 'Country of Birth'
))
->add('religion', 'entity', array('empty_value' => 'Select Religion',
'class' => 'AppBundle\Entity\Religion',
'property' => 'name',
'label' => 'Religion'
));
Action
$success = false;
$record_rep = new \AppBundle\Entity\Records();
$form = $this->createForm(new \AppBundle\Form\AddPersonType(), $record_rep);
if ($this->getRequest()->getMethod() == 'POST') {
$form->submit($request);
if ($form->isValid()) {
$data = $form->getData();
$file = $data->getImagePath();
$image = $file->getClientOriginalName();
$new_image_name = $this->hanldeUpload($image, $file);
$this->savetoDB($data, $record_rep, $new_image_name);
$success = true;
}
}
return $this->render('AppBundle:Homepage:add_person_form.html.twig', array('form' => $form->createView(), 'success'=>$success ));
}
With jQuery, use serialize() the form and post it to your route.
$('#form').submit(function(e) {
e.preventDefault();
var url = "{{ path('YOUR_PATH') }}";
var formSerialize = $(this).serialize();
$.post(url, formSerialize, function(response) {
//your callback here
alert(response);
}, 'JSON');
});
In your action
if ($form->isSubmitted() && $form->isValid()) {
....
// or return new JsonResponse($anyData);
return new Response(json_encode(['status'=>'success']));
}
it must be ok like this. but you can add some parameters like the format, methods etc... in your routing.
For the Ajax:
$("#person").submit(function(e){
var formURL = "{{ path('form') }}";
var formData = new FormData(this);
$.ajax({
url: formURL,
type: 'POST',
data: formData,
mimeType:"multipart/form-data",
contentType: false,
cache: false,
processData:false,
success: function(data, textStatus, jqXHR)
{
},
error: function(jqXHR, textStatus, errorThrown)
{
}
});
e.preventDefault(); //Prevent Default action.
e.unbind();
});
$("#person").submit();
And for Action
if ($request->isXmlHttpRequest()) {
....
return new Response(json_encode(array('status'=>'success')));
}

Categories