[ad_1]
when i am making validation in the form i made it with ajax
but in ajax when i wrote this console.log(response) it works but when i wrote like this
console.log(response.status) it returns undefined i don’t know why although i wrote status at response->json() and also the same when i make console.log(response.errors)
and here is my code
my form blade
<form method="POST" enctype="multipart/form-data" id="productform">
@csrf
@method('POST')
<ul id="showerrors">
</ul>
<div class="form-group">
<label for="">name</label>
<input type="text" name="name" class="form-control">
</div>
<div class="form-group">
{{-- <label for="">image</label>
<input type="file" name="image" class="form-control"> --}}
</div>
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Save changes</button>
</form>
and myy response code in store method
public function store(Request $request)
{
$validation = Validator::make($request->all(),[
'name' => 'required',
]);
if($validation->fails()){
return response()->json([
'errors' => $validation->errors(),
'status' => 400,
]);
}
// dd($request->all());
$product = new Product();
$product->name = $request->name;
$product->save();
return response()->json([
'status' => 200,
'message' => 'added successfully',
]);
}
and my route
Route::resource('products',App\Http\Controllers\ProductController::class);
and my ajax code that returns console.log(response.status) undefined
$(document).ready(function(){
$('#productform').submit(function(e){
e.preventDefault();
var data = {
'name' : $("input[name="name"]").val(),
'_token' : $("input[name="token"]").val(),
}
// console.log(data);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url:"/products",
type : "POST",
data:data,
dataType:'text',
success:function(response){
console.log(response.status);
if(response.status = 400){
$('ul#showerrors').html = "";
$('ul#showerrors').addClass = "alert alert-danger";
$.each(response.errors, function (key,value){
$('ul#showerrors').append('<li>'+value+'</li>');
});
}
},
});
});
});
[ad_2]