Archives for August 2010...

(1 results found)

Fix for jQuery Ajax and json_encode problem

Wed Aug 4 02:12:58 2010

I came across something that really interested and surprised me today. There I was coding happily for one of my latest projects in which I needed to return values from a .php file via Ajax / $.get using jQuery. The aim was to build an array of filtered results from the SQL database and then pass them on to jQuery which would update the HTML on the page and display the results in real time.

I used json_encode( array ) on the PHP side and jQuery.parseJSON(data) on the jQuery side to get the array into something usable for jQuery. The problem was that the array that was jSON encoded was, as I mentioned, filtered on the PHP side. Below is the sort of thing I was doing.

$checkAgainst=array("1","2","3","4","5");
$whatsMissing = array("1","3","4","5");
$finalArray=array_diff($checkAgainst,$whatsMissing);	
echo json_encode($finalArray);

Here's what's happening. I've set up an array $checkAgainst which contains values that I want to check to see if they exist in another array I've set up called $whatsMissing. In this simple example, you can probably see that the number that is missing is '2'. So when we run the array_diff() and save the results to $finalArray we should be left with the value '2'. The last thing to do is output this array as jSon using json_encode(). Done! Great ...or so I thought.

The code below is jQuery code and is similar to what I used to parse the json encoded data.

$.get('getJson.php',
   function(data){
      var obj = jQuery.parseJSON(data);	
      alert(obj)
   }
);

This bit of code simply makes contact with the PHP file containing the PHP code above and the returned data is then parsed using jQuery.parseJSON(); and the resulting data is saved to a variable called 'obj'. Simple, right? Wrong! The only thing that was returned seemed to be an empty array. Of course it isn't empty. We know it's not. So what went wrong?

Well, if we tried to return any old array from the PHP code, it would work fine. I noticed the problem was that the jSON returned was a mess. The nodes were out of order and sometimes missing. The culprit, you guess it, array_diff()!

Solving the problem is really easy. I added sort($finalArray); to the PHP file before outputting the data which sorted the data correctly and jQuery was successfully able to parse it properly. What an nuisance!

Most recent posts

  1. Flashcards Maker - the app the helps you learn in a flash
  2. Convert Font Suitcase to TTF in 3 Easy Steps
  3. Rain or Shine - Weather Forecast Available Now!
  4. Getting around Apple's silly rules for iOS 10
  5. Localising App Names for iOS and Android

Search site:

Apps by Ubacoda.com

Click the app icons to see more info


Archives

Categories