Please help me I am getting error "Internal server error"
This is PostController.php in larvae
I am using ajax to save the post in database.
I also pasted javascript code so that some me can suggest the proper solution
public function create(Request $request)
{
if ($request->isMethod('get'))
return view('posts.form');
$rules = [
'title' => 'required',
'description' => 'required',
];
$validator = Validator::make($request->all(), $rules);
if ($validator->fails())
return response()->json([
'fail' =>true,
'errors' => $validator->errors()
]);
$post = new Post();
$post->title = $request->title;
$post->description = $request->description;
$post->save();
return response()->json([
'fail' => false,
'redirect_url' => url('posts')
]);
}
---------------java script code--------
$(document).on('submit', 'form#frm', function (event) {
event.preventDefault();
var form = $(this);
var data = new FormData($(this)[0]);
var url = form.attr("action");
$.ajax({
type: form.attr('method'),
url: url,
data: data,
cache: false,
contentType: false,
processData: false,
success: function (data) {
$('.is-invalid').removeClass('is-invalid');
if (data.fail) {
for (control in data.errors) {
$('#' + control).addClass('is-invalid');
$('#error-' + control).html(data.errors[control]);
}
} else {
ajaxLoad(data.redirect_url);
}
},
error: function (xhr, textStatus, errorThrown) {
alert("Error: " + data);
}
});
return false;
});
Do you have error reporting on ? If not you do it as below
Go to environment file of your project(.env)
Change below constant as stated
APP_DEBUG=true
Now send Ajax request once again it will show exact what error causing the internal server error , Check that line/function/file.
There will be syntax error or some logical coding error which causing the Ajax request internal server error.
Related
Here is my view(Ajax)
$('#basicInfoForm').submit(function(e){
e.preventDefault();
let formData = new FormData(this);
$.ajax({
type: "POST",
url: "{{route('profile.basic_info')}}",
dataType: 'json',
data: formData,
contentType: false,
processData: false,
beforeSend:function(){
$("#fountainG").fadeIn(1000);
},
success: function(response){
$.each(response.errors, function (key, value) {
$("#fountainG").fadeOut(1000);
$('.alert-danger').fadeIn(2000);
$('.alert-danger').append('<span>'+value+'</span>'+'<br>');
setTimeout(function() {
$('.alert-danger').fadeOut(4000, 'swing');
}, 3000);
});
},
error: function(data){
iziToast.error({
title: 'Upload Error',
message: data.avatar,
position: 'topRight'
});
}
});
});
And, here is my controller
public function updateBasicInformation(Request $request)
{
$basic_info = Validator::make($request->all(), [
'fullname' => 'required|min:2|max:255',
'phone_number' => 'required|numeric|min:10',
'email' => 'required|unique:users',
'country' => 'required',
'address' => 'required',
], [
'phone_number.min' => "The phone number must be at least 10 digits",
]);
if($basic_info->fails())
{
return response()->json([
'errors'=> $basic_info->errors()->all()
]);
}
}
So, basically, there is form with the ID:
basicInfoForm
and the div with the class -alert-danger displays the error. But when I submit the form more than once, it keeps on duplicating the errors even the ones that have been properly validated.
The error
How do I get around this, please?
I tried changing the dataType to json but it didn't make any difference.
I am new to Ajax and Laravel
On each submit clear all the errors from UI:
$('#basicInfoForm').submit(function(e){
e.preventDefault();
$('.alert-danger').remove();
// ...
});
on every submit call you are appending errors and not clearing previous error.
you can do this to fix this.
remove previous error div from DOM and append new error div on AJAX success.
success: function(response){
$('.alert-danger').remove();
$.each(response.errors, function (key, value) {
//
}
I have a Laravel application that works perfectly locally, but every AJAX call returns 404 when hosted. I'm unsure if this is from a sever config error, a missing php.ini setting, or something else? I've included an example of a failing call.
AJAX/JQ:
var url = "/final-review";
$("#review_note_text").change(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
$('#review_note_loader').show();
var formData = {
note_text: $('#review_note_text').val(),
};
var type = "POST";
var reviewNoteUrl = url + '/review-note';
$.ajax({
type: type,
url: reviewNoteUrl,
data: formData,
dataType: 'json',
success: function (data) {
$('#failure-message-review').hide();
$('#success-message-review p').html("Saved successfully" + '×');
$('#success-message-review').show();
$('#review_note_loader').removeClass("halted-loader").hide();
},
error: function (data) {
$('#review_note_loader').addClass("halted-loader");
$('#failure-message-review p').html("Something went wrong, your record was not updated. <strong>Error Code: " + data.status + "</strong>" + '×');
$('#failure-message-review').show();
}
});
});
My Corresponding Route:
Route::post('final-review/review-note', 'FinalReviewController#update_review_note');
Controller Function
public function update_review_note(Request $request){
$validatedData = $request->validate([
'note_text' => 'nullable|string',
]);
$note = \App\ReviewNote::create([
'note_text' => $request->get('note_text'),
'author' => Auth::user()->name,
'created_at' => now()
]);
return Response::json($note);
}
SOLVED:
I had to change the "url" var in my blade template to be:
var url = "{{ url('/final-review') }}";
In my AJAX I was defining "url" as "/final-review", which led to a route of "foobar.com/final-review/params" what I really needed was "foobar.com/app-name/final-review/params".
Testing locally, I did not have "app-name" in my URL.
testAjax function inside PostsController class:
public function testAjax(Request $request)
{
$name = $request->input('name');
$validator = Validator::make($request->all(), ['name' => 'required']);
if ($validator->fails()){
$errors = $validator->errors();
echo $errors;
}
else{
echo "welcome ". $name;
}
}
inside web.php file:
Route::get('/home' , function(){
return view('ajaxForm');
});
Route::post('/verifydata', 'PostsController#testAjax');
ajaxForm.blade.php:
<script src="{{ asset('public/js/jquery.js') }}"></script>
<input type="hidden" id="token" value="{{ csrf_token() }}">
Name<input type="text" name="name" id="name">
<input type="button" id="submit" class="btn btn-info" value="Submit" />
<script>
$(document).ready(function(){
$("#submit").click(function(){
var name = $("#name").val();
var token = $("#token").val();
/**Ajax code**/
$.ajax({
type: "post",
url:"{{URL::to('/verifydata')}}",
data:{name:name, _token: token},
success:function(data){
//console.log(data);
$('#success_message').fadeIn().html(data);
}
});
/**Ajax code ends**/
});
});
</script>
So when click on submit button by entering some data then the output message(echo "welcome ". $name;) is printing. But when I click on submit button with empty text box then it does not print the error message from the controller and it throws a 422 (Unprocessable Entity) error in console. Why my approach is wrong here and how can I print the error message then. Please help. Thank you in advance.
Your approach is actually not wrong, it's just, you need to catch the error response on your ajax request. Whereas, when Laravel validation fails, it throws an Error 422 (Unprocessable Entity) with corresponding error messages.
/**Ajax code**/
$.ajax({
type: "post",
url: "{{ url('/verifydata') }}",
data: {name: name, _token: token},
dataType: 'json', // let's set the expected response format
success: function(data){
//console.log(data);
$('#success_message').fadeIn().html(data.message);
},
error: function (err) {
if (err.status == 422) { // when status code is 422, it's a validation issue
console.log(err.responseJSON);
$('#success_message').fadeIn().html(err.responseJSON.message);
// you can loop through the errors object and show it to the user
console.warn(err.responseJSON.errors);
// display errors on each form field
$.each(err.responseJSON.errors, function (i, error) {
var el = $(document).find('[name="'+i+'"]');
el.after($('<span style="color: red;">'+error[0]+'</span>'));
});
}
}
});
/**Ajax code ends**/
On your controller
public function testAjax(Request $request)
{
// this will automatically return a 422 error response when request is invalid
$this->validate($request, ['name' => 'required']);
// below is executed when request is valid
$name = $request->name;
return response()->json([
'message' => "Welcome $name"
]);
}
Here's a better approach to validation:
In your controller:
public function testAjax(Request $request)
{
$this->validate($request, [ 'name' => 'required' ]);
return response("welcome ". $request->input('name'));
}
The framework then will create a validator for you and validate the request. It will throw a ValidationException if it fails validation.
Assuming you have not overriden how the validation exception is rendered here's the default code the built-in exception handler will run
protected function convertValidationExceptionToResponse(ValidationException $e, $request)
{
if ($e->response) {
return $e->response;
}
$errors = $e->validator->errors()->getMessages();
if ($request->expectsJson()) {
return response()->json($errors, 422);
}
return redirect()->back()->withInput($request->input())->withErrors($errors);
}
Again this is handled for you by the framework.
On the client side you should be able to do:
<script>
$(document).ready(function(){
$("#submit").click(function(){
var name = $("#name").val();
var token = $("#token").val();
/**Ajax code**/
$.ajax({
type: "post",
url:"{{URL::to('/verifydata')}}",
data:{name:name, _token: token},
success:function(data){
//console.log(data);
$('#success_message').fadeIn().html(data);
},
error: function (xhr) {
if (xhr.status == 422) {
var errors = JSON.parse(xhr.responseText);
if (errors.name) {
alert('Name is required'); // and so on
}
}
}
});
/**Ajax code ends**/
});
});
</script>
best way for handle in php controller :
$validator = \Validator::make($request->all(), [
'footballername' => 'required',
'club' => 'required',
'country' => 'required',
]);
if ($validator->fails())
{
return response()->json(['errors'=>$validator->errors()->all()]);
}
return response()->json(['success'=>'Record is successfully added']);
The code for form validation in Vannilla Javascript
const form_data = new FormData(document.querySelector('#form_data'));
fetch("{{route('url')}}", {
'method': 'post',
body: form_data,
}).then(async response => {
if (response.ok) {
window.location.reload();
}
const errors = await response.json();
var html = '<ul>';
for (let [key, error] of Object.entries(errors)) {
for (e in error) {
html += `<li>${error[e]}</li>`;
}
}
html += '</ul>';
//append html to some div
throw new Error("error");
})
.catch((error) => {
console.log(error)
});
Controller
use Illuminate\Support\Facades\Validator;//Use at top of the page
$rules = [
'file' => 'image|mimes:jpeg,png,jpg|max:1024',
'field1' => 'required',
'field2' => 'required'
];
$validator = Validator::make($request->post(), $rules);
if ($validator->fails()) {
return response()->json($validator->errors(), 400);
}
session()->flash('flash', ['status' => 'status', 'message' => 'message']);
Jquery Code:
let first_name= $('.first_name').val();
let last_name= $('.last_name').val();
let email= $('.email').val();
let subject= $('.subject').val();
let message= $('.message').val();
$('.show-message').empty();
console.log('clicked');
$.ajax({
type : 'POST',
url : '{{route("contact-submit")}}',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: {
first_name,
last_name,
email,
subject,
message,
},
success: function(data) {
console.log('data',data);
$('.show-message').html('Form Submitted');
},
error : function(data,data2,data3)
{
let response=data.responseJSON;
let all_errors=response.errors;
console.log('all_errors',all_errors);
$.each(all_errors,function(key,value){
$('.show-message').append(`<p>${value}</p>`);
});
}
});
Controller Code:
$validator=Validator::make($request->all(),[
'first_name'=>'required',
'last_name'=>'required',
'email'=>'required|email',
'subject'=>'required',
'message'=>'required',
]);
if($validator->fails())
{
return response()->json([
'success'=>false,
'errors'=>($validator->getMessageBag()->toArray()),
],400);
}
return response()->json([
'success'=>true,
],200);
See More Details at: https://impulsivecode.com/validate-input-data-using-ajax-in-laravel/
I have an Ajax call which sends user form input to be processed in the back end. The controller in the back-end sends back result as JSON, when the form is submitted the page reloads and redirects to a blank page with raw JSON instead of the json being picked up by AJAX.
This is the Ajax call:
<script type="text/javascript">
$(document).ready(function(){
$('form').on('submit', '#topup-form', function(e){
e.preventDefault();
$.ajax({
url: $('form').attr('action'),
method: 'post',
data: $('form').serialize(),
success: function(result){
alert(result);
},
error: function(errorData){
alert(errorData);
}
});
});
$.ajaxSetup({
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
})
});
</script>
This is the Laravel controller, if the validation fails it sends Json, if the user is authenticated, it redirects the user, else it returns 401 asking user to login.
public function topupPost(Request $request) {
$validator = [
'topupAmount'=> 'required|integer|between:10,500',
'phonenumber'=> 'required|regex:/^05[602][0-9]{7}$/',
];
$inputs = $request->all();
Log::info($inputs);
$validator = Validator::make($inputs, $validator);
if($validator->fails()){
return Response::json([
'error' => true,
'message' => $validator->messages(),
'code' => 400
], 400);
}
elseif (Auth::check()) {
return view('pages.checkout', compact('inputs'));
}
return Response::json([
'error' => true,
'message' => "Please login first",
'code' => 401
], 401);
}
What happens is that nothing pops up as an alert but the user is redirected to a page with the raw JSON.
I had faced a similar issue
I solved it by changing the submit button type to "button" so that the form does not auto submit. my ajax code is below:
$(document).ready(function() {
$("#submit").click(function() {
var loginForm = $("#contactForm");
var formData = loginForm.serialize();
/*alert(formData);*/
$.ajax({
url: /*you URL*/,
type:'post',
data:formData,
success:function(data){
//alert(data); //for redirecting instead of alert try below code
if(data == "") { //True Case i.e. passed validation
alert('error')
}
else { //False Case: With error msg
alert(data); //$msg is the id of empty msg
}
},
error: function (data) {
/*console.log(data);*/
alert(data);
}
});
});
/*alert('Successfully Loaded');*/
});
also your php response handle seems fine. hope this helps
I am new to laravel framework and started following the laravel tasks tutorial.
I am trying to pass via ajax request the name of the task in order to save it in the database.
front end:
var taskdata= {
"name": $("#new_task").val()
};
//console.log(JSON.stringify(taskdata));
$.ajax({
url: '/task',
type: 'POST',
data: taskdata,
contentType: 'json',
processData: false,
success: function(result) {
alert("success");
}
});
server side:
Route::post('/task', function (Request $request) {
//die(var_dump($request->json("name")));
$validator = Validator::make(json_decode($request->getContent(), true), [
'name' => 'required|max:255',
]);
if ($validator->fails()) {
return redirect('/')
->withInput()
->withErrors($validator);
}
$task = new \App\Task;
$task->name = $request->name;
$task->save();
return redirect('/');
});
When using the validate method during an AJAX request, Laravel will not generate a redirect response. Instead, Laravel generates a JSON response containing all of the validation errors. This JSON response will be sent with a 422 HTTP status code.
Hence you could change your controller method to
Route::post('/task', function (Request $request) {
$validator = Validator::make($request->all(), [
'name' => 'required|max:255',
]);
if ($validator->fails()) {
return $validator->errors()->all();
}
$task = new \App\Task;
$task->name = $request->name;
$task->save();
return url("/");
});
and your ajax method as
var taskdata= {
"name": $("#new_task").val(),
"_token" : "{{ csrf_token() }}"
};
$.ajax({
url: '/task',
type: 'POST',
data: taskdata,
contentType: 'json',
success: function(result) {
console.log(result); // The url
},
error: function (data) {
console.log(data.responseJSON); // Here you could see the error
}
});
Here's a better way to solve that:
Route::post('/task', function (Request $request) {
$validator = Validator::make($request->all(), [
'name' => 'required|max:255',
]);
if ($validator->fails()) {
throw new ValidationException($validator); //Your error handler should send JSON or redirect as appropriate.
}
$task = new \App\Task;
$task->name = $request->name;
$task->save();
if ($request->expectsJson()) {
return response()->json(true); //Success
} else {
return redirect()->to("/");
}
});
Update:
You also need to let jQuery process the data so it constructs a proper query:
var taskdata= {"name": $("#new_task").val()};
//console.log(JSON.stringify(taskdata));
$.ajax({
url: '/task',
type: 'POST',
data: taskdata,
contentType: 'json',
processData: true, //Or remove it completely since the default is true
success: function(result) {
alert("success");
}
});