i develop web application with laravel 5.2 , i try to send an array with ajax to my controller , the request sent but after that i saw the error :405 method not allowed , i searched many times but this problem didn't solve :
my ajax code is :
// send array of stream checkbox to controller
$('#json-btn').click(function () {
var input = $("form input:checkbox");
var stream = [];
$.each($(input), function(){
stream.push($(this).val());
});
var jstream = JSON.stringify(stream);
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajax({
url: '/ajaxGet/',
type: 'POST',
data: {_token: CSRF_TOKEN , jstream:jstream},
dataType: 'JSON',
success: function (data) {
alert(data);
}
});
});
my route is :
Route::post('ajaxGet', 'ajaxController#getRequest');
my controller is :
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
class ajaxController extends Controller
{
public function getRequest(Request $request)
{
echo $request['jstream'];
}
}
and finally this is my form :
{!! Form::open(array('id' => 'trailer-form')) !!}
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<table dir="rtl">
<thead>
<tr>
<th>quality</th>
<th>link</th>
<th>steram</th>
</tr>
</thead>
<tbody>
<tr>
<td>
{!! Form::select('quality[]', array('noQuality'=>'select...','64p'=>'64p','144p'=>'144p','240p'=>'240p','360p'=>'360p','480p'=>'480p','720p'=>'720p', '1080p'=>'1080p'), null , ['class'=> 'form-control lns' , 'id' => 'quality-input']) !!}
</td>
<td>
{!! Form::text('downLoadLink[]',null,['class' => 'form-control ln' , 'id' => 'down-input']) !!}
</td>
<td>
{!! Form::checkbox('stream[]','false',null,['class' => 'form-control' , 'id' => 'streamCheck' , 'onchange' => 'createAlerts(this)']) !!}
</td>
<td>
<button class="btn btn-success btn-add" type="button">
<i class="glyphicon glyphicon-plus gs"></i>
</button>
</td>
</tr>
</tbody>
</table>
{!! Form::submit('json create',['class' => 'btn btn-success' , 'id' => 'json-btn']) !!}
{!! Form::close() !!}
please help me to solve this problem thank you so very much :)
Related
I need to store my images in the database in one column dynamically I have no idea how to do it please help me. thank you in advance here is my view controller and model. Here is an image, Below there are an array that on Choose File Button. I want to store them into the database in a column how to do that?
My Database Table name is InflightMagazine
My VIEW code
{!! Form::open(['action'=>'Admin\InflightMagazines#store', 'method' => 'POST','enctype'=>'multipart/form-data']) !!}
<div class="table-responsive">
<table class="table table-bordered" id="dynamic_field">
<tr class="form-row">
<td> <b>{{ Form::text('inflightmagz_date[]', date('F Y') , ['class' => 'form-control', 'id'=>"exampleFormControlFile1"])}}</b><br>
{{ Form::file('infightmagazine_pdf[]',['id'=>'exampleFormControlFile1']) }}
{{ Form::button('', ['class' => 'btn btn-success fa fa-plus-circle addFile', 'id'=>'addFile','name'=>'addFile', 'style'=>'font-size:15px;']) }}
</td>
<td>{{ Form::button('', ['class' => 'btn btn-success fa fa-plus-circle add', 'id'=>'add','name'=>'add', 'style'=>'font-size:15px;']) }}</td>
</tr>
</table>
{{Form::submit('submit', ['class'=>'btn btn-primary', 'name'=>'submit'])}}
</div>
{!! Form::close() !!}
AJAX / JQuery Code
<script>
$(document).ready(function() {
var len = $('.form-row').length;
$(document).on('click', '.add', function() {
$('#dynamic_field').append('<tr class="form-row" data-id="'+len+'"><td> {{ Form::text('inflightmagz_date[]', date('F Y') , ['class' => 'form-control', 'id'=>"exampleFormControlFile1"])}} <br> {{ Form::file('infightmagazine_pdf[]',['id'=>'exampleFormControlFile1']) }} {{ Form::button('', ['class' => 'btn btn-success fa fa-plus-circle addFile', 'id'=>'addFile','name'=>'addFile', 'style'=>'font-size:15px;']) }}</td><td><button type="button" name="remove" class="btn btn-danger fa fa-minus-circle btn_remove_all"></button></td></tr>');
});
$(document).on('click', '.submit', function() {
$.ajax({
method: "POST",
data: $('#add_name').serialize(),
success: function(data) {
alert(data);
$('#add_name')[0].reset();
}
});
});
$(document).on('click', '.addFile', function() {
var id = $(this).closest('.form-row').data('id');
var elem = '<tr class="'+id+'"><td>{{ Form::file('infightmagazine_pdf[]',['id'=>'exampleFormControlFile1']) }}<button type="button" name="remove" class="btn btn-danger btn_remove fa fa-minus-circle"></button></td></tr>';
$(elem).insertAfter($(this).closest('tr'));
});
$(document).on('click', '.btn_remove, .btn_remove_all', function() {
if($(this).hasClass('btn_remove_all')){
var id = $(this).closest('.form-row').data('id');
$('tr.'+id).remove();
}
$(this).closest('tr').remove();
});
});
</script>
Controller Storing Function code
public function store(Request $request){
$this->validate($request, [
'inflightmagz_date' => 'required',
'infightmagazine_pdf' => 'required'
]);
if ($request->has('infightmagazine_pdf')){
//Handle File Upload
$inflightmags = [];
foreach ($request->file('infightmagazine_pdf') as $key => $file){
// Get FileName
$filenameWithExt = $file->getClientOriginalName();
//Get just filename
$filename = pathinfo( $filenameWithExt, PATHINFO_FILENAME);
//Get just extension
$extension = $file->getClientOriginalExtension();
//Filename to Store
$fileNameToStore = $filename.'_'.time().'.'.$extension;
//Upload Image
$path = $file->storeAs('public/infightmagazine_pdfs',$fileNameToStore);
array_push($inflightmags, $fileNameToStore);
}
$fileNameToStore = serialize($inflightmags);
}
}
I think what you are looking for is attribute casting to array
https://laravel.com/docs/5.7/eloquent-mutators#attribute-casting
this will allow you to save an array of file locations to a single field in the DB and retrieve them as an array
I would remove the serialise on the $fileNamesToStore
Hope this helps
I am using Vue.js with Axios to post my data. But Axios returns NULL from my Laravel Controller. Input text is empty when using v-model (update form - blade laravel).
Pretty new to this awesome framework. I need to make an AJAX call for a text input in an update form (blade laravel), however in the form the input is blank and I’m having trouble to figure out if I’m missing something.
Question:
How do I send the input value from the blade template when the form is loaded to the Vue data instance
Blade:
{!! Form::open(['url' => '','class'=>'form-horizontal', 'id'=>'smv-cost-form','enctype'=>'multipart/form-data']) !!}
{!! Form::hidden('trans_id_d','36', ['class' => 'custom-input-bom','readonly'=>'readonly']) !!}
<tr id="smvCostAdd">
<td colspan="2">
{!! Form::text('knittingCost','',['class'=>'input-custom form-control','id'=>'knittingCost','v-model'=>'smvCostModel.knittingCost']) !!}
<p class="error" v-if="knittingCost_error">#{{knittingCost_error}}</p>
</td>
<td colspan="2">
{!! Form::text('linkingCost','',['class'=>'input-custom form-control','id'=>'linkingCost','v-model'=>'smvCostModel.linkingCost']) !!}
<p class="error" v-if="linkingCost_error">#{{linkingCost_error}}</p>
</td>
<td colspan="2">
{!! Form::text('tremingCost','',['class'=>'input-custom form-control','id'=>'tremingCost','v-model'=>'smvCostModel.tremingCost']) !!}
<p class="error" v-if="tremingCost_error">#{{tremingCost_error}}</p>
</td>
<td colspan="2">
{!! Form::text('mendingCost','',['class'=>'input-custom form-control','id'=>'mendingCost','v-model'=>'smvCostModel.mendingCost']) !!}
<p class="error" v-if="mendingCost_error">#{{mendingCost_error}}</p>
</td>
<td colspan="2">
{!! Form::text('washCost','',['class'=>'input-custom form-control','id'=>'washCost','v-model'=>'smvCostModel.washCost']) !!}
<p class="error" v-if="washCost_error">#{{washCost_error}}</p>
</td>
<td colspan="2">
{!! Form::text('pcqCost','',['class'=>'input-custom form-control','id'=>'pcqCost','v-model'=>'smvCostModel.pcqCost']) !!}
<p class="error" v-if="pcqCost_error">#{{pcqCost_error}}</p>
</td>
<td>
{!! Form::text('ironCost','',['class'=>'input-custom form-control','id'=>'ironCost','v-model'=>'smvCostModel.ironCost']) !!}
<p class="error" v-if="ironCost_error">#{{ironCost_error}}</p>
</td>
<td>
{!! Form::text('sewingCost','',['class'=>'input-custom form-control','id'=>'sewingCost','v-model'=>'smvCostModel.sewingCost']) !!}
<p class="error" v-if="sewingCost_error">#{{sewingCost_error}}</p>
</td>
<td>
{!! Form::text('packingCost','',['class'=>'input-custom form-control','id'=>'packingCost','v-model'=>'smvCostModel.packingCost']) !!}
<p class="error" v-if="packingCost_error">#{{packingCost_error}</p>
</td>
<td></td>
<td>{!! Form::button('Save', ['class' => 'btn btn-primary', 'v-on:click.prevent'=>'saveSMVcost();'] ) !!}</td>
</tr>
{!! Form::close() !!}
JS:
saveSMVcost: function () {
/*var request = new XMLHttpRequest();*/
var form = document.querySelectorAll("#smv-cost-form");
var formData = new FormData(form);
var base_url = window.location.origin;
var page_url = base_url + '/bca/smv-cost-action';
$('#ajax-call-effect').show();
console.log(formData.knittingCost);
alert(formData.knittingCost);
axios.post(page_url, formData).then(
function (response) {
$('#ajax-call-effect').hide();
if (response.data.errors) {
response.data.errors.knittingCost ? app.knittingCost_error = response.data.errors.knittingCost[0] : app.knittingCost_error = '';
response.data.errors.linkingCost ? app.linkingCost_error = response.data.errors.linkingCost[0] : app.linkingCost_error = '';
response.data.errors.tremingCost ? app.tremingCost_error = response.data.errors.tremingCost[0] : app.tremingCost_error = '';
response.data.errors.mendingCost ? app.mendingCost_error = response.data.errors.mendingCost[0] : app.mendingCost_error = '';
response.data.errors.washCost ? app.washCost_error = response.data.errors.washCost[0] : app.washCost_error = '';
response.data.errors.pcqCost ? app.pcqCost_error = response.data.errors.pcqCost[0] : app.pcqCost_error = '';
response.data.errors.ironCost ? app.ironCost_error = response.data.errors.ironCost[0] : app.ironCost_error = '';
response.data.errors.sewingCost ? app.sewingCost_error = response.data.errors.sewingCost[0] : app.sewingCost_error = '';
response.data.errors.packingCost ? app.packingCost_error = response.data.errors.packingCost[0] : app.packingCost_error = '';
}
else {
/* $('#knittingCost').val('');
$('#linkingCost').val('');
$('#tremingCost').val('');
$('#mendingCost').val('');
$('#washCost').val('');
$('#pcqCost').val('');
$('#ironCost').val('');
$('#sewingCost').val('');
$('#packingCost').val('');*/
app.knittingCost_error = '';
app.linkingCost_error = '';
app.tremingCost_error = '';
app.mendingCost_error = '';
app.washCost_error = '';
app.pcqCost_error = '';
app.ironCost_error = '';
app.sewingCost_error = '';
app.packingCost_error = '';
app.showNotification('top', 'center', response.data.status, response.data.message);
}
})
}
There are a few ways, but one would be to json_encode the object or array, as shown below. I ususally set a global object and then grab that in my Javascript, but you could technically set this value directly to a JS variable. Use #php and #endphp if you want more blade-like syntax.
<!-- Global App Object -->
<script>
window.App = <?php echo json_encode(
'isAdmin' => user()->isAdmin(),
'credentials' => user()->softphone()->credentials(),
'forwardToCellphone' => user()->forward_to_cellphone,
'status' => (new App\Http\Controllers\Users\UserStatusController)->details(),
); ?>;
</script>
I am new to Ajax I was following tutorial to send data to db using Ajax
here is my form
{!! Form::open(array('url'=>'admin/blog', 'method'=>'post', 'files'=>'true')) !!}
<div class="box-body">
<div class="form-group">
{!! Form::label('title', 'Title') !!}
{!! Form::text('title', '', array('placeholder'=>'Blog title', 'class'=>'form-control')) !!}
</div>
<div class="form-group">
{!! Form::label('paragraph', 'Blog Content') !!}
{!! Form::textarea('paragraph', '', array('class'=>'form-control', 'placeholder'=>'Enter Paragraph...', 'rows'=>3)) !!}
<script>
CKEDITOR.replace('paragraph', {
uiColor: '#9AB8F3',
stylesSet: 'my_custom_style'
});
</script>
</div>
<div class="form-group">
{!! Form::label('image', 'Main Image') !!}
{!! Form::file('image') !!}
<p class="help-block">Please review the upload instructions in 'Reminder!'</p>
</div>
</div>
<div class="box-footer">
{!! Form::submit('Add', array('class'=>'btn btn-primary', 'onClick'=>'send(event)')) !!}
</div>
{!! Form::close() !!}
and this is the Ajax I used
<script type="text/javascript">
function send(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "{{ 'admin/blog' }}",
data: {
title: $("#title").val(),
paragraph: $("#paragraph").val(),
image: $("#image").val(),
_token: "{{ Session::token() }}"
},
success:function(result)//we got the response
{
alert('Successfully called');
},
error:function(exception){alert('Exeption:'+exception);}
})
}
</script>
and here is the controller
public function store(Request $request)
{
$this->validate($request, [
'title' => 'required',
'paragraph' => 'required|min:100',
'image' => 'required|image|mimes:jpeg,png',
]);
$add = new Blog();
if ($request->hasFile('image')) {
$image = $request->file('image');
$filename = time() . '.' . $image->getClientOriginalExtension();
Image::make($image)->resize(600, 390)->save(public_path('images/blog/' . $filename));
Image::make($image)->fit(335, 219)->save(public_path('images/blog/thumbs-' . $filename));
$add->image = $filename;
}
$add->title = $request->title;
$add->paragraph = $request->paragraph;
$add->addBy = \Auth::user()->name;
$add->save();
if ($request->ajax()) {
return response()->json();
}
return \Redirect::back();
}
when I try to click add I got
Error Exeption:[object Object]
Edit
In my routes I was using resource add new Route with POST method
Route::resource('blog', 'BlogController');
Route::post('blog', 'BlogController#store');
Changed the Ajax URL and the error results
url: "{{ url('admin/blog/store') }}",
error:function(exception){console.log(exception)}
in my console got this error
Object { readyState: 4, getResponseHeader:
.ajax/x.getResponseHeader(), getAllResponseHeaders:
.ajax/x.getAllResponseHeaders(), setRequestHeader:
.ajax/x.setRequestHeader(), overrideMimeType:
.ajax/x.overrideMimeType(), statusCode: .ajax/x.statusCode(), abort:
.ajax/x.abort(), state: .Deferred/d.state(), always:
.Deferred/d.always(), then: .Deferred/d.then(), 11 more… }
I had the same issue, solved by JSON.stringify(dataObject) before sending AJAX request.
I have a problem here. I am developing my web application and I want it to connect to my API through ajax. I am trying to send an image to my api through ajax from my form in the client side, which is the web.
So, here's my form in the client side..
{{ Form::open(['enctype' => "multipart/form-data", 'id' => 'addplant', 'method' => 'POST', 'files' => true, 'class' => 'col s12']) }}
{{ csrf_field() }}
<div class="row" style="margin-top:10%;">
<div class="col s12 center">
<img class="circle" id="image_url" src=""></a>
{!! Form::file('image_url', array('id' => 'image', 'class' => 'form-control')) !!}
</div>
</div>
<div class="row">
<div class="input-field col s6">
{{ Form::text('herbal_name', null, array('id' => 'herbal_name', 'class' => 'form-control validate')) }}
{{ Form::label('herbal_name', 'Herbal Name') }}
</div>
<div class="input-field col s6">
{{ Form::text('scientific_name', null, array('id' => 'scientific_name', 'class' => 'form-control validate')) }}
{{ Form::label('scientific_name', 'Scientific Name') }}
</div>
</div>
{{ Form::submit('Add plant', array('class' => 'btn btn-primary right add')) }}
{{ Form::close() }}
Here's my ajax, still in the client side
<script type="text/javascript">
$(".add").click(function() {
$.ajax({
url: 'http://127.0.0.1/identificare_api/public/api/plants',
data: new FormData($("#addplant")[0]),
type: "POST",
success: function( msg ) {
console.log(msg);
},
error: function(){
alert('pangit');
}
});
});
</script>
EDIT: and in my api, I just have this one
return json_encode($request->file('image_url'));
What am I missing here? Did I missed something?
UPDATE: I tried to apply the answer of #bfcior but when I try to console.log(base64img), it will return this very long string and it's longer than you expected.
click for image
I'm not entirely sure if this is the issue but aren't you supposed to be using a button instead of a submit? I'd imagine using a submit is preventing the ajax from working because the form is being submitted to the server for processing.
EDIT: What happens when you click the submit button? Telling us will help stackoverflow users diagnose the problem.
You handle the file by using:
$request->file('image_url');
https://laravel.com/docs/5.3/requests#files
Another approach is to convert img into base64 and pass it as a param. Then in your controller/route you can decode the base64 and save to a file (if is needed).
{{ Form::open(['enctype' => "multipart/form-data", 'id' => 'addplant', 'method' => 'POST', 'files' => true, 'class' => 'col s12']) }}
<div class="row" style="margin-top:10%;">
<div class="col s12 center">
<img class="circle" id="image_url" src=""></a>
{!! Form::file('image_url', array('id' => 'image', 'class' => 'form-control')) !!}
</div>
</div>
<div class="row">
<div class="input-field col s6">
{{ Form::text('herbal_name', null, array('id' => 'herbal_name', 'class' => 'form-control validate')) }}
{{ Form::label('herbal_name', 'Herbal Name') }}
</div>
<div class="input-field col s6">
{{ Form::text('scientific_name', null, array('id' => 'scientific_name', 'class' => 'form-control validate')) }}
{{ Form::label('scientific_name', 'Scientific Name') }}
</div>
</div>
{{ Form::submit('Add plant', array('class' => 'btn btn-primary right add')) }}
{{ Form::close() }}
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}'
}
});
var base64img = null;
$(document).ready(function() {
$('#image').change(function(){
var file = this.files[0];
var reader = new FileReader();
reader.addEventListener("load", function () {
base64img = reader.result;
}, false);
if (file) {
reader.readAsDataURL(file);
}
});
$(".add").click(function(e) {
e.preventDefault();
$.ajax({
url: 'http://127.0.0.1:8000/identificare_api/public/api/plants',
data: $("#addplant").serialize() + '&image_url=' + base64img,
type: "POST",
success: function( msg ) {
console.log(msg);
},
error: function(){
alert('pangit');
}
});
});
});
</script>
and route
Route::post('identificare_api/public/api/plants', function (Request $request) {
return json_encode($request->all());
});
in my index.balde.php
{{ Form::open(['url'=>'/crm/promotion/multi_destroy', 'method'=>'POST', 'id'=>'form_delete_all','class'=>'form-horizontal']) }}
#foreach ($promotions as $promotion)
<tr class="odd gradeX data-table-item">
<td><input type="checkbox" class="multidel" name="multidel_{{$promotion->id}}"></td>
<td>{{$promotion->name}}</td>
<td>{{$promotion->i_name}}</td>
<td>{{ substr($promotion->descr, 0, 100)}}...</td>
<td>{{$promotion->start}}</td>
<td>{{$promotion->end}}</td>
<td>
#if(isset(Session::get('permissions')[$module]))
{{ Render::tableButtons(Session::get('permissions')[$module], $actions['table'] ,array("[ID]" => $promotion->id), array() ) }}
#endif
</td>
</tr>
#endforeach
{{Form::close()}}
when one action change i will show by
if($('#ed').val()!="" && $('#sd').val()=="")
{
$.ajax({
type: "GET",
dataType: "json",
url: '/crm/promotion/promotion_search_end',
data:'end='+$('#ed').val(),
beforeSend: function(){
},
success: function (data)
{
//$('.data-table-item').html('');
$('.data-table-item').empty();
console.log(data);
$.each(data, function(index, item_data)
{
//console.log(item_data.id);
$('#data-table').footable();
$('#data-table').append('<tr class="odd gradeX data-table-item"><td><input type="checkbox" class="multidel" name="multidel_'+item_data.id+'"></td><td>'+item_data.name+'</td><td>'+item_data.i_name+'</td><td>'+item_data.descr+'</td><td>'+item_data.start+'</td><td>'+item_data.end+'</td><td></td></tr>');
});
},
complete: function(){
// do the following after success is done.
},
error: function(){
// do the following if there is error.
}
});
}
I want to use in ajax. How can i use?
#if(isset(Session::get('permissions')[$module]))
{{ Render::tableButtons(Session::get('permissions')[$module], $actions['table'] ,array("[ID]" => $promotion->id), array() ) }}
#endif
You can use laravel blade code in javascript. In your case, you can use like the following
<script>
#if(isset(Session::get('permissions')[$module]))
var value = {{ Render::tableButtons(Session::get('permissions')[$module], $actions['table'] ,array("[ID]" => $promotion->id), array() ) }}
alert(value);
#endif
</script>