JSON output returns page source code

I have written a plugin/extension for WordPress’ plugin ACF, which does what it needs to do when installed on a default WP install. I wrote this plugin because I needed the function on my own website. It has worked there without any problems until recently, when I noticed it throws a JSON error (when logged in as a non-admin).

The JSON error is “Uncaught SyntaxError: Unexpected token < in JSON at position 1"
This is the error:

Uncaught SyntaxError: Unexpected token < in JSON at position 1
at JSON.parse (<anonymous>)
at city-selector.js?ver=0.4:15
at Object.success (city-selector.js?ver=0.4:64)
at j (jquery.js:3099)
at Object.fireWith [as resolveWith] (jquery.js:3211)
at x (jquery.js:8264)
at XMLHttpRequest.<anonymous> (jquery.js:8605)

When I debug the output (when being logged in as an admin) it shows me exactly what I expected.
Expected output (when selecting Netherlands):

[{“country_code”:””,”state_code”:””,”state_name”:”Select a province/state”},{“country_code”:”NL”,”state_code”:”DR”,”state_name”:”Drenthe”},{“country_code”:”NL”,”state_code”:”FL”,”state_name”:”Flevoland”},{“country_code”:”NL”,”state_code”:”FR”,”state_name”:”Friesland”},{“country_code”:”NL”,”state_code”:”GE”,”state_name”:”Gelderland”},{“country_code”:”NL”,”state_code”:”GR”,”state_name”:”Groningen”},{“country_code”:”NL”,”state_code”:”LI”,”state_name”:”Limburg”},{“country_code”:”NL”,”state_code”:”NB”,”state_name”:”Noord-Brabant”},{“country_code”:”NL”,”state_code”:”NH”,”state_name”:”Noord-Holland”},{“country_code”:”NL”,”state_code”:”OV”,”state_name”:”Overijssel”},{“country_code”:”NL”,”state_code”:”UT”,”state_name”:”Utrecht”},{“country_code”:”NL”,”state_code”:”ZE”,”state_name”:”Zeeland”},{“country_code”:”NL”,”state_code”:”ZH”,”state_name”:”Zuid-Holland”}]

When I debug the output (when being logged in as a non-admin) it shows me the page’s source code instead of the JSON and thus it returns as an error because < is not allowed in JSON. That makes sense to me.

What I don’t get is why it doesn’t return what it needs to. I thought it might have something to do with not being able to access the ajaxurl or so or not having the proper user rights, but when I test it in a ‘vanilla’ WP install it all works.

calls get_states function (which throws the JSON error)

get_states function

get_states_call function

I have copied the get_states_call function to be called on each page load to debug the output of json_encode( $items ). Then it does give me the output I expect (on each user role), so how can it go into error between the echo and call in the function ?

You can see it yourself if you go to http://sd8.dutch-downhill.com

login = Tom
pass = 654321

Go to “Add a profile” and select a country on the form.

I’ve added a console.log(response); on line 15 in the code that calls get_states.

Read more here:: JSON output returns page source code

Leave a Reply

Your email address will not be published. Required fields are marked *