Post Image with ajax in laravel 5.6 - javascript

I want to create an upload adapter for ckeditor,
I have an issue in my laravel ajax application,
here is my code.
export default class UploadAdapter {
constructor(loader) {
this.loader = loader;
}
upload() {
return new Promise((resolve, reject) => {
let data = new FormData();
data.append('upload', this.loader.file);
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: '/loadImage',
type: 'POST',
data: data,
dataType: 'json',
async:false,
processData: false,
contentType: false,
success: function (data) {
console.log(data.get('upload'));
},
error: function (request, status, error) {
console.log(error);
}
});
});
}
}
I stuck in responding with ajax to laravel controller.
Here is my Controller function:
try {
$file = $request->file('upload');
$uploader = MediaUploader::fromSource($file);
$uploader->setAllowedMimeTypes(['image/jpeg', 'image/gif', 'image/png']);
$uploader->setAllowedExtensions(['jpg', 'jpeg', 'png', 'gif']);
$media = $uploader->upload();
return response()->json([
'uploaded' => true,
'url' => $media->getUrl()
]);
} catch (\Exception $e) {
return response()->json(
[
'uploaded' => false,
'error' => [
'message' => $e->getMessage()
]
]
);
}
Here is my error
SyntaxError: Unexpected end of JSON input
at parse (<anonymous>)
at ajaxConvert (app.js:11826)
at done (app.js:12294)
at XMLHttpRequest.<anonymous> (app.js:12587)
What is the error in my code ???
I cant get the file information in laravel controller..
How can i solve this issue...? Help me Please!!!

You have data - empty
JSON.parse(''); // SyntaxError: Unexpected end of input
Add verification:
data = data != "" ? $.parseJSON(data) : {};

Related

How to get to a laravel route using jquery ajax

I am trying to put to a method in a controller using ajax but I keep getting a 404 not found.
My JS:
var dataroomForm = $('#dataroomForm');
var dataroomId = $('#dataroomId').val();
var saveButton = $('.saveDataroom');
saveButton.click(function(e) {
var dataroomData = dataroomForm.serialize();
e.preventDefault();
console.log(dataroomData);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: '/dataroom/' + dataroomId,
type: 'PUT',
data: {
'dataroom': dataroomData
},
dataType: 'json',
success: function (data) {
console.log(data);
},
error: function (request, error) {
alert("Request: " + JSON.stringify(request));
}
});
});
The route I am trying to trigger:
Route::put('dataroom/{dataroom}', ['as' => 'update', 'uses' => 'DataroomController#update']);
And update method (not really relevant I think but posting for complete view)
public function update(DataroomRequest $request, $id, MailService $mailService)
{
$dataroom = Dataroom::withoutGlobalScope(ActiveScope::class)->find($id);
if (is_null($dataroom)) {
\Flash::error('Dataroom niet gevonden!');
return redirect(route('admin.dataroom.index'));
}
$dataroom->fill($request->all());
$dataroom->save();
$dataroom->handleUploader($request, 'image');
if ($request->has('send_update')) {
$changes = $request->input('changes');
foreach ($dataroom->accounts as $account) {
$mailService->sendUpdate($account, $dataroom, $changes);
}
if (empty($changes)) {
$changes = 'Dataroom gewijzigd';
}
$dataroom->log($changes);
}
\Flash::success('De wijzigingen voor <strong>' . $dataroom->title . '</strong> zijn opgeslagen');
return redirect()->route('admin.dataroom.index');
}
In my network tab I get:
Request URL: http://website.nl.test/dataroom/26
Request Method: PUT
Status Code: 404 Not Found
And as response : exception: "Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException"
What am I doing wrong?
I don't see any issues in your code try using the command in your terminal php artisan optimize:clear in root folder this will flush/remove the application cache, route cache, and config cache altogether.

wordpress ajax rest api ("code":"rest_invalid_json","message":"Invalid JSON body passed.")

I dont understand what i did wrong, can anyone give me a suggestion on what causes the above error below is my code. I can confirm that, i am hitting the route, succesfully because the code inside get it executed. I am also adding the 1 value at the end, to be passed it to json as per wp_send_json_success. At this point i dont know what to next, can anyone explaint to me, on what is going on?
route.php
function update_employee_photo($request){
global $wpdb;
$data_with_photo = array(
'photo' => $request['photo'],
'photo_privacy' => $request['photoPrivacy'],
'photo_description' => $request['photoDescription']
);
$data_null_photo = array(
'photo_privacy' => $request['photoPrivacy'],
'photo_description' => $request['photoDescription']
);
$data = ($request['photo'] != "null") ? $data_with_photo : $data_null_photo;
$where = array('wp_user_id' => get_current_user_id());
$result = $wpdb->update("aupair_registered_employee", $data, $where);
if($result){
wp_send_json_success($result, 200, 1);
} else {
wp_send_json_error($wpdb->last_query);
}
die();
}
add_action('rest_api_init', function(){
register_rest_route( 'activeAupair/v1', '/updateEmployeePhoto', [
'methods' => 'POST',
'callback' => 'update_employee_photo'
]);
});
file.js
$.ajax({
type: 'POST',
url: myAjax.restURL + 'activeAupair/v1/updateEmployeePhoto',
contentType: 'application/json',
datatype: 'json',
data: {
photo: photo,
photoPrivacy: getPhotoPrivacy(),
photoDescription: getPhotoDescription()
},
beforeSend: function (xhr) {
xhr.setRequestHeader('X-WP-Nonce', myAjax.nonce);
},
success: function(response){
console.log('TYPE OF ', typeof response);
console.log('RESPONSE ', response);
msg.empty();
msg.append($('<p id="required"></p>').text('Updated'));
uploadBtn.attr('value', 'Update');
uploadBtn.attr('disabled', false);
},
error: function (xhr, ajaxOptions, thrownError) {
},
complete: function(data){
console.log('COMPLETE ', data);
}
});
As per the wordpress wp_send_json_success() function expect third parameter 1(default 0) to encode it into JSON format (see the reference). So you need to pass the status code as second parameter and 1 for the JSON object.
wp_send_json_success($result, 200, 1);

How to delete image with ajax in laravel

I am trying to delete a record from my products table, each product has an image. I don't know how to delete the image from the file where it is stored.
Product.js
$(document).ready(function() {
$("#btn-delete").click(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'DELETE',
url: '/product/' + $("#frmDeleteProduct input[name=product_id]").val(),
dataType: 'json',
success: function(data) {
$("#frmDeleteProduct .close").click();
window.location.reload();
},
error: function(data) {
console.log(data);
}
});
});
});
function deleteProductForm(product_id) {
$.ajax({
type: 'GET',
url: '/product/' + product_id,
success: function(data) {
$("#frmDeleteProduct #delete-title").html("¿Do you want to delete this product (" + data.products.name + ")?");
$("#frmDeleteProduct input[name=product_id]").val(data.products.id);
$('#deleteProductModal').modal('show');
},
error: function(data) {
console.log(data);
}
});
}
ProductController.php
I read that I need to put something like this in my controller File::delete('img/products/' . $image); but I don't now how.
public function destroy($id)
{
//File::delete('img/products/' . $image);
$products = Product::destroy($id);
return response()->json([
'error' => false,
'products' => $products,
], 200);
}
You need to pass as a parameter to File::delete() the full path when your image was save. For example, if your images were in a laravel storage path in the subdirectory img/products/, and the name of the image is the id of the product with the .jpg extension, you can do this:
public function destroy($id)
{
$fullImgPath = storage_path("img/products/$id.jpg");
if(File::exists($fullImgPath)) {
File::delete($fullImgPath);
}
$products = Product::destroy($id);
return response()->json([
'error' => false,
'products' => $products,
], 200);
}
But if you have the name of the image in your Product model, you can do this:
public function destroy($id)
{
$product = Product::find($id);
$fullImgPath = storage_path("img/products/".$product->image_name);
if(File::exists($fullImgPath)) {
File::delete($fullImgPath);
}
$product->delete();
return response()->json([
'error' => false,
'products' => $product->id,
], 200);
}

Formdata is empty - laravel 5.4

Hi Friends,
I am trying to upload an image using ajax in laravel 5.4
Issue :
Formdata is empty on server-side
CODE :
View :
<form role="form" action="{{route('auth.upload')}}" method="post" enctype="multipart/form-data" id="form3">
{{ csrf_field() }}
<h3>Upload Logo</h3>
<div class="form-group">
<label class="custom-file upload-image">
<input type="file" id="image" name="image" class="custom-file-input">
<span class="custom-file-control"></span>
</label>
</div>
<button type="submit" class="btn btn-upload">Save Image</button>
</form>
JS :
$('#form3').on('submit',function(e){
e.preventDefault();
var url = $(this).attr('action'),
post = $(this).attr('method'),
data = new FormData(this);
$.ajax({
url: url,
method: post,
data: data,
success: function(data){
console.log(data);
},
error: function(xhr, status, error){
alert(xhr.responseText);
},
processData: false,
contentType: false
});
});
Route :
Route::post('home/form3', 'HomeController#store')->name('auth.upload');
Controller :
public function store(Request $request){
if ($request->ajax()) {
return $request->all(); // THIS IS RETURNING EMPTY OBJECT
if ($request->hasFile('image')) {
$name = $request->image->getClientOriginalName();
$request->image->storeAs('public/upload',$name);
$company = new Company;
$url = Storage::url($name);
$company->update(['image'=>$url]);
return response(['msg'=>'image uploaded']);
}else{
return response(['msg'=>'No file has selected']);
}
}
}
return response from server side is :
Object {_token: "zFKgoBkdjaIswMG5X0fOyVtaGSYMs84iPDtJA4F5", image: Object}
image : Object
_token : "zFKgoBkdjaIswMG5X0fOyVtaGSYMs84iPDtJA4F5"
__proto__ : Object
I can see only token is returning but not data of uploaded image. If I submit form without using ajax then it is working fine.
Output if submitted without using ajax (this is the output I am expecting even submitted using ajax):
array:2 [▼
"_token" => "eVEjl9UW4rU69oz1lIIiuNABZVpRJFldDST02Nje"
"image" => UploadedFile {#229 ▼
-test: false
-originalName: "empty-normal.png"
-mimeType: "image/png"
-size: 85494
-error: 0
#hashName: null
path: "C:\xampp\tmp"
filename: "php917E.tmp"
basename: "php917E.tmp"
pathname: "C:\xampp\tmp\php917E.tmp"
extension: "tmp"
realPath: "C:\xampp\tmp\php917E.tmp"
aTime: 2017-05-18 11:17:11
mTime: 2017-05-18 11:17:11
cTime: 2017-05-18 11:17:11
inode: 0
size: 85494
perms: 0100666
owner: 0
group: 0
type: "file"
writable: true
readable: true
executable: false
file: true
dir: false
link: false
linkTarget: "C:\xampp\tmp\php917E.tmp"
}
]
Can any one help me in solving this issue ?
**THANKS IN ADVANCE...
Try this, it will help you.
$(document).on('submit', 'yourformId', function (event) {
event.stopPropagation();
event.preventDefault();
var data = new FormData($(this)[0]);
if (xhr && xhr.readyState !== 400 && xhr.status !== 200) {
xhr.abort();
}
var xhr = $.ajax({
url: "urltoUpload",
method: "POST",
cache: false,
data: data,
contentType: false, // NEEDED, DON'T OMIT THIS (requires jQuery 1.6+)
processData: false, // NEEDED, DON'T OMIT THIS
// dataType: 'json',
statusCode: {
404: function () {
alert("status message")
},
500: function () {
alert("server down");
}
},
beforeSend: function (jqXHR, setting) {
if (setting.status !== 200) {
console.log("You can put here")
}
},
error: function (jaXHR, textStatus, errorThrown) {
// Now it will get parse error because dataType is json and response is html
// console.log(errorThrown);
},
success: function (data, textStatus, jqXHR) {
console.log(data);
if (typeof data.error === 'undefined') {
// Success so call function to process the form
console.log('SUCCESS: ' + data.success);
}
else {
// Handle errors here
console.log('ERRORS: ' + data.error);
}
},
complete: function (jqXHE, textStatus) {
document.body.innerHTML = "dfafsaf";
}
});
});
In you controller you can use
dd($request->all());
for your sure !!

Forbidden Error In JavaScript Ajax Call in CakePHP 3

I have Seen Similar Questions but I could not arrive at the solution. Please help on this code, I am new to javascript
My JavaScript Code :
function checkId(id_corpus){
var dataSet = {identity_number: id_corpus};
var requestUrl = appBaseUrl+'users/check-id-presence';
alert(id_corpus);
$.ajax({
type: "POST",
url: requestUrl,
data: dataSet,
success: function(result) {
if(result == false){
$('#ino').css('background-color', 'red');
$('#ino').css('color', 'black');
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
}
The Above JS code is called by the following CakePHP view:
$this->Form->input('identity_number', ['style' => 'background-color : black; color : #1798A5;', 'id' => 'ino', 'onkeypress' => 'checkId(this.val)']);
Following is the controller code
public function checkIdPresence()
{
$this->autoRender = false;
$id_corpus = $this->request->data['identity_number'];
$check = $this->Users->find()->where(['identity_number LIKE' => '%'.$id_corpus.'%']);
if((iterator_count($check)) > 0){
echo false; //Corpus Exists
}else{
echo true;
}
}
I am stuck in the "Forbidden Error", I would like to bring it to your notice that similar AJAX is being used by me for Image display(as shown below), it is not showing any error:
function fetch(user_id, photo, photo_dir)
{
var dataSet = {id: user_id};
var requestUrl = appBaseUrl+'users/admin-side-nav-details';
var imageUrl = 'http://localhost/media/images/users/photo/'+photo_dir+'/'+'100x100_'+photo;
$.ajax({
type: "POST",
url: requestUrl,
data: dataSet,
success: function(result) {
$('#display_info').html(result);
var image = "<img src ="+imageUrl+" />"
console.log(image);
$('#display_image').html(image);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
}
EDIT: My Auth Component setup :
public function initialize()
{
$this->loadComponent('Auth', [
'authenticate' => [
'Form' => [
'fields' => ['username' => 'email', 'password' => 'password']
]
],
'loginAction' => [
'controller' => 'Users',
'action' => 'login',
],
'authError' => 'Are you sure, you want to enter?',
'logoutAction' => [
'controller' => 'Users',
'action' => 'login',
],
]);
Check https://book.cakephp.org/3.0/en/controllers/components/authentication.html#handling-unauthenticated-requests. "If authenticator returns null, AuthComponent redirects user to the login action. If it’s an AJAX request and config ajaxLogin is specified that element is rendered else a 403 HTTP status code is returned."
It seems to me like you didn't specify any authorization scheme so according to https://book.cakephp.org/3.0/en/controllers/components/authentication.html#using-no-authorization "If you don’t use an authorization scheme, make sure to check authorization yourself in your controller’s beforeFilter or with another component."
You can make actions public (in beforeFilter or initialize) using:
// Allow all actions
$this->Auth->allow();
// Allow only the index action.
$this->Auth->allow('index');
// Allow only the view and index actions.
$this->Auth->allow(['view', 'index']);

Categories