0👍
✅
I finally fixed it, it seemed to have problems with the way I was inserting my script code in my children view. I had to read about stacks (check https://laravel.com/docs/7.x/blade#stacks) which seems to be the right way to insert scripts in your parent view.
The parent view is the same as posted in the question, but I uncommented the script in the head, and put this befores closing body label:
@stack('script')
And my children view now looks like this (focus on the push and endpush part which is the script that had problems):
@extends('layouts.app')
@section('grid')
<!-- Bootstrap css -->
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<!-- Style css -->
<link rel="stylesheet" type="text/css" href="css/style.css">
@endsection
@push('script')
<script>
x = document.getElementById("alertabien");
y = document.getElementById("alertamal");
x.style.display = "none";
y.style.display = "none";
@foreach($productos as $product)
document.getElementById('postForm{{$product->id}}').addEventListener('submit', prueba{{$product->id}});
function prueba{{$product->id}}(e){
e.preventDefault();
var id = document.getElementById({{$product->id}}).value;
var params = "idproducto="+id+"&idcarrito="+{{$carrito_id[0]->id}};
xhr = new XMLHttpRequest();
xhr.open('POST', '/carrito', true);
xhr.setRequestHeader('Content-type', "application/x-www-form-urlencoded");
xhr.setRequestHeader('X-CSRF-TOKEN', "{{ csrf_token() }}");
xhr.onload = function(){
if(this.responseText){
document.getElementById("alertamal").innerHTML = "Lo sentimos, ha habido un error en la base de datos, por favor recargue la página.";
y.style.display = "block";
$("#alertamal").fadeIn("slow");
$("#alertamal").fadeOut(8000);
} else {
document.getElementById("alertabien").innerHTML = "¡FELICIDADES! Ha añadido correctamente su producto al carrito de compras";
x.style.display = "block";
$("#alertabien").fadeIn("slow");
$("#alertabien").fadeOut(8000);
}
}
xhr.send(params);
}
@endforeach
</script>
@endpush
@section('content')
<div class="alert alert-success" id="alertabien">
</div>
<div class="alert alert-danger" id="alertamal">
</div>
<div class="container">
<h1 class="text-center">NUESTROS PRODUCTOS</h1>
<hr>
<div class="row">
@foreach ($productos as $producto)
<div class="col-md-4 product-grid">
<div class="image">
<a href="#">
<img src="storage/app/images/apple-watch.jpg" class="w-100">
<div class="overlay">
<div class="detail">View Details</div>
</div>
</a>
</div>
<form id="postForm{{$producto->id}}" method="POST" class="postForm">
@csrf
<input type="hidden" id="{{$producto->id}}" name="producto_id" class="producto_id" value="{{$producto->id}}">
<h5 class="text-center">{{$producto->nombre}}</h5>
<h5 class="text-center">Price: {{$producto->precio}}</h5>
<input id="guarda" name="guarda"type="submit" value="AÑADIR AL CARRITO" class="btn buy btn-enviar">
</form>
</div>
<!-- /Product -->
@endforeach
</div>
</div>
@endsection
Source:stackexchange.com