Closed nixondesigndev closed 4 years ago
Not quite sure what you mean, as all controller actions support returning JSON for Ajax requests. Refer to the following:
<form class="ajax-form" method="POST">
<input type="hidden" name="action" value="wishlist/items/toggle">
{{ csrfInput() }}
<input type="text" name="elementId" value="{{ entry.id }}">
<input type="submit" value="Toggle in List">
</form>
$('.ajax-form').on('submit', function(e) {
e.preventDefault();
var data = $(this).serialize();
$.ajax({
type: 'post',
url: '',
data: data,
dataType: 'json',
success: function (response) {
console.log(response);
}
});
});
The above works as expected. Can you provide what you're using, template and JS?
@engram-design OK so after a bit of digging I'm now getting JSON back. Turns out that for some reason in Chrome when using the fetch API it displayed the response in the network panel as blank unless you explicitly call response.json(),
simply doing fetch
and looking at the network request doesn't work, the header still gets set ''Accept': 'application/json' so must be a dev tool bug (Firefox works). Sorry about that.
fetch('', options)
.then(response => response.json())
.then(data => console.log(data));
I'm now getting {"success":true}
.
Would it be possible to add another property in there with the action performed, i.e. 'added' or 'removed'?
Added in 1.2.7
@engram-design Just tried the update, I was more thinking along the lines of when you call toggle the JSON comes back with the actual action performed so when calling it you get a response saying if the item was added or removed.
Perhaps that's the wrong way of looking at it and the JSON should return the items/ids in the list?
Right, gotcha. Added in 1.2.8.
Just bare in mind the trick about this is that items
will always return as an object, with the ID of the item and the named action taken. This is because you can toggle multiple items at the same time, or just one. As such, we need to cater for both scenarios.
Description
It would be super useful for AJAX forms if the toggle, add and remove controllers returned JSON. At the moment there's no way of knowing if an error occurred or if the element was added or removed when calling toggle.