Laravel sending data by ajax - javascript

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

Related

php codeigniter Video Upload Not Uploaded Video file

When uploading image files, the upload is complete and successful, but when uploading the video file, it is not uploaded and it does not show where the error is
HTML Code:
<div class="row mb-5">
<div class="col-md-12">
<input type="file" name="slider_image" id="" class="form-control mb-5" onchange="homeSliderUpload(this)">
<div class="progress mb-5" style="--sa-progress--value: 0%">
<div class="progress-bar progress-bar-sa-primary" role="progressbar" aria-valuenow="25" aria-valuemin="0" aria-valuemax="100">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
function homeSliderUpload(form) {
alert("First");
var file_data = $("input[name='slider_image']").prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: "<?php echo base_url(); ?>/Path/VedioUploader",
dataType: 'text',
method: "post",
cache: false,
contentType: false,
processData: false,
data: form_data,
success: function(data) {
var rJson = $.parseJSON(data);
if (rJson.status == true) {
$(".progress").attr("style", "--sa-progress--value: 100%");
$("input[name='slider_image']").val('');
setInterval(() => {
location.reload();
}, 1000);
} else {
alert("Error");
}
}
});
}
php Code ( Ajax Code):
public function VedioUploader()
{
$validateImage = $this->validate([
'file' => [
'uploaded[file]',
'mime_in[file, video/mp4, image/png, image/jpg,image/jpeg, image/gif]',
'max_size[file, 1000000000]',
],
]);
if ($validateImage) {
$imageFile = $this->request->getFile('file');
$folder = "Vedio/";
$fileName = rand(10005, 100005) . time() . ".mp4";
$imageFile->move($folder, $fileName);
$data = [
'img_name' => $imageFile->getClientName(),
'file' => $imageFile->getClientMimeType(),
'type' => $imageFile->getClientExtension(),
];
if ($fileName) {
$homeSliderModel = new VedioUplaod();
$home_slider["slider_file_url"] = $folder . "/" . $fileName;
$home_slider["slider_show"] = 1;
$home_slider["slider_order"] = 0;
$homeSliderModel->insert($home_slider);
if (!$homeSliderModel->errors()) {
echo json_encode([
"status" => true,
"slider_id" => $homeSliderModel->getInsertID(),
"file_url" => $folder . "/" . $fileName,
"order" => 0
]);
}
}
}
}
I tried removing the image types and retrying to upload the images, but it didn't work. It was similar to uploading the video. I thought it was because of the type, but nothing happened.
'mime_in[file, video/mp4]',

PHP not running with ajax POST

I have a form in a modal:
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
Add user
</button>
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form action="" method="post" id="saveperson">
<label for="newcat">Project Name</label>
<input type="text" name="newcat" value="">
<label for="description">Description</label>
<input type="text" name="description" value="">
<input type="submit" name="user" value="Submit">
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
On submit I run the js:
$(document).ready(function() {
$('#saveperson').submit(function(event) { //Trigger on form submit
var postForm = { //Fetch form data
'name' : $('input[name=newcat]').val(),
'desc' : $('input[name=description]').val() //Store name fields value
};
$.ajax({ //Process the form using $.ajax()
type : 'POST', //Method type
url : 'process.php',
data : postForm, //Forms name
dataType : 'json',
success : function(data) {
$('.modal-body').html("Done!");
}
else {
$('.modal-body').html("Error!");
}
}
});
event.preventDefault();
});
});
And then this should run in process.php
<?php
header ( "Content-Type: application/json");
$cat_ID = get_cat_ID( sanitize_title_for_query($_POST['newcat']) );
// Check if category exists
if($cat_ID == 0) {
$cat_name = sanitize_text_field($_POST['newcat']);
$cat_desc = sanitize_text_field($_POST['description']);
$cat_slug = sanitize_title_with_dashes($cat_name);
$my_cat = array(
'cat_name' => $cat_name,
'category_description' => $cat_desc,
'category_nicename' => $cat_slug,
'category_parent' => 0
);
if( wp_insert_category( $my_cat ) ) {
// Category added successfully
die ( json_encode ( array ( "success" => 1)));
} else {
// Error while creating new category
die ( json_encode ( array ( "success" => 0)));
}
} else {
// That category already exists
die ( json_encode ( array ( "success" => 0)));
}
?>
But after the submit, nothing happens and the data isn't saved in the db, meaning isn't working. If I use this php tho in a standard php without ajax, it works and saves the data in the db
<?php
header ( "Content-Type: application/json");
if( isset( $_POST['user'] ) ) {
if( !empty( $_REQUEST['newcat'] ) ) {
$cat_ID = get_cat_ID( sanitize_title_for_query($_POST['newcat']) );
// Check if category exists
if($cat_ID == 0) {
$cat_name = sanitize_text_field($_POST['newcat']);
$cat_desc = sanitize_text_field($_POST['description']);
$cat_slug = sanitize_title_with_dashes($cat_name);
$my_cat = array(
'cat_name' => $cat_name,
'category_description' => $cat_desc,
'category_nicename' => $cat_slug,
'category_parent' => 0
);
wp_insert_category( $my_cat );
}
}
}
?>
There is an error in the browser console:
$(document).ready(function() {
$('#saveperson').submit(function(event) { //Trigger on form submit
var postForm = { //Fetch form data
'name' : $('input[name=newcat]').val(),
'desc' : $('input[name=description]').val() //Store name fields value
};
$.ajax({ //Process the form using $.ajax()
type : 'POST', //Method type
url : 'process.php',
data : postForm, //Forms name
dataType : 'json',
success : function(data) {
$('.modal-body').html("Done!");
}
else {
$('.modal-body').html("Error!");
}
}
});
event.preventDefault();
});
});
Notice the
else {
$('.modal-body').html("Error!");
}
Error:
Uncaught SyntaxError: Unexpected token else
Remove the else block, it should work
It should be:
$(document).ready(function() {
$('#saveperson').submit(function(event) { //Trigger on form submit
var postForm = { //Fetch form data
'name' : $('input[name=newcat]').val(),
'desc' : $('input[name=description]').val() //Store name fields value
};
$.ajax({ //Process the form using $.ajax()
type : 'POST', //Method type
url : 'process.php',
data : postForm, //Forms name
dataType : 'json',
success : function(data) {
$('.modal-body').html("Done!");
}
});
event.preventDefault();
});
});
Here is the fiddle
Did u try this?
$( "#saveperson" ).submit(function( event ) {
let form = $( this );
let formData = new FormData(form[0]);
$.ajax({ //Process the form using $.ajax()
type : 'POST', //Method type
url : 'process.php',
data : formData,
success : function(data) {
$('.modal-body').html("Done!");
}
});
event.preventDefault();
});
The issue was I was running wordpress standard functions from an external php file and it doesn't work. In order to achieve what i was doing, I had to use
function.php and wordpress ajax
add_action( 'wp_footer', 'ajax_Person' );
function ajax_Person() { ?>
<script type="text/javascript">
jQuery("#createCat").on("click", function(e){
e.preventDefault();
person();
});
function person(){
jQuery.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'post',
data: { action: 'data_person', catName: jQuery('#newCat').val(), catDesc: jQuery('#descRiption').val() },
success: function(data) {
}
});
}
</script>
<?php }
add_action('wp_ajax_data_person' , 'data_person');
add_action('wp_ajax_nopriv_data_person','data_person');
function data_person(){
$catname = $_POST['catName'];
$catdesc = $_POST["catDesc"];
$cat_ID = get_cat_ID( sanitize_title_for_query($catname) );
// Check if category exists
if($cat_ID == 0) {
$cat_name = $catname;
$cat_desc = $catdesc;
$cat_slug = sanitize_title_with_dashes($cat_name);
$my_cat = array(
'cat_name' => $cat_name,
'category_description' => $cat_desc,
'category_nicename' => $cat_slug,
'category_parent' => 0
);
if( wp_insert_category( $my_cat ) ) {
echo 'Category added successfully';
} else {
echo 'Error while creating new category';
}
} else {
echo 'That category already exists';
}
}

Ajax Add button in for each loop Laravel 5.4

I'm trying to create an "Add button" in foreeach loop. And submit it using ajax. But i have problems finding out what exactly im doing wrong, my JS knowledge is very poor.
So this is my code.
View:
#foreach ($lots as $lot)
#if (count($lot->comments) >= 1)
<span class="glyphicon glyphicon-ok"></span>
#else
<form id="favorites-button" data-id="{{ $lot->lot_id }}">
{{ csrf_field() }}
<input type="hidden" name="body" value="0_o" class="form-control">
<button type="submit" class="btn btn-xs btn-primary">Favorites</button>
</form>
#endif
#endforeach
This is my JS
#section('js')
<!-- Ajax add to favorites -->
<script type="text/javascript">
$("document").ready(function(){
$("#favorites-button").submit(function(e){
e.preventDefault();
var button = $(this);
var url = '/lots/' + button.data('id') + '/comment';
var body = $("input[name=body]").val();
var dataString = 'body='+body;
$.ajax({
type: "POST",
url : url,
data : dataString,
dataType : "json",
success : function(data){
}
},"json");
});
});
</script>
#endsection
This is my route:
Route::post('/lots/{lot}/comment', 'CommentsController#add');
And my controller:
public function add(Lot $lot)
{
Comment::create([
'body' => request('body'),
'lot_id' => $lot->lot_id,
'user_id' => auth()->user()->id,
'bid' => $lot->bid,
'lot_date' => $lot->lot_date,
'auction_name' => $lot->auction_name,
'pics_urls' => $lot->pics_urls,
'company' => $lot->company,
'model_name_en' => $lot->model_name_en,
'model_type_en' => $lot->model_type_en,
'scores_en' => $lot->scores_en,
'model_year_en' => $lot->model_year_en,
'color_en' => $lot->color_en,
'displacement' => $lot->displacement,
'transmission_en' => $lot->transmission_en,
'start_price_en' => $lot->start_price_en,
'inspection_en' => $lot->inspection_en,
'grade_en' => $lot->grade_en,
'equipment_en' => $lot->equipment_en,
'mileage_num' => $lot->mileage_num,
'result_en' => $lot->result_en,
'auct_ref' => $lot->auct_ref,
]);
return "ok";
}
So i think the problem is also in ID that im using in foreach loop. That means all forms in loop have same ID's. So i need to reconsider my whole approach. Any one have ideas how can i do this?
<script type="text/javascript">
$("document").ready(function(){
$("#favorites-button").submit(function(e){
e.preventDefault();
var button = $(this);
var url = '/lots/' + button.data('id') + '/comment';
var body = $("input[name=body]").val();
$.ajax({
type: "POST",
url: url,
data: {
body: body,
_token: '{{ csrf_token() }}'
},
dataType: "json",
success: function(data){
console.log('success');
}
},"json");
});
});
</script>
I think it helps.
So i was doing everything wrong in the beginning!
I changed the whole approach. Thanks to my friends help.
Now first of all i change form in to a Button witch calls an event:
this is the view:
#foreach ($lots as $lot)
#if (count($lot->comments) >= 1)
<span class="glyphicon glyphicon-ok"></span>
#else
<button data-id="{{ $lot->lot_id }}" class="btn btn-xs btn-primary favouriteButton">Favourite</button>
#endif
#endforeach
Than i change JS:
<!-- Ajax add to favorites -->
<script type="text/javascript">
// call button via class
$('.favouriteButton').click(function (e) {
var button = $(this);
e.preventDefault();
// change the route
$.get('/lots/' + $(this).data('id') + '/favourite')
.done(function (response) {
// instead of button insert check icon
button.parent().append('<span class="glyphicon glyphicon-ok"></span>');
// remove button
button.remove();
})
.fail(function (respnse) {
});
});
</script>
Than i change my route:
Route::get('/lots/{lot}/favourite','CommentsController#favouriteButton');
And created new function:
public function favouriteButton(Lot $lot){
Comment::create([
'body' => 'Auto add', // this is the body for new comment
'lot_id' => $lot->lot_id,
'user_id' => auth()->user()->id,
'bid' => $lot->bid,
'lot_date' => $lot->lot_date,
'auction_name' => $lot->auction_name,
'pics_urls' => $lot->pics_urls,
'company' => $lot->company,
'model_name_en' => $lot->model_name_en,
'model_type_en' => $lot->model_type_en,
'scores_en' => $lot->scores_en,
'model_year_en' => $lot->model_year_en,
'color_en' => $lot->color_en,
'displacement' => $lot->displacement,
'transmission_en' => $lot->transmission_en,
'start_price_en' => $lot->start_price_en,
'inspection_en' => $lot->inspection_en,
'grade_en' => $lot->grade_en,
'equipment_en' => $lot->equipment_en,
'mileage_num' => $lot->mileage_num,
'result_en' => $lot->result_en,
'auct_ref' => $lot->auct_ref,
]);
return "ok";
}
I hope my experience will help some body.

Ajax not working in codeigniter 3

when i click in the button btnSalvar, ajax need to send data to my controller, but not working.
my ajax:
$("#btnSalvar").on('click', function(){
$.ajax({
url: '<?= base_url(); ?>' + 'grupoProduto/cadastro',
type: 'POST',
data: {Nome: $("#txtNome").val(), Ativo: $("#cbxAtivo").val()},
dataType: 'json',
cache: false,
success:
function(data){
alert(data.Nome); //as a debugging message.
}
});
return false;
});
My controller:
public function cadastro() {
$this->load->view('grupoproduto_view');
}
my alert(data.Nome) showing nothing
here's my full php code:
`
<div class="row">
<div class="form-group">
<label for="txtNome" class="col-md-3 control-label">Nome</label>
<div class="col-md-6">
<?php echo form_input(['name' => 'txtNome', 'class' => 'form-control',
'value' => set_value('txtNome'), 'required' => 'true', 'maxlength' => '50', 'required' => 'true', 'id' => 'txtNome']); ?>
</div>
</div>
<div class="form-group">
<label for="cbxAtivo" class="col-md-3 control-label">Ativo</label>
<div class="col-md-1">
<?php echo form_checkbox(['name' => 'cbxAtivo', 'class' => 'form-control', 'required' => 'true', 'id' => 'cbxAtivo']); ?>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<div class="modal-footer">
<?php echo anchor(NULL, "<i class='glyphicon glyphicon-remove'></i> Sair", ['class' => 'btn btn-default', 'id' => 'btnSair', 'role' => 'button', 'data-dismiss' => 'modal']); ?>
<?php echo form_button(NULL, "<i class='glyphicon glyphicon-ok'></i> Salvar", ['class' => 'btn btn-success', 'id' => 'btnSalvar', 'role' => 'button']); ?>
</div>
</div>
</div>
</div>
</fieldset>
new edit!
`$("#btnSalvar").on('click', function(){
var nome = $("#txtNome").val();
var ativo = $("#cbxAtivo").val();
var url = '<?= base_url(); ?>grupoProduto/cadastro';
$.ajax({
url: url,
type: 'POST',
data: {Nome: nome, Ativo: ativo},
dataType: 'json',
cache: false,
success:
function(data){
alert(data.Nome); //as a debugging message.
},
error: function() {
alert(url);
}
});
return false;
});`
return error in the ajax and show this url: http://localhost/admin/grupoProduto/cadastro. It's correct, but why not success?
Your PHP '<?= base_url(); ?>' + 'grupoProduto/cadastro' is not getting evaluated
$.ajax({
url: '+<?= base_url(); ?>+'+ 'grupoProduto/cadastro',
....
Problem is in your base_url()
In order to use base_url(), you must first have the URL Helper loaded. This can be done either in application/config/autoload.php (on or around line 67):
$autoload['helper'] = array('url');
Or,
manually:
$this->load->helper('url');
checkout this answer
maybe the problem as Nadir says that base_url not evaluated ,
you can try something like this
var link = "<?php echo base_url(); ?>";
var Nome = $("#txtNome").val();
var Ativo = $("#cbxAtivo").val();
$.post(link + "grupoProduto/cadastro", {Nome : Nome ,Ativo :Ativo},function(data){
alert("something")
});

Instant search with Ajax and Symfony2

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

Categories