Laravel 5.2 : Error Exeption:[object Object] - php

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.

Related

Image upload Laravel 5.3 using ajax

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

Laravel post form error

I'm having a problem for the first time when i submit a form.
When i submit the form it doesn't go to post route and i don't know why.
my post route is that:
Route::post('/app/add-new-db', function()
{
$rules = array(
'name' => 'required|min:4',
'file' => 'required'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
// get the error messages from the validator
$messages = $validator->messages();
// redirect our user back to the form with the errors from the validator
return Redirect::to('app/add-new-db')
->withErrors($validator);
}
else
{
$name = Input::get('name');
$fname = pathinfo(Input::file('file')->getClientOriginalName(), PATHINFO_FILENAME);
$fext = Input::file('file')->getClientOriginalExtension();
echo $fname.$fext;
//Input::file('file')->move(base_path() . '/public/dbs/', $fname.$fext);
/*
DB::connection('mysql')->insert('insert into databases (name, logotipo) values (?, ?)',
[$name, $fname.$fext]);
*/
//return Redirect::to('app/settings/');
}
});
And my html:
<div class="mdl-cell mdl-cell--12-col content">
{!! Form::open(['url'=>'app/add-new-db', 'files'=>true]) !!}
<div class="mdl-grid no-verticall">
<div class="mdl-cell mdl-cell--12-col">
<h4>Adicionar Base de Dados</h4>
<div class="divider"></div>
</div>
<div class="mdl-cell mdl-cell--6-col">
<div class="form-group">
{!! Form::label('name', 'Nome: ') !!}
{!! Form::text('name', null, ['id'=> 'name', 'class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('image', 'Logotipo:') !!}
{!! Form::file('image', ['class'=>'form-control']) !!}
#if ($errors->has('image'))
<span class="error">{{ $errors->first('image') }}</span>
#endIf
</div>
<div class="form-group">
{!! Form::submit('Adicionar', ['id'=>'add-new-db', 'class'=>'btn btn-default']) !!}
<p class="text-success"><?php echo Session::get('success'); ?></p>
</div>
</div>
</div>
{!! Form::close() !!}
</div>
I'm loading this from from a jquery get:
function addDB()
{
$( "#settings-new-db" ).click(function(e)
{
$.get('/app/add-new-db', function(response)
{
$('.content-settings').html("");
$('.content-settings').html(response);
componentHandler.upgradeDom();
});
e.preventDefault();
});
}
When i try to submit the form i'm getting 302 found in network console from chrome.
I'm doing forms at this way and it is happens for the first time. Anyone can help me?
Thanks
Fix the name attribute for your image upload field. You refer it as image in the form but you are trying to fetch it as file in your controller.

Dropzone shows upload success but file is not uploaded in Laravel 5

I'm still learning Laravel and trying to build some sort of an article management system. As part of form for inserting new articles I want to also upload multiple pictures of them. The upload shows success, yet there is no file in uploads folder. Here is my form code:
{!! Form::open(['route' => 'admin_artikli.store', 'class' => 'dropzone', 'id' => 'create_artikal', 'enctype' => 'multipart/form-data' ]) !!}
<div class="form-group">
{!! Form::label('Firma', 'Firma') !!}
{!! Form::text('firma_id', Input::old('firma_id'), array('class' => 'form-control')) !!}
</div>
<div class="form-group">
{!! Form::label('Naziv', 'Naziv') !!}
{!! Form::text('naziv', Input::old('naziv'), array('class' => 'form-control')) !!}
</div>
<div class="form-group">
{!! Form::label('Opis', 'Opis') !!}
{!! Form::text('opis', Input::old('opis'), array('class' => 'form-control')) !!}
</div>
<div class="form-group">
{!! Form::label('Cijena', 'Cijena') !!}
{!! Form::text('cijena', Input::old('cijena'), array('class' => 'form-control')) !!}
</div>
<div class="form-group">
{!! Form::label('kolicina', 'kolicina') !!}
{!! Form::text('kolicina', Input::old('kolicina'), array('class' => 'form-control')) !!}
</div>
<div class="form-group">
{!! Form::label('dostupnost', 'dostupnost') !!}
{!! Form::text('dostupnost', Input::old('dostupnost'), array('class' => 'form-control')) !!}
</div>
<div class="form-group">
{!! Form::select('aktivan', array('D' => 'Aktivan', 'N' => 'Neaktivan'), 'D') !!}
</div>
<div class="form-group">
{!! Form::select('aktivan', array('D' => 'Aktivan', 'N' => 'Neaktivan'), 'D') !!}
</div>
{!! Form::submit('Kreiraj artikal', array('class' => 'btn btn-primary', 'id' => 'create_artikal_submit')) !!}
{!! Form::close() !!}
My routes.php(showing only relevant):
Route::post('/upload', 'ArtikalAdminController#upload');
Route::resource('admin_artikli', 'ArtikalAdminController');
My controller methods for store and upload:
public function upload(){
$input = Input::all();
$rules = array(
'file' => 'image|max:3000'
);
echo "eldaaaaaaaaaaaaaaaaaaaaaaaaar";
$validation = Validator::make($input, $rules);
if ($validation->fails())
{
return Response::make($validation->errors->first(), 400);
}
$file = Input::file('file');
$extension = File::extension($file['name']);
$directory = public_path().'uploads/'.sha1(time());
$filename = sha1(time().time()).".{$extension}";
$file->move($directory, $filename);
$upload_success = Input::file('file', $directory, $filename)->move($directory, $filename);;
echo $directory;
if( $upload_success ) {
return Response::json('success', 200);
} else {
return Response::json('error', 400);
}
}
public function store(Request $request)
{
$artikal = new Artikal;
$artikal->firma_id = Input::get('firma_id');
$artikal->naziv = Input::get('naziv');
$artikal->sifra = Input::get('sifra');
$artikal->opis = Input::get('opis');
$artikal->cijena = Input::get('cijena');
$artikal->kolicina = Input::get('kolicina');
$artikal->dostupnost = Input::get('dostupnost');
$artikal->aktivan = Input::get('aktivan');
$artikal->save();
Session::flash('flash_message', 'Uspješno unesen artikal!');
//return redirect()->back();
}
Finally, dropzone options I am currently using:
Dropzone.options.createArtikal = { // The camelized version of the ID of the form element
// The configuration we've talked about above
autoProcessQueue: false,
uploadMultiple: true,
parallelUploads: 10,
maxFiles: 10,
// The setting up of the dropzone
init: function() {
var myDropzone = this;
// First change the button to actually tell Dropzone to process the queue.
var element = document.getElementById('create_artikal_submit');
var form = document.getElementById('create_artikal');
element.addEventListener("click", function(e) {
// Make sure that the form isn't actually being sent.
e.preventDefault();
e.stopPropagation();
myDropzone.processQueue();
});
// Listen to the sendingmultiple event. In this case, it's the sendingmultiple event instead
// of the sending event because uploadMultiple is set to true.
this.on("sendingmultiple", function() {
// Gets triggered when the form is actually being sent.
// Hide the success button or the complete form.
});
this.on("successmultiple", function(files, response) {
// Gets triggered when the files have successfully been sent.
// Redirect user or notify of success.
form.submit();
});
this.on("errormultiple", function(files, response) {
// Gets triggered when there was an error sending the files.
// Maybe show form again, and notify user of error
});
}
}
I know this is lacking many things, but I'm trying to go on step at a time and I'm stuck here. When I check the network tab of dev tools I see XHR requests are 200 OK, but yet I see no file.
You forgot to write 'files' => true in form, update form & try.
{!! Form::open(['route' => 'admin_artikli.store', 'class' => 'dropzone', 'id' => 'create_artikal', 'files'=>true, 'enctype' => 'multipart/form-data' ]) !!}

CKEDITOR - Update / Create of products fails using AJAX in Laravel 5

I want to store the html content written in ckeditor textarea field in my database table called products using AJAX.
Everything gets inserted and/or updated successfully leaving the product description.
product_edit.blade.php
{!! Form::open(['files' => 'true', 'autocomplete' => 'off', 'name' => 'formEditProductGeneralInfo', 'id' => 'formEditProductGeneralInfo']) !!}
<div class="form-group">
{!! Form::label('code', 'Code:') !!}
{!! Form::text('code', $product->code, ['class' => 'form-control input-sm']) !!}
</div>
<div class="form-group">
{!! Form::label('name', 'Name:') !!}
{!! Form::text('name', $product->name, ['class' => 'form-control input-sm']) !!}
</div>
<div class="form-group">
{!! Form::label('description', 'Product Description:') !!}
{!! Form::textarea('description', $product->description, ['class' => 'form-control input-sm ckeditor', 'rows' => 3, 'id' => 'prdDescription']) !!}
</div>
<div class="form-group">
{!! Form::label('price', 'Price:') !!}
{!! Form::text('price', $product->price, ['class' => 'form-control input-sm']) !!}
</div>
<div class="form-group">
{!! Form::label('image_file', 'Image:') !!}
{!! Form::file('image_file', ['id' => 'image_file', 'class' => 'form-control input-sm']) !!}
</div>
<div class="form-group">
{!! Form::submit( 'Update', ['class' => 'btn btn-primary btn-block', 'id' => 'btnEditProductGeneral'] ) !!}
</div>
{!! Form::close() !!}
ajax
$('form[name="formEditProductGeneralInfo"]').submit(function(e) {
var inputData = new FormData($(this)[0]);
var message = CKEDITOR.instances.prdDescription.getData();
console.log(message);
console.log(inputData);
$.ajax({
url: '{{ url(' / admin / products / update / general ', $product->id) }}',
type: 'POST',
data: inputData,
async: true,
success: function(m) {
if (m.status === 'success') {
toastr.success(m.msg, 'Successs!');
} else {
toastr.error(m.msg, msg.status);
}
},
error: function(data) {
if (data.status === 422) {
var errors = data.responseJSON;
var errorsHtml = '<div class="alert alert-danger"><ul>';
errorsHtml += '<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>';
$.each(errors, function(key, value) {
errorsHtml += '<li>' + value[0] + '</li>';
});
errorsHtml += '</ul></div>';
$('.errors').html(errorsHtml);
}
},
cache: false,
contentType: false,
processData: false
});
e.preventDefault();
return false;
});
How am I suppose to save the description's html content in the database ?
Any help is highly appreciated. Thanks.
I have solved it. The issue was that I had to check for the instances of CKEDITOR in the for loop which I had not checked. So I added the for loop to check the instances, and everything works completely fine.
ajax updated:
$('form[name="formEditProductGeneralInfo"]').submit(function(e) {
for (instance in CKEDITOR.instances) {
CKEDITOR.instances[instance].updateElement();
}
var inputData = new FormData($(this)[0]);
$.ajax({
url: '{{ url(' / admin / products / update / general ', $product->id) }}',
type: 'POST',
data: inputData,
async: true,
success: function(m) {
if (m.status === 'success') {
toastr.success(m.msg, 'Successs!');
} else {
toastr.error(m.msg, msg.status);
}
},
error: function(data) {
if (data.status === 422) {
var errors = data.responseJSON;
var errorsHtml = '<div class="alert alert-danger"><ul>';
errorsHtml += '<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>';
$.each(errors, function(key, value) {
errorsHtml += '<li>' + value[0] + '</li>';
});
errorsHtml += '</ul></div>';
$('.errors').html(errorsHtml);
}
},
cache: false,
contentType: false,
processData: false
});
e.preventDefault();
return false;
});
Send var message with the AJAX request. and then in your controller check it and save. :)

Laravel 4 image upload

Hi, I'm trying to make an image upload via laravel, everything is working but now I want to change the upload to an jquery upload instead but then I get an 500 internal server error
so when I handle things with Jquery it fails. Anyone knows what the problem might be?
html:
{{ Form::open(array('url' => '../public/posts/add', 'class'=>'form-horizontal', 'role' => 'form', 'id' => 'addPin', 'files' => true)) }}
<div id="validation-errors" class="alert alert-danger" hidden>
<p>Some errors occured</p>
<ul></ul>
</div>
<!-- Image Type -->
<span id="type-image" class="type-media">
<div class="form-group">
<label class="col-sm-3 control-label">Title</label>
<div class="col-sm-9">
{{ Form::text('Image-title', null, array('class' => 'form-control', 'placeholder' => '')) }}
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Choose file</label>
<div class="col-sm-9">
{{ Form::file('Image-file') }}
<p class="help-block">Only .jpg, .png, .gif, .bmp allowed.</p>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Description</label>
<div class="col-sm-9">
{{ Form::textarea('Image-description', null, array('class' => 'form-control', 'rows' => '3')) }}
</div>
</div>
</span>
<div class="modal-footer">
{{ Form::submit('Close', array('class' => 'btn btn-default', 'data-dismiss' => 'modal')) }}
{{ Form::submit('Pin it, babe!', array('class' => 'btn btn-info')) }}
</div>
{{ Form::close() }}
Jquery
addPin.on('submit', function() {
event.preventDefault();
var errorForm = addPin.find('div#validation-errors');
$.ajax({
url: '../public/posts/add',
type: 'post',
cache: false,
data: addPin.serialize(),
beforeSend: function() {
errorForm.hide();
errorForm.find("ul").empty();
},
success: function(data) {
if(data.success == false) {
var arr = data.errors;
console.log(arr);
$.each(arr, function(index, value){
if (value.length != 0){
errorForm.find("ul").append('<li>'+ value +'</li>');
}
});
errorForm.show();
} else {
location.reload();
}
},
error: function() {
alert('Something went to wrong.Please Try again later...');
}
});
return false;
} );
PHP
public function postAdd(){
if (Auth::check()){
$rules = array(
'Image-title' => 'Required|Min:3|Max:255|alpha_spaces',
'Image-description' => 'Required|Min:3',
'Image-file' => 'image',
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return \Response::json(['success' => false, 'errors' => $validator->getMessageBag()->toArray()]);
} else {
$post = Post::create(array(
'user_id' => Auth::user()->id,
'title' => Input::get('Image-title'),
'description' => Input::get('Image-description'),
'type' => 'Image',
));
$file = Input::file('Image-file');
$destinationPath = 'img/';
$extension = $file->getClientOriginalExtension();
$filename = 'usr_'. Auth::user()->id . '_post'.$post->id .'.'. $extension;
$file->move($destinationPath, $filename);
$post->imgLocation = $filename;
$post->save();
DB::table('board_post')->insert(['board_id' => 2, 'post_id' => $post->id]);
return \Response::json(['success' => true]);//*/
}
}
}
You should have an error in your app/storage/logs/laravel.log file stating the exact error. Setting PHP to show all errors is preferable in a development environment tho, so you might want to consider turning those on, so you'll get a more descriptive message than just "500 Internal Server Error".
Check you upload_max_filesize in php.ini
Echo ini_get ("upload_max_filesize");
See this
The problem was due the fact that Jquery/JS don't really support Image upload
I fixed the problem by when you click on the button, the form get's validated (via ajax) and show the errors when there are, otherwise it does the normal form sending (the one if I wouldn't do the event.prefentdefault())
this works for now, prehaps I'll have a second look at it to make it completly AJax, but probably not :)

Categories