Does have anybody any example with properly coded cascading dorpdowns menus? I tried to search in the internet but I am only confused from different approaches. And yes, I do not want to use echo json_encode($states) in my controller code …
So you’re looking for an Ajax solution where you make a selection in the first field, then the second one gets filled in with valid options based on that, and then the third one with valid options based on the first two, that sort of thing?
Which piece, specifically, are you having problems with? It’s a lot of pieces that have to come together to make this work, only a couple of which are in any way CakePHP-specific. There should be lots of tutorials out there about how to do this in general.
Could you help me to find what I am doing wrong? I found also working solution solution here - CakePHP Sandbox App: AjaxExamples but I do not understand it. It is too complicated for occasional programmer like me.
I am just seeking for CakePHP proper way. Once more thank you for your help.
I wonder if the addition of the application/json type header means that the browser is automatically recognizing that it’s a JSON payload and parsing it for you? Not at a good place right now to check that out, but it should be pretty easy for you. In your jQuery code, instead of trying to parse the result, just console.log(result);, and show us what that looks like in both of your controller scenarios.
I am not really sure if this helps you but usually if you want to fetch JSON data from CakePHP you can follow these steps to leverage the JsonView provided by CakePHP:
Tell CakePHP that you want JSON data back via adding dataType: 'json', to your jQuery $.ajax() config. So like
The important part here are the last 2 lines with $this->set() to set variables into the view (aka make them available to the template) as well as $this->viewBuilder()->setOption(); to tell CakePHP to serialize those variables inside the JSON.
This will result in a JSON being returned which looks like this:
Hi all. Once more thank you very much @Zuluru, @ndm and @KevinPfeifer for your help. I do not why but the option with Serialize Key proposed by @KevinPfeifer and described in CakePHP Cookbook did not work. Response on ajax request was empty (at least according to Network tab Preview, subject_id was sent).
You do not have to use any of those JSON functions, result will already be a JavaScript object!
Your JS error was caused by passing that object to JSON.parse(), where it was implicitly being converted into its string representation, which is [object Object], and of course that’s not a valid JSON string that could be parsed.