guys,
Well I have a simple form with a dropdown to select one 'product types' of a few. When an item is selected, it'll trigger an onChange
event. A given product type can have an expiration date
or not. I want to change the visibility of a field according to it.
I already made a route /product_type/get_exp/{id}
but I'm having a hard time crafting the jQuery request that'll GET the value and hide the field accordingly
Best How To :
You need to make sure to send a JSON response from that route. Otherwise you're making it yourself harder.
As there's not much code to work with, I'll try to explain it in a generic way...
Create the route (you've already done that). A get
route is just fine for this.
$route->get('product_type/get_exp/{id}', '[email protected]');
In the corresponding Controller method, do something like this. Note that I'm typehinting the ProductType model. This will only work however if the model was bound in the router.
public function getFooMethod(ProductType $id)
{
// Check if ID has expiration date field
// Let's store it in $hasExpiration
// e.g. $hasExpiration = false
return Response::json(array('showExpiration'=> (int) $hasExpiration));
}
And then in the onChange
method:
$('#SELECT_ID').on('change', function() {
// Fetch the ID of the selected option.
var optionID = $(this).attr('data-id'); // please change per your layout definition
// Construct the url.
var productTypeExpirationUrl = 'url_to_route_with_trailing_slash/' + optionID;
// Perform an Ajax GET request using the product type ID.
$.ajax({
url: productTypeExpirationUrl,
type: 'GET',
dataType: 'json',
success: function(result) {
// Extract the showExpiration property of result and hide/show the extra field accordingly.
}
});
});
Please don't forget to send along the CSRF token as well (described here), otherwise the request silently fails.
As an additional security measure, I'd hop in some Middleware to only allow Ajax requests on that route.