Undefined AJAX Laravel 5.2 Message - javascript

My problem is not work AJAX Laravel For me in ver5.2 how to solve this problem
my error:
Route [category] not defined. (View: C:\wamp\www\pc\resources\views\admin\category.blade.php)
my Route file:
Route::group(['middleware' => 'web'], function () {
Route::auth();
Route::get('category', 'categoryController#index');
});
Route::group(['middleware' => 'web'], function () {
Route::auth();
Route::post('category', 'categoryController#create');
});
my controller:
public function create(messageRequest $request)
{
try {
Category::create($request->all());
return response()->json(array('sms'=>'save Success'));
}catch (Exception $e){
return response()->json(array('err'=>'error'));
}
}
my javascript:
<script>
$('#submit').on('click', function (e) {
e.preventDefault();
var data = $('#create').serialize();
$.ajax({
type: 'post',
url: '{!! URL::route('category') !!}',
data: data,
success: function (data) {
alert(data.sms);
console.log('data');
},
error:function(){
alert(data.err);
console.log('data');
}
});
});
</script>

Route::post('category', 'categoryController#create');
change to
Route::post('category', ['as' => 'category', 'uses' => 'categoryController#create']);

in view:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
<meta name="csrf-token" content="{{ csrf_token() }}" />
<input type="hidden" name="_token" value="{{ csrf_token() }}">
in controller:
/**
* Determine if the session and input CSRF tokens match.
*
* #param \Illuminate\Http\Request $request
* #return bool
*/
protected function tokensMatch($request)
{
// If request is an ajax request, then check to see if token matches token provider in
// the header. This way, we can use CSRF protection in ajax requests also.
$token = $request->ajax() ? $request->header('X-CSRF-Token') : $request->input('_token');
return $request->session()->token() == $token;
}

Related

how to call delete route with ajax in laravel?

i want to call route resource with ajax, when i put type as delete i got error (exception "Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException")
and given message (message "The DELETE method is not supported for this route. Supported methods: GET, HEAD, POST.").function almost work beacuse after make refresh the status also change but i am the above error.
route :
Route::resource('category', ArtistCategoryController::class);
controller :
public function destroy($id)
{
$category = ArtistCategory::findOrFail($id);
$deleteResponse = $category->update([
'status'=>'d'
]);
if ($deleteResponse) {
deleteMessage();
return redirect()->back();
} else
errorMessage();
}
view :
</i>
ajax:
<script>
$(".categoryDelete").on('click', function (e) {
e.preventDefault();
let id = $(this).data('id')
// console.log(id)
$.ajax({
url: '/artist/category/'+id,
type: 'DELETE',
data:{"id": id, "_token": "{{ csrf_token() }}"},
success: function (data)
{
alert(data)
},
error: function (e){
alert(e)
}
});
})
</script>
solved it with some changes in destroy method
because i have used return return redirect()->back();it gives error and this is unacceptable
updated
public function destroy($id): \Illuminate\Http\JsonResponse
{
$category = ArtistCategory::findOrFail($id);
$deleteResponse = $category->update([
'status'=>'d'
]);
if ($deleteResponse) {
return response()->json([
'data' => [
'id' => $id
],
'status' => 'success',
]);
} else
{
return response()->json([
'data' => [
'id' => $id
],
'status' => 'error',
'message' => __("Couldn't Delete. Please Try Again!")
], 500);
}
}
You need to set the csrf token in the header. Have a look at the docs in the bottom of the page: https://laravel.com/docs/8.x/csrf#csrf-x-csrf-token
Create a meta tag with the token like this:
<meta name="csrf-token" content="{{ csrf_token() }}">
And grap it like this:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});

Select2 POST AJAX Request 500 Error Laravel

I'm trying to use select2 retrieving large data in my dropdown using the following article.
Getting 500 Internal Server Error in my console log.
I have store token in HTML meta tag.
<meta name="csrf-token" content="{{ csrf_token() }}">
And sending a token as a parameter in my POST request.
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$(document).ready(function(){
$( "#test" ).select2({
ajax: {
url: "path/to/url",
type: "POST",
dataType: 'JSON',
delay: 250,
data: function (params) {
return {
_token: CSRF_TOKEN,
search: params.term // search term
};
},
processResults: function (response) {
return {
results: response
};
},
cache: true
}
});
});
<select class="test" id="test" style="width:100%;"></select>
I have checked routes using php artisan route:list and clear cache using php artisan config:cache. But still getting the same error link. and link.
Is there anything I'm missing? I would be grateful if you can help me out to debug/inspect my Request and Response.
Tried
error: function(err){
console.log(err)
}
Server-Side \ Controller
public function getdata(Request $request){
$search = $request->search;
if($search == ''){
$data = DB::table('table')
->orderby('name','asc')
->select('id','name')
->limit(5)->get();
}else{
$data = DB::table('table')
->orderby('name','asc')
->select('id','name')
->where('name', 'like', '%' .$search . '%')
->limit(5)->get();
}
$response = array();
foreach($data as $i){
$response[] = array(
"id"=>$i->id,
"text"=>$i->name
);
}
return response()->json($response);
}
Happy Coding.

laravel cannot post data with ajax server status 419

I am doing a project with Laravel.
When I change the selected option of the following select element I should insert the selected value to mysql database to retrieve all the data about the selected id from the server (for example the name of the user).
This is the select element (adminArea.blade.php):
<select name="employees" onchange="fillEmployeeData(this)" class="form-control col-sm-6" id="employees">
<option value="0"></option>
#foreach ($users as $user)
<option value="{{ $user->id }}">{{ $user->surname . ' ' . $user->name }}</option>
#endforeach
</select>
And this is the called function (adminArea.blade.php)::
function fillEmployeeData(emp_id) {
var emp_selected = emp_id.value;
$.ajax({
type: "POST",
url: "{{ route('adminAreaPostEmployee') }}",
data: 'emp_selected=' + emp_selected,
success: function (data) {
var emp_data = JSON.parse(data);
alert(emp_data);
}
});
};
These are my routes (web.php):
Route::get('/adminarea', 'AdminAreaController#index')->name('adminArea');
Route::post('/adminarea/postemployee', 'AdminAreaController#post_employee')->name('adminAreaPostEmployee');
And these are my controller methods (adminAreaController.php):
public function post_employee(Request $request)
{
$select = $request->get('emp_selected');
$user = User::where('id', $select);
echo $user;
}
public function index()
{
$operations = Operation::all();
$users = User::all()->sortBy('surname');
$rooms = Room::all();
return view('adminArea', compact('users', 'rooms', 'operations'));
}
However, when I change the selected value nothing happens... and if I go to the developer tools I see the following error:
Failed to load resource: the server responded with a status of 419
(unknown status).
Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException
The GET method is not supported for this route. Supported methods:
POST.
I don't see any alert. Someone can help me?
The HTTP status code for the MethodNotAllowedHttpException is 405
See here
public function __construct(array $allow, string $message = null, \Throwable $previous = null, ?int $code = 0, array $headers = [])
{
$headers['Allow'] = strtoupper(implode(', ', $allow));
parent::__construct(405, $message, $previous, $headers, $code);
}
A TokenMismatchException HTTP status code is 419
See here
protected function prepareException(Exception $e)
{
if ($e instanceof ModelNotFoundException) {
$e = new NotFoundHttpException($e->getMessage(), $e);
} elseif ($e instanceof AuthorizationException) {
$e = new AccessDeniedHttpException($e->getMessage(), $e);
} elseif ($e instanceof TokenMismatchException) {
// HTTP Status code is send in the header here
$e = new HttpException(419, $e->getMessage(), $e);
} elseif ($e instanceof SuspiciousOperationException) {
$e = new NotFoundHttpException('Bad hostname provided.', $e);
}
return $e;
}
So this appears to be a CSRF token issue
Make sure that you have a meta tag on the head of your document like this
<meta name="csrf-token" content="{{ csrf_token() }}">
Also from the JQuery Ajax Documentation
I think that the HTTP method should be defined as method parameter not type (though type works ¯\_(ツ)_/¯)
// Send a CSRF token header with every Ajax request
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
function fillEmployeeData(emp_id) {
var emp_selected = emp_id.value;
$.ajax({
method: "POST",
url: "{{ route('adminAreaPostEmployee') }}",
data: 'emp_selected=' + emp_selected,
success: function (data) {
var emp_data = JSON.parse(data);
alert(emp_data);
}
});
};
But now you're gonna get an error
Object of class Illuminate\Database\Eloquent\Builder could not be converted to string
Because you're trying to return a query builder instance User::where('id', $select) instead of the user record itself serialized
I think you may want to do this
public function post_employee(Request $request)
{
$select = $request->get('emp_selected');
return User::find($select);
}
Hope this helps
Try to 'method' instead of 'type' . You should use type if you're using versions of jQuery prior to 1.9.0
function fillEmployeeData(emp_id) {
var emp_selected = emp_id.value;
$.ajax({
method: "POST",
url: "{{ route('adminAreaPostEmployee') }}",
data: 'emp_selected=' + emp_selected,
success: function (data) {
var emp_data = JSON.parse(data);
alert(emp_data);
}
});
};
this is a CSRF protection of laravel,
you can add csrf meta tag in the head
<meta name="csrf-token" content="{{ csrf_token() }}">
and in the top of the script write
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});

Laravel 5.3 AJAX login doesn't redirect

I have similar issue like this one.
I'm trying to make AJAX login using Laravel 5.3 Auth.
Here's what I got so far:
var login = function()
{
var data = {};
data["email"] = $('#email').val();
data["password"] = $('#password').val();
if($('#remember').is(':checked'))
data["remember"] = "on";
$.ajax({
type: "POST",
url: '/login',
data: JSON.stringify(data),
// data: data,
headers : { 'Content-Type': 'application/json' },
success: function(data) {
console.log(data);
// window.location.href = "/dashboard";
}
});
};
I'm sending CRSF token as X-CSRF-TOKEN header.
The problem is that when I successfully login, I say on the same page,
but in Network tab I can see that /dashboard page is loaded by I'm not
redirected.
In the same manner, when I pass wrong credentials, I stay on the same page,
but I can see that /login page is loaded in the separate call with an error message that should be actually displayed.
Also, I've tried without headers : { 'Content-Type': 'application/json' },
and sending data as: data = data, but I get the same thing.
Why the browser doesn't redirect to that page since it is loading it in the "background"?
Edit: I'm getting correct page as request response as well, I can see it
in console (console.log(data);).
//Login FORM
$(document).on('submit', 'form#FormID', function(e) {
e.preventDefault();
var forms = document.querySelector('form#FormID');
var request = new XMLHttpRequest();
var formDatas = new FormData(forms);
request.open('post','/login');
request.send(formDatas);
request.onreadystatechange = function() {
if (request.readyState === 4) {
if (request.status === 200) {
if (request.responseText == 'success') {
setTimeout(function() {
window.location.href = "/dashboard";
}, 5000);
}else{
};
}
}
}
});
//Controller
public function authUser(Request $request){
$data = $request->except('_token');
$validate = \Validator::make($data, [
'email' => 'email'
]);
if ($validate->fails())
return 'Invalid email format for username.';
if (\Auth::attempt($data)) {
return 'success';
}else{
return 'Invalid username or password';
}
}
//Route
Route::post('/login', 'YourController#authUser');
The problem might be with the response AJAX request is expecting before redirect.
Try the above code.
in the controller method
function login(Request $request){
if(\Auth::attempt($request)){
return response()->json('success');
}else{
return response()->json('wrong username or pass', 401);
}
}
in ajax
$.ajax({
type: "POST",
url: '/login',
data: JSON.stringify(data),
// data: data,
headers : { 'Content-Type': 'application/json' },
success: function(data) {
console.log(data);
window.location.href = "/dashboard";
},
error : function(data){
alert(data);
}
});
Here's an interesting solution.
/**
* Get the failed login response instance.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
protected function sendFailedLoginResponse(Request $request)
{
if ($request->ajax()) {
return response()->json([
'error' => Lang::get('auth.failed')
], 401);
}
return redirect()->back()
->withInput($request->only($this->username(), 'remember'))
->withErrors([
$this->username() => Lang::get('auth.failed'),
]);
}
And this:
var loginForm = $("#loginForm");
loginForm.submit(function(e) {
e.preventDefault();
var formData = loginForm.serialize();
$('#form-errors-email').html("");
$('#form-errors-password').html("");
$('#form-login-errors').html("");
$("#email-div").removeClass("has-error");
$("#password-div").removeClass("has-error");
$("#login-errors").removeClass("has-error");
$.ajax({
url: '/login',
type: 'POST',
data: formData,
success: function(data) {
$('#loginModal').modal('hide');
location.reload(true);
},
error: function(data) {
console.log(data.responseText);
var obj = jQuery.parseJSON(data.responseText);
if (obj.email) {
$("#email-div").addClass("has-error");
$('#form-errors-email').html(obj.email);
}
if (obj.password) {
$("#password-div").addClass("has-error");
$('#form-errors-password').html(obj.password);
}
if (obj.error) {
$("#login-errors").addClass("has-error");
$('#form-login-errors').html(obj.error);
}
}
});
});

Can't send data to the Controller with a POST method Symfony3

I have a POST method Jquery. Ajax and I can't send my data to the controller, I have tried every solution on the net, but no result.......
My JavaScript
$(document).ready(function(){
$('#submitForm').click(function(){
var data1 = {request : $('#request').val()};
$.ajax({
type: "POST",
url: "/Manufacturer",
data: data1,
success: function(dataBack) {
console.log(dataBack);
},
contentType: "application/json",
dataType: 'json'
});
});
});
MY controller
public function indexAction(Request $request)
{
//$name = $request->request->get('data');
//return new Response($name);//or do whatever you want with the sent value
if($request->isXmlHttpRequest()){
$name = $request->request->get('data1');
If($name == 1)
{
return new Response('Yeap');
}
else
{
return new Response(';(');
}
}
return $this->render('MyIndex/Manufacturer_LIST.html.twig' );
}
HEre is my Console ::
And my response is as it's obvious ";("
First you need to install FOSJsRoutingBundle to be able to "expose" your Symfony routes into the javascript code. Follow the steps in the official documentation.
Then, in your twig template if you have a form like:
<form>
<input type="text" id="name"> <br>
<button type="submit" id="submitForm">Submit</button>
</form>
your js code could look liks this:
$('#submitForm').click(function(e){
e.preventDefault();
var name = $('#name').val();
$.ajax({
method: 'POST',
url: Routing.generate('Manufacturer_LIST');
// OR: url: "/Manufacturer", if you don't want to install FOSJsRoutingBundle
data: { name:name }
}).done(function(msg){
console.log(msg);
}).fail(function(XMLHttpRequest, textStatus, errorThrown){
console.log(textStatus + ' ' + errorThrown);
});
});
And in your controller:
/**
* #Route("/Manufacturer", name="Manufacturer_LIST", options={"expose"=true})
*/
public function indexAction(Request $request){
if($request->isXmlHttpRequest()){
$name = $request->request->get('name');
return new Response($name);//or do whatever you want with the sent value
}
return $this->redirectToRoute('homepage');
}

Categories

Resources