Im trying to submit a form using a modal but im getting this error. 422 (Unprocessable Entity). In my Menu Model i specified my table name $menu using protected $table ='menu';
<script type="text/javascript">
$(document).ready(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
My read function is completely working but the adding is not working
function load(){
$.get('dash',function(data){
$.each(data,function(key,val){
$('#data')
.append("<tr>"+
"<td>"+val.Item_Code+"</td>"+
"<td>"+val.Name+"</td>"+
"<td>"+val.Printer+"</td>"+
"<td>"+val.Category+"</td>"+
"<td>"+val.Price+"</td>"+
"<td>"+val.Stocks+"</td>"+
"<td>"+val.Image+"</td>"+
"<td>"+
"<button type='button' class='btn btn-outline-success'>
<i class='fa fa-clipboard'></i> Edit</button>"+
"<button type='button' class='btn btn-outline-danger'><i
class='fa fa-trash'></i> Delete</button>"+
"</td>"+
"</tr>");
});
});
}
My add function does not add the data inputted in the modal
load();
$('form').submit(function(e){
e.preventDefault();
Item_Code = $('#Item_code').val();
Name = $('#Name').val();
Printer = $('#Printer').val();
Category = $('#Category').val();
Price = $('#Price').val();
Stocks = $('#Stocks').val();
Image = $('#Image').val();
$.post('/post',{Item_Code:Item_Code,Name:Name,
Printer:Printer,Category:Category,Price:Price,
Stocks:Stocks,Image:Image},function(data){
$('#Item_Code').val('');
$('#Name').val('');
$('#Printer').val('');
$('#Category').val('');
$('#Price').val('');
$('#Stocks').val('');
$('#Image').val('');
load();
});
});
});
My method
public function post(Request $req)
{
if($req->ajax()){
$req->validate([
'Item_Code'=>'required',
'Name'=>'required',
'Printer'=>'required',
'Category'=>'required',
'Price'=>'required',
'Stocks'=>'required',
'Image'=>'required'
]);
$post = new Menu;
$post->Item_Code = $req->Item_Code;
$post->Name = $req->Name;
$post->Printer = $req->Printer;
$post->Category = $req->Category;
$post->Price = $req->Price;
$post->Stocks = $req->Stocks;
$post->Image = $req->Image;
$post->save();
return response()->json();
}
}
My routes.
Route::post('/post', 'AdminController#post')->name('create.inventory');
My modal
<div class="modal-body">
<form>
<label for="required-input" class="require">Item Code:</label>
<input type = "text" class="form-control" placeholder="Item Code" id = "Item_Code">
<label for="placeholder-input" class="require">Name:</label>
<input type= "text" class="form-control" placeholder="Name" id = "Name">
<label for="single-select" class="require">Printer</label>
<select id="Printer" class="form-control">
<option>Kitchen</option>
<option>Bar</option>
</select>
<label for="single-select">Category</label>
<select id="Category" class="form-control">
<option>Japanese</option>
<option>Beverage</option>
</select>
<label for="required-input" class="require">Input Price:</label>
<input type ="number" class="form-control" placeholder="Price" id="Price">
<label for="required-input" class="require">Quantity:</label>
<input type ="number" class="form-control" placeholder="Quantity" id="Stocks">
<label for="required-input" class="require">Image:</label>
<input type = "file" class="form-control" id="Image">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-link" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
422 is the status code for Laravel validation
Check the input data, Probably one of values is null
This is how I would make such a function
bootstrap model - I added an ID to the form and I also added a div with the class of messages for the validation and success messages.
<div class="modal-body">
<div class="messages"></div>
<form id="productForm">
{{ csrf_field() }}
<label for="required-input" class="require">Item Code:</label>
<input type = "text" class="form-control" placeholder="Item Code" id = "Item_Code">
<label for="placeholder-input" class="require">Name:</label>
<input type= "text" class="form-control" placeholder="Name" id = "Name">
<label for="single-select" class="require">Printer</label>
<select id="Printer" class="form-control">
<option>Kitchen</option>
<option>Bar</option>
</select>
<label for="single-select">Category</label>
<select id="Category" class="form-control">
<option>Japanese</option>
<option>Beverage</option>
</select>
<label for="required-input" class="require">Input Price:</label>
<input type ="number" class="form-control" placeholder="Price" id="Price">
<label for="required-input" class="require">Quantity:</label>
<input type ="number" class="form-control" placeholder="Quantity" id="Stocks">
<label for="required-input" class="require">Image:</label>
<input type = "file" class="form-control" id="Image">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-link" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
Ajax code
<script>
var form = $('#productForm');
var formData = form.serialize();
var createUrl = '{{ route('create.inventory') }}';
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
url: createUrl,
type: 'post',
data: formData,
dataType: 'json',
success: function (response) {
var successHtml = '<div class="alert alert-success">'+
'<button type="button" class="close" data-dismiss="alert">×</button>'+
'<strong><i class="glyphicon glyphicon-ok-sign push-5-r"></i></strong> '+ response.message +
'</div>';
var messages = $('.messages');
$(messages).html(successHtml);
window.setTimeout(function() {
location.reload();
}, 800);
},
error: function(response) {
var errors = response.responseJSON.errors;
var errorsHtml = '<div class="alert alert-danger"><ul>';
$.each( errors, function( key, value ) {
errorsHtml += '<li>'+ value[0] + '</li>';
});
errorsHtml += '</ul></div';
$('.messages').html(errorsHtml);
}
});
});
</script>
for the controller code.
make sure you add the use Validator; to the controller
now will make the validation in the controller
public function post(Request $request)
{
if ($request->ajax()) {
$validator = Validator::make($request->all(), [
'Item_code' => 'required',
'Name' => 'required',
'Printer' => 'required',
'Category' => 'required',
'Price' => 'required',
'Stocks' => 'required',
'Image' => 'required',
]);
if ($validator->fails()) {
return response()->json(['success' => false, 'errors' => $validator->errors()], 422);
} else {
$post = new Menu([
'Item_name' => $request->input('Item_code'),
'Name' => $request->input('Name'),
'Printer' => $request->input('Printer'),
'Category' => $request->input('Category'),
'Price' => $request->input('Price'),
'Stocks' => $request->input('Stocks'),
'Images' => $request->input('Images')
]);
$post->save();
return response()->json(['success' => true, 'message' => 'success'], 200);
}
}
}
Related
I use the Modal display field in the Partial View to input data for the User, and use data-url=#url.action("Create") in the main screen to call Modal.
And wrote Autocomplete JavaScript in Partial View.
It works perfectly before using Ajax Post.
But after going through Ajax, the JavaScript cannot be used when it returns because of an error.
How can I make corrections?
Main View
<div id="PlaceHolderHere" data-url="#Url.Action("Create")"></div>
Ajax Code
$(function () {
var PlaceHolderElement = $('#PlaceHolderHere');
$('button[data-toggle="ajax-modal"]').click(function (event) {
event.preventDefault();
var url = $(this).data('url');
$.get(url).done(function (data) {
PlaceHolderElement.html(data);
PlaceHolderElement.find('.modal').modal('show');
});
});
PlaceHolderElement.on('click', '[data-save="modal"]', function (event) {
event.preventDefault();
var form = $(this).parents('.modal').find('form');
var actionUrl = form.attr('action');
var sendData = new FormData(form.get(0));
console.log(sendData);
$.ajax({
url: actionUrl,
method: 'post',
data: sendData,
processData: false,
contentType: false,
cache: false,
success: function (redata) {
console.log(redata);
if (redata.status === "success") {
PlaceHolderElement.find('.modal').modal('hide');
}
else {
var newBody = $('.modal-body', redata);
var newFoot = $('.modal-footer', redata);
PlaceHolderElement.find('.modal-body').replaceWith(newBody);
PlaceHolderElement.find('.modal-footer').replaceWith(newFoot);
}
},
error: function (message) {
alert(message);
}
})
})
})
Partial View of JavaScript part
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script src="~/bootstrap-autocomplete/dist/latest/bootstrap-autocomplete.min.js"></script>
$('#BossName').autoComplete({
resolver: 'custom',
minLength: 2,
formatResult: function (item) {
return {
value: item.value,
text: "[" + item.value + "] " + item.text,
}
},
noResultsText:'There is no matching data, please confirm whether there is data in the company field',
events: {
search: function (qry, callback) {
// let's do a custom ajax call
$.ajax(
'#Url.Action("GetRolesByAutoComplete","Roles")',
{
data: {
'q': qry,
'key': document.getElementById('CompanyCode').value
}
}
).done(function (res) {
callback(res)
});
}
}
});
$('#BossName').on('autocomplete.select', function (evt, item) {
console.log(item);
$('#BossID').val(item.value);
$('#BossName').val(item.text);
});
Partial View of Modal
<div class="modal fade" id="AddEditRoles" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="AddEditRolesLabel">Add New Roles</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form asp-action="Create" id="Edit">
<div class="input-group">
<span class="input-group-text">#Html.DisplayNameFor(m => m.RolesCode)</span>
#if (Model != null && Model.RolesCode != null)
{
<input asp-for="RolesCode" class="form-control" readonly />
}
else
{
<input asp-for="RolesCode" class="form-control" autocomplete="off" />
}
<span asp-validation-for="RolesCode" class="text-danger"></span>
</div>
<div class="input-group">
<span class="input-group-text">#Html.DisplayNameFor(m => m.Title)</span>
<input asp-for="Title" class="form-control" autocomplete="off" />
<span asp-validation-for="Title" class="text-danger"></span>
</div>
<div class="input-group">
<span class="input-group-text">#Html.DisplayNameFor(m => m.CompanyCode)</span>
<input type="text" asp-for="CompanyCode" class="form-control col-md-3" readonly />
<input type="text" id="CompanyName" class="form-control" autocomplete="off"
placeholder="Please type Key word" />
<span asp-validation-for="CompanyCode" class="text-danger"></span>
</div>
<div class="input-group">
<span class="input-group-text">#Html.DisplayNameFor(m => m.BossID)</span>
<input asp-for="BossID" type="text" class="form-control col-md-3" readonly />
<input id="BossName" type="text" class="form-control" autocomplete="off"
placeholder="Please type Key word" />
<span asp-validation-for="BossID" class="text-danger"></span>
</div>
</form>
</div>
<div class="modal-footer">
<div class="text-danger">#Html.ValidationMessage("error")</div>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button id="Save" type="button" class="btn btn-primary" data-save="modal">Save changes</button>
</div>
</div>
</div>
</div>
You send data to the server, but when it fails you replace modal contents.
Replacing HTML destroys everything that was already there, so you wipe everything that was done by your autocomplete plugin.
All you need to do is to initialize autocomplete again:
success: function (redata) {
if (redata.status === "success") {
} else {
var newBody = $('.modal-body', redata);
var newFoot = $('.modal-footer', redata);
PlaceHolderElement.find('.modal-body').replaceWith(newBody);
PlaceHolderElement.find('.modal-footer').replaceWith(newFoot);
// INITIALIZE AUTOCOMPLETE HERE
}
},
I am new to codeigniter & javascript, I have been working with the form submission through ajax in codeigniter. I need to use form validation on the text field & other inputs in the form. I searched the web & couldn't find any resources or references. Currently my form submission is working fine, I just need to validate my inputs using Jquery or ajax.
Here is my Model
class test_model extends CI_Model {
function save_data()
{
$name = $this->input->post('Name');
$email = $this->input->post('Email');
$contact = $this->input->post('Contact');
$sex = $this->input->post('Sex');
$country = $this->input->post('Country');
$data = array(
'Name' => $name,
'Email' => $email,
'Contact' => $contact,
'Sex' => $sex,
'Country' => $country);
$result = $this->db->insert('test2',$data);
return $result;
}
}
My Controller just forwards the data to Model
class test extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->model('test_model');
$this->load->helper('url');
}
function index() {
$this->load->view('test_index');
}
function save() {
$data = $this->test_model->save_data();
echo json_encode($data);
}
}
Here is my View
<form>
<div class="container" style="padding-top: 80px;">
<div class="form-group">
<label for="Name">First Name :</label>
<div class="col-md-4">
<input type="text" name="Name" id="Name" class="form-control" placeholder="Your Name..">
</div>
</div>
<div class="form-group">
<label for="Contact">Contact :</label>
<div class="col-md-4">
<input type="text" class="form-control" id="Contact" name="Contact" placeholder="Your Contact No..">
</div>
</div>
<div class="form-group">
<label for="Sex" class="col-md-1">Gender :</label>
<div class="form-check form-check-inline">
<label >
<input type="radio" class="form-check-input" name="Sex" id="Sex" value="Male">Male </label><span style="padding-right: 10px;"></span>
<label>
<input type="radio" class="form-check-input" name="Sex" id="Sex" value="Female">Female </label>
</div>
</div>
<div class="form-group">
<select class="form-control custom-select col-md-4" id="Country" name="Country">
<option value="">Select Country</option>
<option value="Europe">Europe</option>
<option value="United Stated of America">United States of America</option>
<option value="India">India</option>
</select>
</div>
<div class="form-group">
<button type="button" type="submit" id="btn_save" class="btn btn-primary" >
<span class="spinner-border spinner-border-sm"></span>Create</button>
<button type="button" class="btn btn-secondary" >Close</button>
</div>
</div>
</form>
My JS code is below :
$('#btn_save').on('click',function() {
var Name = $('#Name').val();
var Email = $('#Email').val();
var Contact = $('#Contact').val();
var Sex = $('input[name="Sex"]:checked').val();
var Country = $('#Country').find(":selected").val();
$.ajax({
type : "POST",
url : "https://localhost/newCrud/test/save",
dataType : "JSON",
data: {"Name":Name, "Email":Email, "Contact":Contact, "Sex":Sex, "Country":Country},
success : function (data) {
if(data == 1) {
$('[name = "Name"]').val("");
$('[name = "Email"]').val("");
$('[name = "Contact"]').val("");
$('[name = "Sex"]').val("");
$('[name = "Country"]').val();
alert("Data Inserted"); }
}
});
return false;
});
});
Guys, my above code works just fine, I need your help to know how can i validate my form using ajax, as it is already passing data to the model from here. As far I've known that Codeigniter form_validate method can't be used in ajax form submission. Really need your help guys. Thanks for your time & suggestions.
Why not????
You can use CI validation as it is a built in server side validation method and you are hitting your server through AJAX
You need to alter your code a bit
$.ajax({
type : "POST",
url : "https://localhost/newCrud/test/save",
dataType : "JSON",
data: {"Name":Name, "Email":Email, "Contact":Contact, "Sex":Sex, "Country":Country},
success : function (data) {
if(data == 1) {
$('.form-group').removeClass('has-error');
$('[name = "Name"]').val("");
$('[name = "Email"]').val("");
$('[name = "Contact"]').val("");
$('[name = "Sex"]').val("");
$('[name = "Country"]').val();
alert("Data Inserted");
}
},
error : function (error) {
if(error.status == 500){
var response = error.responseJSON.validation;
$('.form-group').removeClass('has-error');
$.each(response, function(index, item) {
$('[name='+index+']').closest('.form-group').addClass('has-error');
});
}
}
});
Update your controller as like this
public function save() {
// add this if not loaded earlier
$this->load->library('form_validation');
$this->form_validation->set_rules('Name','Name', 'required');
$this->form_validation->set_rules('Contact','Contact', 'required');
$this->form_validation->set_rules('Email','Email Address','required|valid_email');
if ($this->form_validation->run() == FALSE) {
$validation = $this->form_validation->error_array();
return $this->output
->set_content_type('application/json')
->set_status_header(500)
->set_output( json_encode(array(
'validation' => $validation,
'message' => 'validation error !!!'
)) );
}
$data = $this->test_model->save_data();
echo json_encode($data);
}
Here i did validation for 3 fields name, email and contact. Also i used bootstrap error class 'has-error' to highlight failed elements.
Simply use the jQuery Validate plugin (https://jqueryvalidation.org/).
jQuery:
$(document).ready(function () {
$('#myform').validate({ // initialize the plugin
rules: {
field1: {
required: true,
email: true
},
field2: {
required: true,
minlength: 5
}
}
});
});
HTML:
<form id="myform">
<input type="text" name="field1" />
<input type="text" name="field2" />
<input type="submit" />
</form>
I'm trying to submit a form request and store data without page refresh or redirect. And send success message to
#if (session('message'))
<div class="alert alert-success">
{{ session('message') }}
</div>
#endif
,I get white page after clicking submit button with the following response
{
"msg": "Setting created successfully"
}
The html Form:
<form method="POST" action="/mail/store" id="contactForm">
#csrf
<div style="display: flex;" class="name-email">
<div class="form-group col-sm-6 fl_wrap">
<input type="text" name="name" value="{{ old('name') }}" id="name"
class="form-control fl_input" placeholder="Name"
required>
</div>
<div class="form-group col-sm-6 fl_wrap">
<input type="text" name="email" value="{{ old('email') }}" id="email"
placeholder="Email"
class="form-control fl_input" required>
</div>
</div>
<div class="form-group col-sm-12 fl_wrap mt-2">
<textarea type="text" name="message" rows="7" value="{{ old('message') }}" id="message"
class="form-control fl_input" placeholder="message"
required></textarea>
</div>
<div class="form-group text-center mt-5">
<button type="submit" value="save" id="submit" class="btn btn-warning submit"
style="color: white;background: rgb(59, 199, 246); border-color: rgb(59, 199, 246); width: 140px;">
send
</button>
</div>
</form>
Js Code:
I think there's something wrong or missing with ajax code but I don't know where
<script src="/js/jquery.min.js"></script>
<script !src="" type="text/javascript">
$(document).ready(function () {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#contactForm').on('submit',function (e) {
e.preventDefault();
var name = $('#name').val();
var email = $('#email').val();
var message = $('#message').val();
$.ajax({
type: "POST",
url: host+'/mail/store',
data: { name:name ,email:email,message:message},
success: function( msg ) {
$("body").append("<div>"+msg+"</div>");
}
});
$.post('contactForm', { name:name, email:email, message:message }, function () {
console.log(data);
$('#postRequestData').html(data);
});
});
});
store function in controller
public function store(Request $request)
{
$mail = new Mail();
$mail->name = $request->name;
$mail->mail = $request->email;
$mail->message = $request->message;
$mail->save();
$result = array(
'msg' => 'Setting created successfully' );
return Response::json($result);
}
Routes
Route::get('/mail','MailsController#create');
Route::post('/mail/store','MailsController#store');
Try this one:
$.post("{{ url('mail/store') }}", {
name, email, message, '_token': "{{ csrf_token() }}"
}, function(data) {
$('#postRequestData').html(data.message);
});
I have a problem when I add input type="file" to the dynamic form insert
all works before I tried to add input type="file"
also, I got no error message on the browser
addMore.blade.php
<form name="add_name" id="add_name" enctype="multipart/form-data">
<input type="text" name="name[]" placeholder="Enter your Name" class="form-control name_list" />
<input type="file" name="proposal[]" id="proposal" class="form-control name_list" />
<button type="button" name="add" id="add" class="btn btn-success">Add More</button> //add dynamically input
<input type="button" name="submit" id="submit" class="btn btn-info" value="Submit" />
</form>
here the ajax
$('#submit').click(function(){
$.ajax({
url:postURL,
method:"POST",
data:$('#add_name').serialize(),
type:'json',
success:function(data)
{
if(data.error){
printErrorMsg(data.error);
}else{
i=1;
$('.dynamic-added').remove();
$('#add_name')[0].reset();
$(".print-success-msg").find("ul").html('');
$(".print-success-msg").css('display','block');
$(".print-error-msg").css('display','none');
$(".print-success-msg").find("ul").append('<li>Record Inserted Successfully.</li>');
// location.href = "http://www.example.com/ThankYou.html"
}
}
});
});
//note the dynamic add input filed button already works #add
//already tried remove serialize() still not work
//also i got no error message on the browser
here the HomeController.php
public function addMorePost(Request $request){
$name = $request->name;
$proposal = $request->file('proposal')->store('proposals'); //already change to ->file(proposal[]) not work
for ($count = 0; $count < count($name); $count++) {
$data = array(
'name' => $name[$count],
'proposal' => $proposal[$count] //already change 'proposal[]' but not work
);
TagList::create($data);
}
return response()->json(['success' => 'done']);
}
you are using serialize while sending data via ajax, you need to pass FormData with ajax.
Below is a complete code for sending file with ajax, and also you can trigger event when form is submitted so you can get entire formdata:
<form name="add_name" id="add_name" enctype="multipart/form-data" action="home" method="post">
#csrf
<input type="text" name="name[]" placeholder="Enter your Name" class="form-control name_list" />
<input type="file" name="proposal[]" id="proposal" class="form-control name_list" />
<button type="button" name="add" id="add" class="btn btn-success">Add More</button>
<input type="submit" name="submit" id="submit" class="btn btn-info" value="Submit" />
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
$('#add_name').submit(function(e) {
e.preventDefault();
var form = $(this);
var formData = new FormData(this);
$.ajax({
url: form.attr('action'),
method: "POST",
data: formData,
type: 'json',
processData: false,
contentType: false,
success: function(data) {
if (data.error) {
printErrorMsg(data.error);
} else {
i = 1;
$('.dynamic-added').remove();
$('#add_name')[0].reset();
$(".print-success-msg").find("ul").html('');
$(".print-success-msg").css('display', 'block');
$(".print-error-msg").css('display', 'none');
$(".print-success-msg").find("ul").append('<li>Record Inserted Successfully.</li>');
// location.href = "http://www.example.com/ThankYou.html"
}
}
});
return false;
});
</script>
HomeController.php
public function addMorePost(Request $request){
$name = $request->name;
$proposal = $request->file('proposal');
foreach ($proposal as $file) {
$file->store('proposals');
}
for ($count = 0; $count < count($name); $count++) {
$data = array(
'name' => $name[$count],
'proposal' => $proposal[$count] //already change 'proposal[]' but not work
);
TagList::create($data);
}
return response()->json(['success' => 'done']);
}
Im creating a validation now using laravel5.1 with ajax of jquery. Everything works fine. But, what I want is to display the errors each <inputs> just like when using validation without ajax. Please see my code below, and the picture for the sample output. I've also tried it with #if of blade(laravel), but not working.
Note: Im using bootstrap framework too.
<div class="row">
<div class="col-md-6">
<div id="result">
<ul></ul>
</div>
<form action="" method="post" id="create">
<div class="form-group">
<label for="name" class="control-label">Name</label>
<input type="text" name="name" id="name" class="form-control">
</div>
<div class="form-group">
<label for="description" class="control-label">Description</label>
<textarea name="description" id="description" cols="30" rows="10" class="form-control"></textarea>
</div>
<div class="form-group">
<label for="type" class="control-label">Type</label>
<input type="text" name="type" id="type" class="form-control">
</div>
<div class="form-group">
<label for="price" class="control-label">Price</label>
<input type="text" name="price" id="price" class="form-control">
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-success">
</div>
{{ csrf_field() }}
</form>
</div>
</div>
<script>
$(document).ready(function(){
var url = '{{ route('ajax-push') }}';
var token = '{{ csrf_token() }}';
$('#create').on('submit', function(){
$.ajax({
type: 'POST',
url: url,
data: { _token: token },
dataType: 'json',
success: function(data){
console.log(data);
},
error: function(data){
var errors = data.responseJSON;
$('#result').removeClass('alert').removeClass('alert-danger');
$('#result > ul').empty();
$.each(errors, function(i, item){
$('#result').addClass('alert').addClass('alert-danger');
$('#result > ul').append('<li>' + item + '</li>');
});
}
});
return false;
});
});
</script>
Controller
public function postAjaxCreate(Request $request){
$validator = $this->validate($request, [
'name' => 'required|max:255',
'description' => 'required|min:2',
'type' => 'required|max:255',
'price' => 'required|numeric'
]);
if($validator->fails()){
return response()->json($validator->messages(), 200)->with($validator->messages());
}
}
You need to pass the from data to the ajax request
data: $('#create').serialize(),
and most likely the response doesn't have a responseJSON property, and you are sending the data twice from, remove the with function in you php function
Add the errors to the page using something similar to the following js:
$.each(data, function(i, item){
$('#'+i).addClass('alert alert-danger');
('#'+i).after('<p>' + item + '</p>');
});