I'm using Symfony2 and I would like to use the BlueImp plugin, basic setup.
Actually, I have a form in which you can load 3 pictures and one song (it is for an artist registration).
As a start, I try to implement the plugin for just one picture. But when I select a file in my input "picture 1", nothing happens.. What is wrong ?
<html>
<head>
<script type="text/javascript" src="{{ asset('bundles/mybundle/js/jquery-file-upload/js/vendor/jquery.ui.widget.js') }}"></script>
<script type="text/javascript" src="{{ asset('bundles/mybundle/js/jquery-file-upload/js/jquery.iframe-transport.js') }}"></script>
<script type="text/javascript" src="{{ asset('bundles/mybundle/js/jquery-file-upload/js/jquery.fileupload.js') }}"></script>
</head>
<form id="myForm" action="{{ path('MyBundle_artist_new') }}" {{ form_enctype(form) }} method="post" novalidate>
<div class="field">
{{ form_label(form.picture1 "Picture 1") }}
{{ form_widget(form.picture1) }}
</div>
<input type="submit" value="Register"/>
</form>
<script type="text/javascript">
$(document).ready(function(){
$('#myform_picture1').fileupload(
{
dataType: 'json',
url:'{{path('MyBundle_ajax_upload_picture') }}',
done: function (e, data) {
$.each(data.result.files, function (index, file) {
$('<p/>').text(file.name).appendTo(document.body);
});
}
});
});
</script>
Here is upload handler (the action for the url {{path('MyBundle_ajax_upload_picture') }} :
<?php
public function ajaxUploadPicture()
{
$request = $this->get('request');
$uploaded_file = $request->files->get('myform_picture1');
if ($uploaded_file)
{
$picture1 = $this->processImage($uploaded_file);
$picture1->setPath('pictures/artist/' . $picture1);
$em->persist($picture1);
$em->flush();
$response = 'success';
}
else $response= 'error';
$response = new Response(json_encode(array('response'=>$response)));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
public static function processImage(UploadedFile $uploaded_file)
{
$path = 'pictures/artist/';
$uploaded_file_info = pathinfo($uploaded_file->getClientOriginalName());
$filename = uniqid() . "." .$uploaded_file_info['extension'];
$uploaded_file->move($path, $filename);
return $filename;
}
You should check what you get from ajax request ex:
$('#myform_picture1').fileupload(
{
dataType: 'json',
url:'{{path('MyBundle_ajax_upload_picture') }}',
done: function (e, data) {
$.each(data.result.files, function (index, file) {
$('<p/>').text(file.name).appendTo(document.body);
});
},
always: function (e, data) {
console.log(data);
}
});
I am not sure about this line $uploaded_file = $request->files->get('myform_picture1');
you sure that your file input name is myform_picture1 ?
Please try $uploaded_file = $request->files->get('myform[picture1]', array(), true);
Related
This is my controller method in Admin Controller , this method receive the search input but i am facing problems to pass output data to the view file
public function action(Request $request)
{
if($request->ajax())
{
$students=Student::where('name','LIKE','%'.$request->search."%")->paginate(5);
$data = $students->count();
if($data > 0)
{
$output=$students;
}
else{
$output=$students;
}
return view('search' compact('output'));
}
}
Here is the ajax in view file (search.blade.php)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script type="text/javascript">
// $(document).on('keyup', '#search', function(){
$('#search').on('keyup',function(){
$value=$(this).val();
$.ajax({
type : 'get',
url : '{{route('search.action')}}',
data:{'search':$value},
success:function(data){
$('tbody').html(data);
}
});
})
</script>
<script type="text/javascript">
$.ajaxSetup({ headers: { 'csrftoken' : '{{ csrf_token() }}' } });
</script>
Here is the ajax route
Route::get('/search/action', 'AdminController#action')->name('search.action');
Update the below source code.
AdminController.php
public function action(Request $request)
{
if ($request->ajax()) {
// Convert to lowercase after trim the searched text
$search_text = strtolower(trim($request->search));
$students = Student::where('name','LIKE','%'.$search_text."%")->paginate(5);
$data = $students->count();
$output = array();
if ($data > 0) {
$output = $students->toArray();
}
// Return JSON response
return response()->json($output);
}
}
search.blade.php
<input type="text" id="search">
<div id="studentlist">
<table>
<thead>
<tr>
<th>Id</th>
<th>Name</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script type="text/javascript">
$('#search').on('keyup',function(){
$value=$(this).val();
$.ajax({
type : 'get',
url : '{{route('search.action')}}',
data:{'search':$value},
success:function(response){
var studentListHtml = "";
if (response) {
if (response.data && response.data.length > 0) {
$.each(response.data , function( index, value ) {
studentListHtml += "<tr><td>" + value.id + "</td>" + "<td>" + value.name + "</td></tr>";
});
$("#studentlist table tbody").empty().html(studentListHtml);
} else {
$("#studentlist table tbody").empty().html("<tr><td colspan='2'>No students found</td></tr>");
}
}
}
});
})
</script>
<script type="text/javascript">
$.ajaxSetup({ headers: { 'csrftoken' : '{{ csrf_token() }}' } });
</script>
I try to make an autocompletion search to my laravel application , but i get an error when i inspect my browser i get " b.toLowerCase is not a function "
Here my controller for Autocomplete :
public function autocomplete(Request $request){
$data = Licencies::select("lb_nom")->where("lb_nom","LIKE","%{$request->input('query')}%")->get();
return response()->json($data);
}
Here my view Input :
#section('content')
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.1/bootstrap3-typeahead.min.js"></script>
<input class="typeahead form-control" style="margin:0px auto;width:300px;" type="text">
Here my script :
<script type="text/javascript">
var path = "{{ route('autocomplete') }}";
$('input.typeahead').typeahead({
source: function (query, process) {
return $.get(path, { query: query }, function (data) {
return process(data);
});
}
});
</script>
Someone knows why i get
b.toLowerCase is not a function
Many thanks in advance
Try this:
$data = Licencies::select("lb_nom as name")
I am trying to build the controller that saves the image in my public folder using image intervention. I have used Cropit jquery plugin for image cropping and use ajax. The error " MethodNotAllowedHttpException in RouteCollection.php line 218" occurs.Below are my controller ,routes and view.
CropController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Image;
class CropController extends Controller
{
public function crop(Request $request){
$img = $request->image_data;
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
Image::make($data)->save('images/images.jpg');
dd("image saved in images/images.jpg");
}
}
web.php
Route::get('/', function () {
return view('welcome');
});
Route::post('/image-crop',[
'uses'=>'CropController#crop',
'as'=>'image-crop',
]);
welcome.blade.php
<body>
<form method="post">
<input type="hidden" value="{{Session::token()}}" name="_token">
<div class="image-editor">
<input type="file" class="cropit-image-input">
<div class="cropit-preview"></div>
<div class="image-size-label">
Resize image
</div>
<input type="range" class="cropit-image-zoom-input">
<input type="hidden" name="imagedata" class="hidden-image-data" />
<button type="submit">Submit</button>
</div>
</form>
<script>
var url1="{{route('image-crop')}}";
$(function() {
$('.image-editor').cropit();
$('form').submit(function() {
//event.preventDefault();
// Move cropped image data to hidden input
var imageData = $('.image-editor').cropit('export');
$('.hidden-image-data').val(imageData);
// Print HTTP request params
var formValue = $(this).serialize();
$.ajax({
type:'post',
data:formValue,
url: '/image-crop',
success: function(data){
$('#result-data').text('New file in: images/'+data);
$('#crop').show();
}
})
.done(function(){
window.location.href=""+'/image-crop';
});
return true;
});
});
</script>
</body>
How to solve that error ?
Thank you
Hey Try to add this metatag on your layout
<meta name="csrf-token" content="{{ csrf_token() }}">
Also in your ajax request add this $.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
Let me know if it works!.
https://laravel.com/docs/5.1/routing#csrf-x-csrf-token
I developed a simple ajax code.According to this image when click+ qty increase and when click - qty decrease
Code in online _help.blade.php
<head>
<title>Ajax Example</title>
<meta name="csrf-token" content="{{ csrf_token() }}">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script>
$(document).ready(function(){
$('.cart_quantity_up, .cart_quantity_down').on('click', function(e) {
e.preventDefault();
var increment = $(this).data('increase');
var itemId = $('.cart_quantity_input').val();
$.ajax({
type:'post',
url:'getmsg',
dataType:'json',
data:{
'item_id': itemId,
'increase': increment
},
success:function(data){
$("cart_quantity_input").val(data.qty);
} });
});
});
</script>
</head>
<body>
<div class="cart_quantity_button">
<a class="cart_quantity_up" href="javascript:void(0)" data-increase="1" > + </a>
<input class="cart_quantity_input" type="text" name="quantity" value="{{1}}" autocomplete="off" size="2">
<a class="cart_quantity_down" href="javascript:void(0)" data-increase="0" > - </a>
</div>
</body>
<footer>
<script type="text/javascript">
var csrf_token = $('meta[name="csrf-token"]').attr('content');
$.ajaxSetup({
headers: {"X-CSRF-TOKEN": csrf_token}
});
</script>
</script>
</footer>
Code in controller function
public function ajaxl(Request $request)
{
if ($request->ajax()) {
$id = $request->item_id;
if ($request->increase) {
//$cart->increment('qty');
$qty = 2;
} else {
//$cart->decrement('qty');
$qty = 0;
}
//echo"hello ajaxlara:";
return response()->json(array('qty'=> $id), 200);
}
}
And this routes.php
Route::get('/ajax',function(){return view('online_help');});
Route::post('/getmsg','Hello#ajaxl');
When I click + or - the value doesn't change and no error.
Please any one help me
The problem is very small.
This line:
$("cart_quantity_input").val(data.qty);
just you forgot to add . before cart_quantity_input
So change it to be :
$(".cart_quantity_input").val(data.qty);
I want to develop simple ajax with laravel5.2 with this code
This oneline_help.php view
<html>
<head>
<title>Ajax Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
function getMessage(){
$.ajax({
type:'POST',
url:'/getmsg',
data:'_token = <?php echo csrf_token() ?>',
success:function(data){
$("#msg").html(data.msg);
}
});
}
</script>
</head>
<body>
<div id = 'msg'>This message will be replaced using Ajax.
Click the button to replace the message.</div>
<?php
echo Form::button('Replace Message',['onClick'=>'getMessage()']);
?>
</body>
</html>
This is the routes
Route::get('/ajax','front#support');
Route::post('/getmsg','Hello#index');
This is front #support
public function support()
{
return view('online_help', array('title' => 'Welcome', 'description' => '', 'page' => 'online_help','subscribe'=>"",'brands' => $this->brands));
}
This is Hallo #index controller
public function index(){
echo"i in in hello index";
$msg = "This is a simple message.";
return response()->json(array('msg'=> $msg), 200);
}
The button appear But when click on it, The text doesn't change .
Please tell me why and how to resolve it.
Here is my working example of AJAX....
You don't need to add token in your ajax request, make it global so with every ajax request, your CSRF token will be added automatically.
In your HTML Head section add this meta tag
<meta name="csrf-token" content="<?php echo csrf_token() ?>">
Then add this code in your Javascript tags. this will add CSRF token in every ajax request.
Note this required jquery file should be included in your page. once include call this method below from the file.
<script type="text/javascript">
var csrf_token = $('meta[name="csrf-token"]').attr('content');
$.ajaxSetup({
headers: {"X-CSRF-TOKEN": csrf_token}
});
</script>
I have modified your method....
<script>
function getMessage(){
$.ajax({
type:'POST',
url:'/getmsg',
data:'_token = <?php echo csrf_token() ?>', //remove this line
dataType:'json', // you skipped this line
beforeSend:function(){
alert('loading....'); //this will show loading alert
},
success:function(data){
$("#msg").html(data.msg);
},
error:function(){
alert('loading error...')
}
});
}
</script>