PHP: Retrieving JSON via jQuery ajax help

Posted by iamjonesy on Stack Overflow See other posts from Stack Overflow or by iamjonesy
Published on 2011-02-14T14:28:04Z Indexed on 2011/02/14 15:25 UTC
Read the original article Hit count: 305

Filed under:
|
|
|

Hey I have a script that is creating and echoing a JSON encoded array of magento products.

I have a script that calls this script using jQuery's ajax function but I'm not getting a proper response.

This is the script that creates the array:

$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addAttributeToSelect('name');
$collection->addAttributeToSelect('price');

$products = array();

foreach ($collection as $product){
  $products[$product->getPrice()] = $product->getName();

}

header('Content-Type: application/x-json; charset=utf-8');
echo(json_encode($products));

Here is my jQuery:

<select id="products">
    <option value="#">Select</option>
</select>

<script type="text/javascript">
    jQuery.noConflict();
    jQuery(document).ready(function(){


    jQuery.ajax({

     type: "GET",
     url: "http://localhost.com/magento/modules/products/get.php",
     dataType: "json",

       success: function(products) 
       {
          jQuery.each(products,function(price,name)
       {

       var opt = jQuery('<option />'); 
          opt.val(name);
          opt.text(price);
          jQuery('#products').append(opt); 
       });
    }


   });


 });
</script>

I'm getting a response from this but I'm not seeing a any JSON. I'm using firebug. I can see there has been a JSON encoded response but the response tab is emtyp and my select boxes have no options.

Can anyone see and problems with my code?

Here is the response I should get:

{"82.9230":"Dummy","177.0098":"Dummy 2","76.0208":"Dummy 3","470.6054":"Dummy 4","357.0083":"Dummy Product 5"}

Thanks,

Billy

© Stack Overflow or respective owner

Related posts about php

Related posts about jQuery