Showing posts with label ajax. Show all posts
Showing posts with label ajax. Show all posts

Monday, July 4, 2011

Fill up Select Box dynamically using Jquery and Ajax

To load the select box with dynamic option thorugh ajax,

you can use following function

function loadComponent(parentId){
        $.ajax({
            type: 'GET',
            url: '## YOUR URL##',
            data: 'id='+parentId,
            beforeSend: function(){
                options = '<option value="">Loading ..</option>';
                $("#DYNAMIC SELECTBOX ID##").html(options);
            },
            success: function( data ) {
                //alert(data);
                var arrObj = jQuery.parseJSON(data); // php response array as json_encode().
                options = '<option value="">select Component</option>';
                $.each(arrObj, function(index, obj) {
                    options += '<option value="' + obj.Id + '">' + obj.PrimaryName + '</option>';
                      // work with value
                });
                $("##DYNAMIC SELECTBOX ID##").html(options);
            }
        });
   }  

iterate array variable in jquery - foreach through jquery

I can across a issue, where i needed to access json response by ajax request.
json response was in array and needed to iterate through each of the records to display it in HTML.

for json response through php I did following
return json_encode($phpArray);

than in the ajax request on html template,
$.ajax({
            type: 'GET',
            url: ##YOURURL##,
            data: '##VARIABLE NAME##='+##VALUE##,
            success: function( jsondata ) {
              //  alert(jsondata);
                var arrObj = jQuery.parseJSON(
jsondata );
                $.each(arrObj, function(index, obj) {
         alert(obj.Id); // here id is any key index in array
         // work with value
       });

            }
        });


In my case, I needed to get the data and insert into an select options.

To create dynamic option for select box, please visit here