Wishing to load the image and text for the selected option in a drop-down list using Ajax

advertisements

I can't find a decent example of this anywhere.

Basically have a dropdown list, each option value is the productID and text is the Product name.

I want to post all the selected option values to an action method that will return the respective images on document ready. Image data will the be passed to a function which will update the DOM and then execute the same function everytime a different option from dropdown list is selected to retrieve and change the selected options/product image only.

The action method will return the image for this option/value to the client in an AJAX response, I also want to return the product description too.

Should the response data-type be JSON or do I have to return it in some other way i.e HTTP response with image MIME type?

Something like the below collects all the selected values in an array:

$(document).ready(function () {
    var arr = new Array();
    $('select option').each(function () {
        arr.push($(this).val());
    });

    // This below will post it off:
    $.ajax({
        type: "POST",
        url: "/System/GetProductImages",
        data: { arr: arr },
        traditional: true,
        success: function (data) {
            mydata = data;
            OnSuccess(data) // <--- The function that will load/update the images
        },
        dataType: "json" //<--- ?
    });
});

I am not sure how to form the AJAX request correctly so I can request both an image and some text, or is it best to make separate calls when requiring different data types? Maybe I can pack them all in into an array of some sort? Also not to sure how the function that will update the DOM with the retrieved images will look.


I would say that your response should be JSON having and Image ID(a value to identify your image from DB) and Product description. Then using that construct dynamic image elements in HTMl and set their src tag to a URL by passing that image ID as parameter and on server side there should be a handler for your request(like servlet, which reads the Image ID and fetches image stream and returns as response). So, browser make a request for each image and get it rendered on browser. hope it will help you!