Reputation: 375
I have confused in her, my plan is I wanna get my error validation message from my response()->json()
in controller and show it in my blade.php
but I can't made them call into my blade, but when I check my result link in my console, my message validation is showing it, who's anyone know my problem, I put my code in bellow :
my controller :
public function testApi(Request $api)
{
$validator = Validator:make($api->all(), [
'name_product' => 'required'
]);
if () {
return response()->json([
'error' => $validator->messages()
], 401);
} else {
// my condition if validator is not fail
}
}
my blade :
@if ($errors->any())
<h4>{{ $error->first() }}</h4>
@endif
@csrf
<div>
<label>Name Product</label>
<input type="text" class="form-control" name="name_product" placeholder="Name">
</div>
<div class="form-group">
<input type="submit" id="productButton" class="btn btn-primary btn-block" value="Add">
</div>
my js :
document.querySelector('#productButton').addEventListener('click', addProduct);
let urlProduct = '/product/add';
let token = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
function addProduct() {
let nameProduct = document.querySelector('input[name="name_product"]').value;
fetch(urlProduct, {
headers: {
"Content-Type": "application/json",
"Accept": "application/json, text-plain, */*",
"X-Requested-With": "XMLHttpRequest",
"X-CSRF-TOKEN": token
},
method: 'post',
credentials: "same-origin",
body: JSON.stringfy({
name_product = nameProduct
})
}).then((data) => {
console.log(data);
}).catch(function (error) {
console.log(error);
})
}
Thank You
Upvotes: 0
Views: 2084
Reputation: 4684
You are making ajax
call, and the page is not refreshed, when you submit the post
request so this
@if ($errors->any())
<h4>{{ $error->first() }}</h4>
@endif
will not be re-rendered again. So all the blade error
will not work for you if you send ajax
request.
You can just do this:
<h4 id="error"></h4>
.then((data) => {
const h4 = document.getElementById("error");
h4.innerHTML = data.error;
})
Upvotes: 1