1

I'm have a little trouble with some jQuery I have been trying to put together today.

Basically what I am trying to achieve is to dynamically have prices inserted into a price button on my page by reading from a JSON feed.

The idea is that there is an empty span that will contain the price. I have given all of the price spans the class .getPriceNew. Each span also has an id which is equal to the SKU number for the item like this <span class="getPriceNew" id="123456"></span>.

The mechanic is that for each span that has the class .getPriceNew the JSON will be queried for the information with the SKU id used as part of the query string.

Here is an example of the code i have tried

jQuery

$(".getPriceNew").each(function() {
    var sku = $(this).attr("id");
    var priceNew = $.getJSON('/api/MyApi.svc/GetProductBySku/'+sku , function(data) {
            return(data.Variants[0].Price);
            });
    $(this).html("&euro;"+priceNew);        
})

HTML

<span class="getPriceNew" id="123456"></span>
<span class="getPriceNew" id="789123"></span>
<span class="getPriceNew" id="456789"></span>
<span class="getPriceNew" id="654321"></span> 

JSON Example This is what a single item from the JSON feed would look like - I have filtered it a little /api/MyApi.svc/GetProductBySku/123456

Updated with valid JSON

 {
    "Age": {
        "Description": "Age 18+",
        "Thumbnail": "http://someurl.com/productImages/assets/img//icon18.gif"
    },
    "Barcode": {
        "Barcode": "5026555408684"
    },
    "Description": "HTML",
    "Id": 12214,
    "Packshots": [
        "http://someurl.com/productImages/914383/1min.jpg",
        "http://someurl.com/productImages/914383/2med.jpg",
        "http://someurl.com/productImages/914383/3max.jpg"
    ],
    "Pegis": [],
    "Platform": {
        "Button": "Format",
        "ID": 0
    },
    "Publisher": {
        "Description": null
    },
    "Release": "/Date(1364252400000+0100)/",
    "Screenshots": [],
    "Title": "Product Title",
    "Variants": [
        {
            "Id": 22488,
            "MaxOrderQuantity": 3,
            "Presellable": true,
            "Price": 49.97,
            "Sku": 914383,
            "Type": {
                "Description": "Pre-Order"
            }
        }
    ],
    "Vendor": {
        "Description": "Take Two Interactive Software"
    },
    "VideoHTML": "HTML",
    "status": {
        "Response": "product found",
        "Success": true
    }
}

I would love some help on this as I am really scratching my newbie head at this stage. I have managed to have console.log output the prices to the log but when I try and insert them back into the spans all I get is [object] [Object].

1

2 Answers 2

1

You are doing

$(".getPriceNew").each(function() {
    var sku = $(this).attr("id");
    var priceNew = $.getJSON('/api/MyApi.svc/GetProductBySku/'+sku , function(data) {
            return(data.Variants[0].Price);
            });
    $(this).html("&euro;"+priceNew);        
})

getJSON returns a jqXHR object, which is not what you need. Try this:

$(".getPriceNew").each(function() {
    var sku = $(this).attr("id");
    // Save a refference to this span.
    var thisSpan = $(this);
    $.getJSON('/api/MyApi.svc/GetProductBySku/'+sku , function(data) {
            // Request complete, NOW we can use the data we got!
            thisSpan.html("&euro;"+data.Variants[0].Price); 
    });

})

The callback is where you want to use the data you get from your AJAX calls. All AJAX methods ($.ajax, $.get, $.post, $.getJSON, etc) will return a jqXHR object.

Sign up to request clarification or add additional context in comments.

4 Comments

Yes, jQuery.getJSON returns a jqXHR (which -- side note -- is a Deferred implementation). So +1: the updates need to happen in the callback.
Okay, thanks for the tip. Seems I am having a little trouble now with my $(this).html("&euro;"+data.Variants[0].Price); It does not seem to be setting the HTML for each of the .getPriceNew spans. Is it possible that it `this' is no longer that jquery object?
Indeed I just checked and now $(this) is the JSON and no longer the span selector. Any tips on how to structure this so that I can still insert my price?
@Jeff this is what I came up with - seems to work so far $(".getPriceNew").each(function() { var sku = $(this).attr("id"); $.getJSON('/api/AthenaService.svc/GetProductBySku/'+sku , function(data) { // Request complete, NOW we can use the data we got! $(".getPriceNew:first").html("&euro;"+data.Variants[0].Price).attr("class", ""); }); });
0

I think your javascript code is correct but your Json output has two errors: 1: "Description":"Some HTML Description here, <- you forgot the closing quote 2: "ID":0}, <- delete the closing brace

So your Json will result like this:

{
"Age": {
    "Description": "Age 18+",
    "Thumbnail": "http://url.com/image.gif"
},
"Barcode": {
    "Barcode": "4876416541647"
},
"Description": "Some HTML Description here",
"Id": 12214,
"Packshots": [
    "http: //url.com/productImages/914383/1min.jpg",
    "http: //http: //url.com/2med.jpg",
    "http: //http: //url.com/3max.jpg"
],
"ID": 0,
"Publisher": {
    "Description": null
},
"Release": "/Date(1364252400000+0100)/",
"Screenshots": [],
"Title": "Titleoftheproduct",
"Variants": [
    {
        "Id": 22488,
        "MaxOrderQuantity": 3,
        "Presellable": true,
        "Price": 49.97,
        "Sku": 914383,
        "Type": {
            "Description": "Pre-Order"
        }
    }
],
"Vendor": {
    "Description": "Vendorname"
},
"VideoHTML": "&lt;iframewidth=&quot;725&quot;height=&quot;408&quot;src=&quot;http: //www.youtube.com/embed/videoseries?list=PLofwA47XDv2_KnfUY52_8mlWg0iUEv8ci&quot;frameborder=&quot;0&quot;allowfullscreen&gt;&lt;/iframe&gt;",
"status": {
    "Response": "productfound",
    "Success": true
}  }

now your code

data.Variants[0].Price

will return 49.97 to validate Json you can paste it into http://jsonlint.com/ i think is very useful

Hope this helps

2 Comments

Thanks for the suggestion. I'm pretty sure I just butchered the JSON when I pasted it in here. I just ran the live JSON through JSONlint and it validated
I have updated the JSON example to have valid code. Thanks for pointing out the error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.