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/
Related
My Ajax Code
Query(document).ready(function(){
jQuery('#password_form').click(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
jQuery.ajax({
url: "{{ url('/changepassword') }}",
method: 'post',
data: {
password: jQuery('#password').val(),
new_password: jQuery('#new_password').val(),
password_confirmation: jQuery('#password_confirmation').val()
},
success: function(result){
console.log(result);
}});
});
});
My Controller:
public function changepassword(Request $request){
$user = Auth::guard()->user();
$request_data = $request->All();
$validator = $this->admin_credential_rules($request_data);
if($validator->fails()) {
$errors = $validator->errors();
$errors = json_decode($errors);
return response()->json([
'success' => false,
'message' => $errors
], 422); } else {
$current_password = $user->password;
if(md5($request_data['password']) == $current_password) {
$user_id = $user->id;
$obj_user = User::find($user_id);
$obj_user->password = md5($request_data['new_password']);
$obj_user->save();
return \Illuminate\Support\Facades\Redirect::to('mujucet')
->with("modal_message_success", "Password has been changed successfully");
} else {
return \Illuminate\Support\Facades\Redirect::to('mujucet')
->with("modal_message_danger", "wong old password");
}
}
}
I am have a popup a there is three fields
1- password
2- new_password
3- password_confirmation
Before ajax my form was submitting but i want to submit form with ajax so my page should not be reload and my success and error message should be shown on my popup form but here when i hit button its reload and also values are not submitted.
I dont know what is wrong with my ajax request.
Your help will be highly appreciated!
Thanks in advance please need your help.
$("#myform").submit(function(e){
e.preventDefault();
//put your ajax here
});
You need to prevent the form from submitting using the code above.
Your popup submit button should be button not submit
<button type="button" class="btn btn-primary" title=""
id="btn_submit">add</button>
<script>
$('#btn_submit').click(function () {
var type = $('#contain-type').val(); // take your all values you want to send
/*ajax call*/
$.post(baseUrl + '/admin/confirmation-mail(your route)',{"_token": "{{
csrf_token() }}", id: parameter, subject: parameter},
function (data, status) {
alert(data);
});
)};
</script>
Controller
public function name(Request $request){
dd(request->all()); //add your php code
}
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.
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");
}
});
I am working with Laravel 4 and I want to perform validation with Ajax. I have 2 main problems:
1. The URL at Ajax is static, which means that if I have my app online I should put the URL for online and locally doesn't works
2. my route is insur_docs/{id} how should be URL for this?
jQuery('form#insur_docs_update').submit(function()
{
jQuery.ajax({
url: "http://localhost:8080/insur_docs/{id}", //my url I don't know how to put it
type: "post",
data: jQuery('form#insur_docs_update').serialize(),
datatype: "json",
beforeSend: function()
{
jQuery('#ajax-loading').show();
jQuery(".glyphicon-warning-sign").hide();
}
})
.done(function(data)
{
$('#validation-div').empty()
if (data.validation_failed === 1)
{
var arr = data.errors;
jQuery.each(arr, function(index, value)
{
if (value.length !== 0)
{
$("#validation-div").addClass('alert alert-danger');
document.getElementById("validation-div").innerHTML += '<span class="glyphicon glyphicon-warning-sign"></span>' + value + '<br/>';
}
});
jQuery('#ajax-loading').hide();
}
})
.fail(function(jqXHR, ajaxOptions, thrownError)
{
alert('No response from server');
});
return false;
});
routes.php
Route::get('insur_docs/{id}', 'Insur_DocController#edit');
controller
public function update($id) {
Input::flash();
$data = [
"errors" => null
];
$rules = array(
"ownership_cert" => "required",
"authoriz" => "required",
"drive_permis" => "required",
"sgs" => "required",
"tpl" => "required",
"kasko" => "required",
"inter_permis" => "required",
);
$validation = Validator::make(Input::all(), $rules);
if ($validation->passes()) {
$car_id = DB::select('select car_id from insur_docs where id = ?', array($id));
$data = InsurDoc::find($id);
$data->ownership_cert = Input::get('ownership_cert');
$data->authoriz = Input::get('authoriz');
$data->drive_permis = Input::get('drive_permis');
$data->sgs = Input::get('sgs');
$data->tpl = Input::get('tpl');
$data->kasko = Input::get('kasko');
$data->inter_permis = Input::get('inter_permis');
$data->save();
return Redirect::to('car/' . $car_id[0]->car_id);
} else {
if (Request::ajax()) {
$response_values = array(
'validation_failed' => 1,
'errors' => $validation->errors()->toArray()
);
return Response::json($response_values);
}
}
}
Use laravel's url generator helper to create your form's action:
<form action="{{ URL::action('Insur_DocController#edit', $id) }}" method="post">
You can access it in your javascript:
jQuery('form#insur_docs_update').submit(function()
{
var url = $(this).attr("action");
jQuery.ajax({
url: url,
type: "post",
data: jQuery('form#insur_docs_update').serialize(),
datatype: "json",
beforeSend: function()
{
jQuery('#ajax-loading').show();
jQuery(".glyphicon-warning-sign").hide();
}
});
}
EDIT
You're second problem is that you're redirecting in response to the ajax call, and that does not redirect the page. You'll need to return the url and do the redirect in javascript like this.
Controller:
return Response::json(["redirect_to" => 'car/' . $car_id[0]->car_id]);
JS (just the relevant part):
.done(function(data)
{
$('#validation-div').empty()
if (data.validation_failed === 1)
{
// your code
} else {
window.location = data.redirect_to;
}
})
var myUrlExtension = "whatever.php"
and inside the ajax
url: "http://localhost:8080/insur_docs/" + myUrlExtension