I have a Laravel app where my blade view makes a JavaScript fetch post to a controller method. I don't understand why my fetch would catch an error on some successful post. My fetch is synchronous.
I had previously used Ajax and got the same results.
Here are the codes. On my blade view, this is my JavaScript code
<script type="text/javascript">
async function fetchPostCards(url, data_post){
return await fetch(url, {
method: 'POST', // or 'PUT'
body: JSON.stringify(data_post), // data can be `string` or {object}!
headers:{
'Content-Type': 'application/json'
}
})
.then(response => response.json());
}
function processCards(){
//this is called via button click
let arrCard = [
{card_number: "ABC001", email: "johndoe@somewhere.com"},
{card_number: "ABC002", email: "janedoe@somewhere.com"},
{card_number: "ABC003", email: "jimdoe@somewhere.com"},
{card_number: "ABC004", email: "jackdoe@somewhere.com"},
{card_number: "ABC005", email: "janetdoe@somewhere.com"},
];
let csrf_token = $( "input[name*='_token']" ).val();
arrCard.forEach(function(indCard){
let post_data = {};
post_data.card_number = indCard.card_number;
post_data.email = indCard.email;
data_post['_token'] = csrf_token;
var fetchPost = fetchPostCards('/processcards', data_post)
.then(data => {
console.log(JSON.stringify(data));
})
.catch(error => {
console.log("error " + error);
});
});
}
</script>
Here is my code on the controller (PHP):
use Log;
class CardController extends Controller
{
public function processcard(Request $request){
$card_number = $request->card_number;
$email = $request->email;
$result = "";
if($card_number == "ABC004") $nonVar += 4; #simulate an error
#do processing here in the cards
#some will have $result = "SUCCESS"
#some will have $result = "CARD NOT VALID", etc.
log::info("card number: ".$card_number);
log::info("activate_status: ".$activate_status);
log::info("******");
return response()->json(['card_number' => $card_number, 'result' => $result]);
}
}
On request for "ABC004", the fetch catches the error, which I expected. On result = "SUCCESS", the fetch catches the error. But when I checked the Laravel logs, I see the "SUCCESS" results with no error.
How do I fix this?
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire