ERROR FIX: json_encode returns null even if there is a value being passed to it

Comments 7 Standard

Loosing Data With json_encode?

So this took me several days of pulling out my hair so I’m hoping to save you some hair loss. I had a query pulling data from a MySQL database and then I was encoding the data and sending it back as a json_encode to an ajax file. The strangest thing was happening to my query — it would load a set number of records and then it just stopped, my json_encode would always return a null value even if there was data being passed to it.

Here’s The Solution

Apparently json_encode will only work properly if the data being passed to it is encoded as UTF-8. One of the posts I was pulling back had a Microsoft curly apostrophe in it (darn you user-entered data!).  So the quick solution is to use the utf8_encode() function around your data before you pass it to json_encode. Otherwise it’s time to go through all of your data and make sure it’s encoded UTF-8 first!

Advertisements

7 thoughts on “ERROR FIX: json_encode returns null even if there is a value being passed to it

  1. i have a big problem with json actually i’m query some data i json_encode and echo it so i can receive its trough ajax but its empty nothing is coming trough but when i’m running the php file it’s self i can see the json data but im not getting nothing on jquery or ajax side how can i fixe this

  2. First make sure your ajax file is returning results without trying to encode it. If it is then it’s an encoding issue. You need to encode the data before you call json_encode like my post says.

  3. What can I say?! Saved my life big time. Even lost lots of hair while trying to solve this problem. Thanks Big 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s