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");
}
});
Related
I try to get data by json using ajax.
My controller:
public function getFreeDay(Reservation $reservation): JsonResponse
{
//here will be other data, this is for test
try {
return response()->json([
'status' => 'success'
]);
} catch (\Exception $e) {
return response()->json([
'status' => 'error',
'message' => 'Wystąpił Błąd'
])->setStatusCode(500);
}
}
Route:
Route::post('/rezerwacja/{reservation}', [ReservationController::class, 'getFreeDay'])->name('getFreeDay');
ajax:
$("select#select-service").change(function () {
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
method: "GET",
url: getFreeDay + $(this).val(),
//data: {id: $(this).data('id')}
})
.done(function (data) {
window.location.reload();
})
.fail(function (data) {
console.log($(this).data('id'))
console.log(data.responseJSON.message);
});
});
const getFreeDay = "{{ url('rezerwacja')}}/";
HTML:
<select class="form-select" id="select-service">
<option selected>Wybierz usługe</option>
#foreach($services as $service)
<option value="{{$service->id}}">
{{$service->service_name}}
</option>
#endforeach
</select>
but each time, when i run ajax by my select list item it return 404.
I know that something is wrong with url and routing but i don't know what.
url and route(name) is different, in your url you used "getFreeDay" which is used as {{route('getFreeDay')}} instead
$.ajax({
type : 'POST',
url : '{{ route("getFreeDay") }}',
data : data
dataType : 'json'
}).done(function(){})
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.
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 send a store request to my laravel application through AJAX. The controller function works properly, but either I cannot get a success message in my ajax function, or the function on success is not working.
Ajax code:
$.ajax({
type: "POST",
url: 'http://127.0.0.1:8000/dreams',
data: {
description: description,
offset_top: offset_top,
offset_left : offset_left
},
success: function(msg){
console.log("done");
}
});
Controller's store function:
public function store(Request $request)
{
echo $request;
if (Auth::check()) {
$user = Auth::user();
$dream = new Dream($request->all());
if ($dream) {
$user->dreams()->save($dream);
$response = array(
'dream' => $dream,
'status' => 'success',
'msg' => 'Setting created successfully',
);
return \Response::json($response);
}
return \Response::json(['msg' => 'No model']);
} else {
return \Response::json('msg' => 'no auth');
}
}
Try to pass data in ajax using this way.
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "POST",
url: 'http://127.0.0.1:8000/dreams',
data: {
description: description,
offset_top: offset_top,
offset_left: offset_left
},
success: function(msg) {
console.log("done");
}
});
Try below code for store method:
public function store(Request $request)
{
if (Auth::check()) {
$user = Auth::user();
$dream = new Dream($request->all());
if ($dream) {
$user->dreams()->save($dream);
$response = array(
'dream' => $dream,
'status' => 'success',
'msg' => 'Setting created successfully',
);
return \Response::json($response);
}
return \Response::json(['msg' => 'No model']);
} else {
return \Response::json(['msg' => 'no auth']);
}
}
I have this codes,
var obj = '{"items":[{"Code":"c101","Description":"Car"}]}';
$.post('get-items',obj,function(){
});
I used this code,
file_get_contents('php://input')
Because I cant get the POST Data that is sent.
Using the above code, I get the raw POST Data.
How can I read data sent without using file_get_contents('php://input')?
Because I can't use file_get_contents('php://input').
Here is my Laravel controller function,
public function getItems()
{
$data = file_get_contents('php://input');
if(isset($data))
{
...
}
}
Laravel 5.3 expects input to be sent in array format https://laravel.com/docs/5.3/requests#retrieving-input
Request sent through jQuery
$.ajax({
url: 'http://weburl.com/api/user/create',
dataType: 'json',
type: 'POST',
data: {'user': user},
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err) {
console.error(null, status, err.toString());
}.bind(this)
});
Laravel UserController::create
public function create(Request $request)
{
$user = new User();
$user->name = $request->input('user.name');
$user->email = $request->input('user.email');
$user->password = $request->input('user.password');
$user->save();
return response($user, 201);
}
In a Laravel 5.2 controller's method you could do this:
public function store(Request $request)
{
$items = $request->input('items');
return [
'error' => false,
'items' => $items
];
}