laravel7 working image upload but ajax says there's error - ajax

So I'm doing an image upload via modal and ajax. It is working, it is saved in the database and saved in public folder as an image, except that the modal does not hide because there's something wrong as said in the console.
statusCode: ƒ ( map )
statusText: "OK"
AJAX:
$(document).ready(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
//ADD PICTURE
$('#btnUpload').click(function(){
$('#uploadModal').modal('show');
});
$('#btnSave').click(function(){
$.ajax({
data: new FormData($('#uploadForm').get(0)),
url: "{{ route('gallery.store') }}",
type: "POST",
dataType: 'json',
contentType: false, // required for
processData: false, // jquery ajax file upload
success: function(data){
$successmessage = 'SUCCESSFULLY UPLOADED';
$('#uploadModal').modal('hide');
$('#successmessage').text($successmessage);
},
error: function(data){
console.log('Error:', data);
}
});
});
});
CONTROLLER:
public function store(Request $request)
{
$galleries=new Gallery;
// Handle File Upload
if($request->hasFile('upload')){
// Get filename with the extension
$filenameWithExt = $request->file('upload')->getClientOriginalName();
// Get just filename
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
// Get just ext
$extension = $request->file('upload')->getClientOriginalExtension();
// Filename to store
$fileNameToStore= $filename.'.'.$extension;
// Upload Image
$path = $request->file('upload')->storeAs('public/upload', $fileNameToStore);
} else {
$fileNameToStore = 'noimage.jpg';
}
$galleries->description = $request->input('description');
$galleries->upload = $fileNameToStore;
$galleries->save();
}

In store function, you have to return response status code. In the case of success, you return 200.
return response()->json(['success' => 'success'], 200);
In the event of a failure, you return the code that corresponds to the error.
Example:
return response()->json(['error' => 'invalid'], 401);

Related

how to redirect to another page if condition is not valid while using ajax?

I want add product to the cart through ajax. only logged in user can add product to the the user. if user is not logged in redirect him to the log in page
Here are my ajax request in blade template
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
function addedToCart(){
var product = $("#productId").val();;
var val = $("#countItem").val();
var unit = parseInt(val);
$.ajax({
type: "POST",
url: "/addtocart",
data: {product: product, unit: unit},
dataType: "json",
success: function (res){
alertMsg.fire({
title: 'Product added to Cart'
})
}
});
}
`
Here the controller code
function addToCart(Request $req){
if($req->session()->has('user')){
$cart = new Cart;
$cart->user_id = $req->session()->get('user')['id'];
$cart->product_id = $req->product;
$cart->unit = $req->unit;
$cart->save();
return response($cart, 201);
}
else{
return redirect('/login');
}
}
It can not go the login route still remain in the same page
Ajax request expects JSON Array Literals, such are JSON formatted array/objects and plain strings, in response. Meaning, you can't make redirect object return in PHP.
You can
// in controller
if (!$req->session()->has('user')) {
return response()->json([
'error' => "Forbidden"
], 403);
}
// save the cart and return success object
Then
// in JS
$.ajax({
type: "POST",
url: "/addtocart",
data: {product: product, unit: unit},
dataType: "json",
success: function (res){
alertMsg.fire({
title: 'Product added to Cart'
})
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
window.location = 'path_for_guests'// this path should be returned from backend for greater security
}
});
Also, be aware of not saved objects. For example, if $cart is not successfully saved you shouldn't return success message. Which is your code doing right now. To follow Object Calisthenics appropriate code (one else it too much), you can use switch and in suitable cases match for various exceptions and expectations like
user session doesn't exist 403
object not created 500
cart created 201
etc
in JSON response you can not use redirect at server side.
either you can play with status here like if the user is logged in, then perform your action, otherwise return a response with status: false.
I have modified your code link below and I have added in comments on what I have changed.
Your JS code
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
function addedToCart(){
var product = $("#productId").val();;
var val = $("#countItem").val();
var unit = parseInt(val);
$.ajax({
type: "POST",
url: "/addtocart",
data: {product: product, unit: unit},
dataType: "json",
success: function (response){
if (response.status) { // if it is true
alertMsg.fire({
title: 'Product added to Cart',
});
} else {
// if it is false, redirect
window.location.href = response.redirect_uri;
}
},
});
}
Your controller function:
function addToCart(Request $request){
if($req->session()->has('user')){
$cart = new Cart;
$cart->user_id = $request->session()->get('user')['id'];
$cart->product_id = $request->product;
$cart->unit = $request->unit;
$cart->save();
return response($cart, 201);
}
else{
// you can return with status flag, and using the redirect_uri your can redirect at your desire page.
return response()->json(array(
'status' => false,
'redirect_uri' => route('login'),
), 401);
}
}
Not sure, about the false status you will get in the AJAX success(), if you will not get then you will have to add the error function after the success(). as we are passing header status in the response.
error: function (error) {
// do console log to check what you get
}

How to return resonse from ajax and display it in Blade file in laravel 8

I am trying to integrate sorting system in laravel application, I am able to do ajax call and got the response but how to display that data in blade file.
I have the data already displayed on search page now if user try to sort the and old data will replaced by the new data.
How can I do that.
Controller Code :
public function sort_data(Request $request){
$results='';
if(request()->sub_sub_category){
$results = Product::orderBy($request->sorting_selection,'asc')->with('categories')->whereHas('categories', function ($query){
$query->where('slug', request()->sub_sub_category);
})->paginate(24);
} elseif (request()->sub_category){
$results = Product::orderBy($request->sorting_selection,'asc')->with('categories')->whereHas('categories', function ($query){
$query->where('slug', request()->sub_category);
})->paginate(24);
} elseif (request()->category){
$results = Product::orderBy($request->sorting_selection,'asc')->with('categories')->whereHas('categories', function ($query){
$query->where('slug', request()->category);
})->paginate(24);
} else{
$results = Product::orderBy($request->sorting_selection,'asc')->with('categories')->paginate(24);
}
// $returnHTML = view('pages.user.shop.products.products')->with(["products"=>$results])->render();
// return response()->json(array('success' => true, 'html'=>$returnHTML));
// return response()->json(['products' => $results, 'status' => 200]);
return view('pages.user.shop.products.products')->with(["products"=>$results]);
}
I have already tried the commented code. But not success
$(document).ready(function(){
$('#soting-select').on('change', function(){
var value = document.getElementById('soting-select').value;
var ajaxurl = '/sort-product';
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: ajaxurl,
type: 'post',
dataType: 'json',
data: {
'sorting_selection' : value
},
success: function(response){
console.log(response);
}
});
});
});
Old Response :
New Response :
You can call render() on the view.
And also you may need to change the $results variable to $products as you have shared the data with $products variable in your blade file.
$returnHTML = view('pages.user.shop.products.products', compact('products'))->render();
See the View source code for more information.

Laravel Explode Ajax Request Containing Name and Numbers

I'm using laravel 8.4 .
My route :
Route::post('test',[\App\Http\Controllers\DataController::class, 'store'])->name('pos-test');
My Controller :
public function store(Request $request)
{
// DB::table('data')->insert('product_code',$request->id);
$badge = explode(' ', $request);
$employee_id = $badge[0];
\DB::table('data')->insert(['product_code'=> $employee_id]);
return response()->json(['success'=>'Product saved successfully.']);
}
Ajax code :
function handleBarcode(scanned_barcode) {
//handle your code here....
console.log(scanned_barcode);
let _token = $('meta[name="csrf-token"]').attr('content');
event.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: "{{ route('pos-test') }}",
type: "POST", // Can change this to get if required
data: {
code : scanned_barcode,
_token: _token
},
success: function(data) {
$("#status").html(data);
},
error: function(jqXHR, textStatus, errorThrown) {
$("#status").text(textStatus);
console.log(jqXHR);
}
});
};
The request is like this "555444 Razif Raziq" , i would like to explode it so I may insert only "555444" into table but in table column product_code is 'POST' .
The question is how to fix it? thank you
you must explode your correct data in request object not request object itself.
$badge = explode(' ', $request->code);
If the 'code' value is sent correctly, just use this
$request->code
public function store(Request $request)
{
\DB::table('data')->insert(['product_code'=> $request->code]);
return response()->json(['success'=>'Product saved successfully.']);
}

Larave/Ajax PUT 500 internal server error possible reasons

My console shows this error whenever I try to update my form using my ajax code:
PUT http://127.0.0.1:8000/clinical/bbr-category-configuration-update/1 500 (Internal Server Error)
Route:
Route::put('/bbr-category-configuration-update/{category_id}', [BBRCategoryConfigurationController::class,'update']);
Ajax:
$(document).on('click', '.update_category', function (e){
e.preventDefault();
var cat_id = $('#edit_cat_id').val();
var update_data = {
'category_name' : $('#edit_category_name').val(),
'category_description' : $('#edit_category_description').val(),
}
//token taken from laravel documentation
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "PUT",
url: "/clinical/bbr-category-configuration-update/"+cat_id,
data: update_data,
dataType: "json",
success: function (response){
// console.log(response);
if(response.status == 400) {
$('#category_formCheckUpdate').html("");
$('#category_formCheckUpdate').addClass('alert alert-danger');
$.each(response.errors, function (key, err_values) {
$('#category_formCheckUpdate').append('<li>'+err_values+'</li>');
});
} else if(response.status == 404) {
$('#category_formCheckUpdate').html("");
$('#category_notif').addClass('alert alert-success');
$('#category_notif').text(response.message);
} else {
$('#category_formCheckUpdate').html("");
$('#category_notif').html("");
$('#category_notif').addClass('alert alert-success');
$('#category_notif').text(response.message);
$('#editCategoryModal').modal('hide');
fetchcategory();
}
}
});
});
Controller:
public function update(Request $request, $category_id) {
$validator = Validator::make($request->all(), [
'category_name'=>'required|max:191',
'category_description'=>'required|max:191',
]);
if($validator->fails()) {
return response()->json([
'status'=>400,
'errors'=>$validator->messages(),
]);
} else {
$category_update = HmsBbrCategory::find($category_id);
if ($category_update) {
$category->category_name = $request->input('category_name');
$category->category_description = $request->input('category_description');
$category->update();
return response()->json([
'status'=>200,
'message'=>'Category Edited!',
]);
} else {
return response()->json([
'status'=>404,
'message'=>'Category Not Found',
]);
}
}
}
Things to note:
As you can see, my category_id is being read properly in: url: "/clinical/bbr-category-configuration-update/"+cat_id,. Also, I went ahead and did a console.log to show in my console that the whole table is getting retrieved. My main issue is this 500 internal server error. Not sure if it is by the PUT.
I also tried to change the PUT to POST or GET just to see if there is any change or other errors, but it's still the same 500 internal server issue. PS, my form has csrf.
Your problem is surely $category, you are using $category_update, not $category

laravel- request empty in controller using ajax

I am using laravel 6.0 and i am building crud application. I have following jquery code in view file
function updaterecord(id) {
$('#modalupdate').on('submit', function (e) {
e.preventDefault();
$.ajax({
url: 'update/'+id,
method: 'post',
success: function (res) {
console.log(res);
}
})
});
}
And this is the code in controller
public function update(Request $request, $id='') {
$country = $request->input('countryname');
$sortname = $request->input('sortname');
$phonecode = $request->input('phonecode');
//return $country.$sortname.$phonecode;
return $request;
// DB::table('countries')->where('id',$id)->update(
// [
// 'name' => $country,
// 'sortname' => $sortname,
// 'phonecode' => $phonecode,
// ]);
}
The problem is $request returns empty.
If I don't use ajax then I am getting all input values. But I dont know why its not working for ajax request. Also I have added this line in view file
headers: {
'X-CSRF-TOKEN': '{!! csrf_token() !!}'
}
});
Please help me to solve this problem
You are not passing your form data. Try this:
function updaterecord(id) {
$('#modalupdate').on('submit', function (e) {
e.preventDefault();
$.ajax({
url: 'update/' + id,
method: 'post',
data: $(this).serialize();
success: function (res) {
console.log(res);
}
})
});
}
laravel by default does not send raw data , you have to convert your data to json, the best practice is :
return response()->json([
'data' => $request
]);
Just try this code for example and see if you get any hint.
function updaterecord(id) {
$('#modalupdate').on('submit', function (e) {
e.preventDefault();
$.ajax({
url: 'update/' + id,
method: 'post',
data: {'countryname' : 'India','sortname' : 'Sort Name', 'phonecode' : '022'};
success: function (res) {
console.log(res);
}
})
});
}
See if you are getting any response.

Resources