Laravel 5: Ajax Post 500 (Internal Server Error) - php

I'm trying to submit data to the database via ajax. The submit article page works fine without ajax. I've added console.log() just to see if anything is going through, but instead I'm getting this error:
POST http://localhost/laravel-5/public/articles/create 500 (Internal Server Error)
What's wrong with my code? Is it the javascript or the controller?
EDIT: I'm getting this in laravel.log
exception 'Illuminate\Session\TokenMismatchException' in C:\xampp\htdocs\laravel-5\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\VerifyCsrfToken.php:53
Route
Route::resource('articles', 'ArticlesController');
Controller
public function store(Requests\ArticleRequest $request)
{
$article = new Article($request->all());
Auth::user()->articles()->save($article);
$response = array(
'status' => 'success',
'msg' => 'Article has been posted.',
);
return \Response::json($response);
}
jQuery
$(document).ready(function() {
$('#frm').on('submit', function (e) {
e.preventDefault();
var title = $('#title').val();
var body = $('#body').val();
var published_at = $('#published_at').val();
$.ajax({
type: "POST",
url: 'http://localhost/laravel-5/public/articles/create',
dataType: 'JSON',
data: {title: title, body: body, published_at: published_at},
success: function( data ) {
$("#ajaxResponse").append(data.msg);
console.log(data);
}
});
});
View
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<h1>Write a New Article</h1>
<hr>
{!! Form::open(['url' => 'articles', 'id' => 'frm']) !!}
<p>
{!! Form::label('title', 'Title:') !!}
{!! Form::text('title') !!}
</p>
<p>
{!! Form::label('body', 'Body:') !!}
{!! Form::textarea('body') !!}
</p>
<p>
{!! Form::label('published_at', 'Date:') !!}
{!! Form::input('date', 'published_at', date('Y-m-d'), ['class' => 'form-control']) !!}
</p>
<p>
{!! Form::submit('Submit Article', ['id' => 'submit']) !!}
</p>
{!! Form::close() !!}
<h3 id="ajaxResponse"></h3>
#if($errors->any())
<ul>
#foreach($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
#endif
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="{{ URL::asset('assets/js/ArticleCreate.js') }}"></script>
});

When you make a request via POST to a resource controller, it automatically calls store method:
Verb Path Action Route Name
----------------------------------
POST /articles store articles.store
So, you just need to change ajax url to:
$.ajax({
type: "POST",
url: 'http://localhost/laravel-5/public/articles',
When you need to send the session token, you can add a global meta-tag like this is you website:
<meta name="csrf-token" content="{{ csrf_token() }}">
Then, just add the token via ajax's headers:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
If you are using Form::open() function (LaravelCollective) it adds a hidden input with the token as value with the name _token. So, you can remove the meta-tag and edit your ajax's headers like this:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('[name="_token"]').val()
}
});

That's what I got exception 'Illuminate\Session\TokenMismatchException' in C:\xampp\htdocs\laravel-5\vendor\laravel\framework\src\Illuminate\Foundation\Htt‌​p\Middleware\VerifyCsrfToken.php:53
You're hitting Laravel's CSRF protection.
http://laravel.com/docs/5.1/routing#csrf-protection
You need to pass the hidden _token field's value. This can be done automatically on all jQuery-initiated AJAX requests by doing this in your application's JS:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('input[name="_token"]').value()
}
});
Or, you can manually fetch and pass the value of the _token hidden field in each of your AJAX calls.

I like to share this code to help someone to need ajax post and get with laravel
<<<<<<<<
POST
<<<<
<<look after #extends<<
<<look beforeSend: function (xhr) <<
<<look use Illuminate\Http\Request in Routes<<
<<<------<<views\login\login.blade.php<<<<-----------<<<
#extends('cuerpito.web')
<meta name="csrf_token" content="{{ csrf_token() }}" />
#section('content')
<form action="#" id="logForm" method="post" class="form-horizontal">
<div class="form-group">
<div class="col-xs-12">
<div class="input-group">
<input type="email" id="email" name="email" class="form-control input-lg" placeholder="Ingresa tu Email." autocomplete="off">
</div>
</div>
</div>
<div class="form-group">
<div class="col-xs-12">
<div class="input-group">
<input type="password" id="password" name="password" class="form-control input-lg" placeholder="Ingresa tu Contraseña." autocomplete="off">
</div>
</div>
</div>
<div class="form-group formSubmit">
<div class="col-xs-12">
<div class="input-group">
<button type="submit" name="feedbackSubmit" id="feedbackSubmit" class="btn btn-success btn-lg" style="display: block; margin-top: 10px;">Ingresar</button>
</div>
</div>
</div>
</form>
<script type="text/javascript">
$(document).ready(function () {
$("#feedbackSubmit").click(function () {
$.ajax({
url: '{{URL::route('login4')}}',
type: "post",
beforeSend: function (xhr) {
var token = $('meta[name="csrf_token"]').attr('content');
if (token) {
return xhr.setRequestHeader('X-CSRF-TOKEN', token);
}
},
data: $("#logForm").serialize(),
success: function (data)
{
if (data) {
alert(data);
console.log(data);
} else {
console.log(data);
}//else
}//success
});//ajax
return false;
});//feedbacksubmit
});//document ready
</script>
-------------0----------------------
-------------0----------------------
<<<----<<app\Http\routes.php<<<<-----------<<<
<?php
use Illuminate\Http\Request;
Route::post('login4', function()
{
return 'Success! POST Ajax in laravel 5';
})->name('login4');
------------------0----------------------
------------------0----------------------
<<<<
Get
<<look after #extends<<
<<look beforeSend: function (xhr) <<
<<look use Illuminate\Http\Request in Routes<<
<<<------<<views\login\login.blade.php<<<<-----------<<<
#extends('cuerpito.web')
<meta name="csrf_token" content="{{ csrf_token() }}" />
#section('content')
<form action="#" id="logForm" method="post" class="form-horizontal">
<div class="form-group">
<div class="col-xs-12">
<div class="input-group">
<input type="email" id="email" name="email" class="form-control input-lg" placeholder="Ingresa tu Email." autocomplete="off">
</div>
</div>
</div>
<div class="form-group">
<div class="col-xs-12">
<div class="input-group">
<input type="password" id="password" name="password" class="form-control input-lg" placeholder="Ingresa tu Contraseña." autocomplete="off">
</div>
</div>
</div>
<div class="form-group formSubmit">
<div class="col-xs-12">
<div class="input-group">
<button type="submit" name="feedbackSubmit" id="feedbackSubmit" class="btn btn-success btn-lg" style="display: block; margin-top: 10px;">Ingresar</button>
</div>
</div>
</div>
</form>
<script type="text/javascript">
$(document).ready(function () {
$("#feedbackSubmit").click(function () {
$.ajax({
url: '{{URL::route('login2')}}',
type: "get",
beforeSend: function (xhr) {
var token = $('meta[name="csrf_token"]').attr('content');
if (token) {
return xhr.setRequestHeader('X-CSRF-TOKEN', token);
}
},
data: $("#logForm").serialize(),
success: function (data)
{
if (data) {
obj = JSON.stringify(data, null, " ");
var datito = JSON.parse(obj);
console.log(datito.response);
alert(datito.response);
} else {
console.log(data);
}//else
}//success
});//ajax
return false;
});//feedbacksubmit
});//document ready
</script>
-------------0----------------------
-------------0----------------------
<<<----<<app\Http\routes.php<<<<-----------<<<
<?php
use Illuminate\Http\Request;
Route::get('login2', 'WebController#login2')->name('login2');
-------------0----------------------
-------------0----------------------
<<<----<<Http\Controllers\WebController.php<<<<-----------<<<
public function login2(Request $datos) {
if ($datos->isMethod('get')) {
return response()->json(['response' => 'This is get method']);
}
return response()->json(['response' => 'This is post method']);
}
-------------0----------------------
-------------0----------------------

You can add your URLs to the VerifyCsrfToken.php middleware. The URLs will be excluded from CSRF verification:
protected $except = [ "your url", "your url/abc" ];

Well if you are looking for the sure shot answer ,here it is :
This error particularly occurs if you are missing csrf_token() in your code
Here is what I did,
<h6>ITEMS ORDERED:CLICK HERE</h6>
<input type="hidden" id="token" value="{{ csrf_token() }}">
Now With Ajax
<script type="text/javascript">
function getcart(val) {
var alpha=val;
var token=document.getElementById('token').value;
$.ajax({
type:'post',
url:'/private/getcart',
data:{'alpha':alpha,'_token': token},//this _token should be as it is
success:function (result) {
alert(result);
}
});
}
</script>
In my laravel controller
public function getcart(Request $req)
{
return response ("its");
}

Related

Laravel Ajax validation worked [422 Status], but the page did not redirected if validation success and the data already inserted to DB

Laravel Ajax validation worked [422 Status], but the page did not redirected if validation success and the data already inserted to DB
There was an error [422 Unprocessable Entity] but i solved as below in code.
i tried to solve that, it works and redirects successfully without enable ajax validation.
// Routes
Route::name('authorCreatePost')->get('post/create', 'AuthorController#createPost');
Route::name('_authorCreatePost')->post('post/create', 'AuthorController#_createPost');
// Controller
public function _createPost(Request $request)
{
$validator = $request->validate([
'title' => 'required|string|max:255',
'content' => 'required|min:20',
]);
if (!$validator)
{
return response()->json(['errors'=>$validator->errors()->all()]);
} else {
$post = new Post();
$post->title = $request['title'];
$post->content = $request['content'];
$post->user_id = Auth::id();
if ($post->save()) {
return redirect(route('authorCreatePost'))->with('success', 'Post Created Successfully');
}
}
}
// View
<form action="{{ route('_authorCreatePost') }}" method="POST" id="create-post-form">
#csrf
<div class="card">
<div class="card-header text-center text-uppercase h4 font-weight-normal bg-light">
{{ __('Create Post') }}
</div>
#if(Session::has('success'))
<div class="alert alert-success">{{ Session::get('success') }}</div>
#endif
<div class="alert alert-danger" style="display:none"></div>
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<div class="card-body">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label for="title" class="require">{{ __('Title') }}</label>
<input id="title" name="title" class="form-control">
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label for="content" class="require">{{ __('Content') }}</label>
<textarea id="content" name="content" class="form-control" rows="6"></textarea>
</div>
</div>
</div>
</div>
<div class="card-footer">
<button id="submit" type="submit" class="btn btn-success btn-block">{{ __('Create') }}</button>
</div>
</div>
</form>
<script type="text/javascript">
$(document).ready(function(){
$('#create-post-form').submit(function(e){
validate_form(e);
});
function validate_form(e) {
e.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $("input[name='_token']").val(),
}
});
$.ajax({
url: "{{ route('_authorCreatePost') }}",
method: 'post',
data: {
_token: $("input[name='_token']").val(),
title: $('#title').val(),
content: $('#content').val(),
},
error: function(data){
if(data.status == 422) {
var errors = $.parseJSON(data.responseText).errors;
$('.alert-danger').empty();
$.each(errors, function(key, value){
$('.alert-danger').show();
$('.alert-danger').append('<p>'+value+'</p>');
});
}
},
});
}
});
</script>
[Validation works][1]
[Request and Response for 1][2]
[Here the data valid and inserted to DB][3]
[Request and Response for 3][4]
[1]: [https://i.stack.imgur.com/Shz0L.png][1]
[2]: [https://i.stack.imgur.com/FNbO7.png][1]
[3]: [https://i.stack.imgur.com/G6mSn.png][1]
[4]: [https://i.stack.imgur.com/QSr4s.png][1]
you can just return a success status from your controller
response()->json(['success' => 'success'], 200);
and then redirect in a success function in your ajax call
$.ajax({
url: "{{ route('_authorCreatePost') }}",
method: 'post',
data: {
//..
},
success: function(response){
window.location.href = "{{ route('authorCreatePost') }}";
},
error: function(data){
//...
},
});
or you can return the route to redirect from your controller
response()->json(['redirect' => route('authorCreatePost')], 200);
and then redirect to the route in the response on the ajax call success function
$.ajax({
url: "{{ route('_authorCreatePost') }}",
method: 'post',
data: {
//..
},
success: function(response){
window.location.href = response.redirect;
},
error: function(data){
//...
},
});

Laravel ajax put request return 500 internal server error

I have this error on my browser console: "PUT http://localhost:8000/post/2 500 (Internal Server Error)"
I use resource Controller and my route- Route::resource('post','PostController');
Here resource controller code for update post:
public function update(Request $request, $id)
{
$post = Post::findOrFail($id);
$post->name = $request->name;
$post->content = $request->content;
$post->save();
return response()->json($post);
}
Here my view code:
<form class="form-horizontal" role="form">
<div class="form-group">
<input type="text" class="none" id="id">
<label class="control-label col-sm-2">Name:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="name">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">content:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="content">
</div>
</div>
<div class="form-group">
<input type="submit" value="Edit" onclick="mainCatEdit();">
</div>
</form>
Ajax code:
function mainCatEdit() {
$.ajax({
url: '/maincategory/'+id,
type: 'PUT',
data: {
'_token': $('input[name=_token]').val(),
'id': $('#id').val(),
'name': $('#name').val(),
'content': $('#content').val()
},
success:function(data) {
console.log(data);
}
});
}
by the way i use meta token {{ csrf_token() }} on my file header.
but i get 500 internal server error on localhost.so someone help me.
You forgot to fill the data to your model, do this:
public function update(Request $request, $id)
{
$post = Post::findOrFail($id);
$post->fill([
$post->name = $request->name;
$post->content = $request->content;
]);
$post->save();
return response()->json($post);
}
you are trying to get the value of a token you did not set, lets look at your code again without testing, just try this
set this at the top of your page under the meta tags
<meta name="csrf-token" content="{{ csrf_token() }}">
then your ajax should be
function mainCatEdit() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: '/maincategory/'+id,
type: 'PUT',
data: {
'id': $('#id').val(),
'name': $('#name').val(),
'content': $('#content').val()
},
success:function(data) {
console.log(data);
}
});
}
i hope this helps

Laravel getting HttpException error when i post form by using ajax

in Laravel i want to post simple form data form by using Ajax i get this error:
exception: "Symfony\\Component\\HttpKernel\\Exception\\HttpException"
for example:
View:
<form action="#" method="POST" id="checkPageForAddToSystem">
{{csrf_field()}}
<div class="form-group">
<div class="col-md-12" style="padding: 0px;">
<input class="form-control" type="text" name="page_name">
</div>
</div>
<div class="text-right">
<button type="button" class="btn btn-link" data-dismiss="modal">
close
</button>
<button type="submit" class="btn btn-primary">
add
</button>
</div>
</form>
jQuery Ajax:
$('#checkPageForAddToSystem').on('submit', function (e) {
e.preventDefault();
let _token = $("input[name='_token']").val();
$.ajax({
method: 'POST',
url: '/panel/addInstagramPageByAjax',
header: {
'X-CSRF-TOKEN': _token
},
dataType: 'JSON',
success: function (data) {
console.log(data);
},
error: function (data) {
console.log(data);
}
});
});
Route:
Route::group(['namespace' => 'Dashboard', 'middleware' => ['auth:web'], 'prefix' => 'panel'], function () {
$this->post('addInstagramPageByAjax', 'ManageInstagramController#addInstagramPageByAjax');
});
Controller Action:
public function addInstagramPageByAjax(Request $request)
{
return response()->json(['sate' => true]);
}
Example usage for setting ajax header with CSRF-TOKEN ,
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
})
I hope this will help you.

Laravel 5.1 MethodNotAllowedHttpException Error

I'm using resource controller , when i submit form through ajax , it is showing method not allowed exception.
View
{!! Form::open(array('route' => 'product.store','class' => 'form-horizontal','id' => 'productform','name' => 'productform','files' => true)) !!}
{!! csrf_field() !!}
<div class="form-group" style="padding-top: 20px">
<label for="productName" class="col-sm-3 control-label">Product name</label>
<div class="col-sm-9">
{!! Form::text('productName',null, array('id'=> 'productName','class'=>'form-control','placeholder'=>'Product name'))!!}
</div>
</div>
<div class="form-group">
<div class="col-sm-9 col-sm-offset-3">
{!! Form::submit('Save', array('class' => 'btn btn-primary btn-block')) !!}
</div>
</div>
{!! Form::close() !!}
AJAX
$("#productform").submit(function () {
var token = $('[name=_token]').val();
$.ajax({
type: 'POST',
url: 'product/store',
data: {
id: '4',
_token: token,
},
success: function (data) {
alert('success');
return false;
}
})
return false;
});
routes.php
Route::resource('product', 'ProductController');
What is the problem here...Any help is much appreciated.
in jquery
var BASEURL = $("#baseURL").val()
in html
<input type="hidden" id="baseURL" value="{{ url('') }}" >
when you try to store data in laravel your URL must be.
url: 'product',
try to go on your CMD and type:
php artisan route:list
and check the URI of product.store Name then that will be you url in your AJAX.
in AJAX
try to set url in AJAX to be route
$("#productform").submit(function () {
var token = $('[name=_token]').val();
$.ajax({
type: 'POST',
url: '{{ route("product.store") }}',
data: {
id: '4',
_token: token,
},
success: function (data) {
alert('success');
return false;
}
});
return false;
});

Page is going blank after json response in laravel

Edit: Here's a little video of my problem: The video
I'm working on my socket based chat app in laravel 5.2. I was basing on this tutorial. Here's what I do and what's the problem:
I run my mysql server
I run redis-server
I run 'node server.js'
I run 'sudo php artisan serve --port=80'
I enter my site in the browser
I log in
I'm redirected to chat page
I enter an massage and send it
Page goes all white with '[]' being the only content
After running chat in two browsers and sending an message in one of them, the message appears properly on the other one. I'm running OS X ElCaptain.
Here's my routes file:
<?php
Route::get('/', function () {
return view('welcome');
});
Route::auth();
// Route::get('/chat', 'ChatController#index');
Route::get('/home', 'HomeController#index');
Route::group(['middleware' => 'web'], function () {
Route::auth();
Route::get('/chat', 'ChatController#index');
});
Route::post('sendmessage', 'ChatController#sendMessage');
Here's my ChatController:
<?php
namespace App\Http\Controllers;
use App\Http\Requests;
use Request;
use LRedis;
class ChatController extends Controller {
public function __construct() {
// $this->middleware('guest');
}
public function index() {
return view('chat.index');
}
public function sendMessage() {
$redis = LRedis::connection();
$data = [
'message' => Request::input('message'),
'user' => Request::input('user')
];
$redis->publish('message', json_encode($data));
/*
Content-Type is set to text/html because otherwise there was an error
in JavaScript console.log:
Resource interpreted as script but transferred with MIME type application/json.
*/
return response()->json([])->header('Content-Type', 'text/html');
}
}
Here's my view:
#extends('layouts.app')
#section('title', 'CityChat')
#section('styles')
<link rel="stylesheet" href="{{ URL::asset('assets/css/chat/index.css') }}">
<meta name="csrf-token" content="{{ csrf_token() }}">
#endsection
#section('scripts')
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<script src="{{ URL::asset('assets/js/chat/index.js') }}"></script>
#endsection
#section('content')
<div id="chat" class="ui container">
<div class="ui grid">
<div class="four wide column">
<div id="users" class="ui segment">
<div class="ui list">
(div.item>strong{username$})*50
</div>
</div>
</div>
<div class="twelve wide column">
<div id="messages" class="ui top attached segment">
</div>
<div class="ui bottom attached segment">
<form action="sendmessage" method="POST">
<input type="hidden" name="_token" value="{{ csrf_token() }}" >
<input type="hidden" name="user" value="{{ Auth::user()->name }}" >
<div class="ui fluid transparent input">
<input class="msg" type="text" name="message" placeholder="Tu wpisz swoją wiadomość">
<button type="button" class="ui button send">Wyślij</button>
{{-- <input type="button" class="send-msg" name="send" value="Send"> --}}
</div>
</form>
</div>
</div>
</div>
</div>
#endsection
Of course jquery is implemented in layouts.app before the index.js, which is:
var socket = io.connect('http://localhost:8890');
socket.on('message', function(data) {
data = jQuery.parseJSON(data);
console.log(data.user);
$("#messages").append("<p><strong>" + data.user + ":</strong> " + data.message + "</p>");
});
$(".send").on('submit', function(e) {
e.preventDefault();
var token = $("input[name ='_token']").val();
var user = $("input[name ='user']").val();
var msg = $(".msg").val();
if (msg != '') {
$.ajax({
type: "POST",
url: '{!! URL::to("sendmessage") !!}',
dataType: "json",
data: {
'_token': token,
'message': msg,
'user': user
},
success: function(data) {
console.log(data);
console.log();
$(".msg").val('');
}
});
} else {
alert("Please Add Message.");
}
})
And here's the server.js
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var redis = require('redis');
server.listen(8890);
io.on('connection', function(socket) {
console.log("client connected");
var redisClient = redis.createClient();
redisClient.subscribe('message');
redisClient.on("message", function(channel, data) {
console.log("mew message add in queue " + data['message'] + " channel");
socket.emit(channel, data);
});
socket.on('disconnect', function() {
redisClient.quit();
});
});
I don't know what else could be helpful. I hope you will help me guys :)

Categories