shane
shane

Reputation: 149

jquery .ajax (or .eval) problem in IE

Hopefully someone can shed some light onto this issue for me.

I have a little APP (http://www.bentinckfencing.co.uk/fence_calculator.php)

I have a php file that sends a JSON encoded string back.

Im using jQuery to retrieve this string with the .ajax() function. After I have the JSON string, I am then using eval() in this manner

$.ajax({
   type: "POST",
   url: "ajax-test.php",
   cache: false,
   data: "choice=34",
   success: function(data){

       var myObject = eval('(' + data + ')');

       //Now I set lots of variables in this manner and use them later in the script

       var productName  = myObject[0]['name'];
       var productPrice = myObject[0]['price'];                                     
       var productID    = myObject[0]['id'];

        }
   });

As always, this works well in all browsers except IE which is throwing the error object doesn't support this property or method

I just can't think where I'm going wrong.. If anyone has time to help, or even to check out my app, I'm be most helpful :)

edit I've found that the Ajax call is successfully retrieving the data in IE. It's string like this [{"name":" 12 inch Rock Face Gravel Board","ID":"106","price":"7.00"},{"name":" 12 inch Double Sided Gravel Board","ID":"108","price":"10.50"},{"name":" 12 inch Smooth Gravel Boards","ID":"109","price":"7.00"}]

So now my issue is down to how I handle the data now that JS has it... Any ideas would be great :)

Upvotes: 0

Views: 2519

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039200

Don't use eval, it's evil. Also make sure your server sends proper content type (application/json):

$.ajax({
    type: 'POST',
    url: 'ajax-test.php',
    cache: false,
    data: { choice: 34 },
    dataType: 'json',
    success: function(items) {
        // TODO: some range checking on this array won't be useless
        // before trying to access its elements

        var productName = items[0].name;
        var productPrice = item[0].price;
        var productID = items[0].ID;

        // TODO: do something useful with those variables
    }
});

Also you probably don't need cache: false with a POST request. Those are probably reflexes that you got from IE and GET requests :-)

Upvotes: 1

user113716
user113716

Reputation: 322562

This line:

   var productID    = myObject[0]['id'];

should be:

   var productID    = myObject[0]['ID'];

Javascript identifiers are case sensitive.

Upvotes: 0

Related Questions