lang="en-US"> ERROR FIX: json_encode returns null even if there is a value being passed to it –  Design1online.com, LLC

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

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!

3 Responses

  1. jonathan says:

    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

    • Jade says:

      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.

  2. jonathan says:

    sorry for my english im a french. 🙂 my english is very poor

Leave a Reply to Jade Cancel reply