Missing params in Ajax Post request in Laravel - ajax

I am trying to make an Ajax post request and pass params to use them in a query, but my params are always empty. Here is my code:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
function searchPatient(){
var params = {
'name' : $("#input-search-name").val(),
'lastname' : $("#input-search-lastname").val()
}
console.log($('meta[name="csrf-token"]').attr('content'));
$.ajax({
data : params,
url : '{{ route("searchPatient") }}',
contentType: "application/json",
type : 'post',
beforeSend : function(){
console.log(params);
},
success : function(data){
//Inserto a la tabla principal el contenido
$("#main-table-patients").html(data);
//alert('exito');
},
error : function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
console.error(err.Message);
}
});
}
And this is my web.php
Route::group(['middleware'=>'auth'], function(){
Route::namespace('Patient')->group(function(){
Route::resource('/patients','PatientController');
Route::post('/patients/search/{name?}/{lastname?}','PatientController#search')->name('searchPatient');
});
});
And this is my method in my controller
public function search($name = '', $lastname = '')
{
$patients = '';
$patients = Patient::where('name', 'like', '%'.$name.'%')
->Where('lastName','like','%'.$lastname.'%');
return $name.' and '.$lastname;
}

It's an expected behaviour. You are sending in POST the variables but your route is designed to retrive the variables from the url.
Decide what you want ...
if you want to pass them in POST then your ajax call's url should be /patients/search
and your route should be only
Route::post('/patients/search','PatientController#search');
your controller at that point can deal with $request object
public function search(Illuminate\Http\Request $request) {
dd($request->all());
}
if you want to pass them in the url (not a good idea IMHO)
then change your ajax call url to:
url: '/patients/search/' + params.name + "/" + params.lastname
This approach can cause problems in case one of the 2 params contains a "slash" (/)

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
}

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.']);
}

how to create relational select option ajax in laravel 8

I try to create a relational select option in laravel 8 using ajax but didn't work I get this error in the console: 405 Method Not Allowed
POST http://127.0.0.1:8000/decomptes/%7B%7B%20route(%20'getOperationsChantier'%20)%20%7D%7D 405 (Method Not Allowed)
the route
Route::post('/getOperationsChantier', [DecompteController::class, 'getOperationsChantier'])->name('getOperationsChantier');
the jquery code
$(document).ready(function(){
// When an option is changed, search the above for matching choices
$('#chantiers').change(function(){
$("#mySelect option").remove();
// $("#city option").remove();
var id = $(this).val();
$.ajax({
url : "{{ route( 'getOperationsChantier' ) }}",
data: {
"_token": "{{ csrf_token() }}",
"id": id
},
type: 'post',
dataType: 'json',
success: function( result )
{
$.each( result, function(k, v) {
$('#mySelect').append($('<option>', {value:k, text:v}));
});
},
error: function()
{
//handle errors
alert('error...');
}
});
}).change();
});
the function in the controller :
function getOperationsChantier( Request $request )
{
$this->validate( $request, [ 'id' => 'required|exists:chantiers,id' ] );
$chantierOperations = ChantierOperation::where('chantier_id', $request->get('id') )->get();
$output = [];
foreach( $chantierOperations as $chantierOperation )
{
$output[$chantierOperation->id] = $chantierOperation->operation_id;
}
return $output;
}
can someone help me this is the first time when I use ajax

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.

Redirecting to different view after an AJAX call Laravel

I am trying to activate my user by doing an AJAX call. I have this jQuery code for that:
$(document).ready(function(){
$(document).one('click','.continue-button',function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var id = $(this).data('id');
$.ajax({
url: '/activate',
type: 'POST',
data: {id : id},
success: function(res){
}
});
});
});
It takes the data-id attribute of my button, which is the user's id and sends an AJAX call. This is how my route looks like:
Route::post('/activate','ActiveController#activate');
My function:
public function activate(Request $request)
{
$id = $request->input('id');
User::where('id',$id)->update([
'active' => '1'
]);
return redirect('/loadDashboard');
}
It activates the user and then redirects to '/loadDashboard' route. This is how the route looks like:
Route::group( ['middleware' => 'auth' ], function()
{
Route::get('/loadDashboard','ActiveController#loadDashboard');
});
And finally my loadDashboard function:
public function loadDashboard()
{
return view('dashboard')->with('title','Dashboard');
}
I want to redirect the user to my dashboard view in aforementioned function, but it seems to return the view to my AJAX call. I can see the view in Inspect->Network. How can I fix this problem?
Instead of this
return redirect('/loadDashboard');
put this
return response()->json(['url'=>url('/loadDashboard')]);
and in your ajax success function put this:
success: function(res){
window.location=res.url;
}

Resources