Link to home
Start Free TrialLog in
Avatar of P1ST0LPETE
P1ST0LPETEFlag for United States of America

asked on

Populate HTML Select with JSON using JQuery

Experts,

I'm using ASP.NET MVC 3 (Razor), and JQuery.  I'm trying to dynamically populate a drop down list (html select) using jquery ajax that fetches json from the server.  However, the error function in the jquery ajax is displaying the following message:

Status: 200
Text: parsererror
Error: jQuery15105500066302597657_1305650239563 was not called

I know my web method on the server is being hit and returning data, I'm just not sure if it's in the proper format.  Using Firebug I can see that the data coming back from the server looks like this:

[
    {"value":353,"text":"15: Building Construction General Contractors And Operative Builders"},
    {"value":354,"text":"16: Heavy Construction Other Than Building Construction Contractors"},
    {"value":355,"text":"17: Construction Special Trade Contractors"}
]

Below is my code.  Can you tell me where I'm going wrong?  Thanks.

MVC Method:
 
public ActionResult GetSubClassifications(long parentID)
{
    AssetManager assetManager = new AssetManager();
    var list = assetManager.GetCodeValues(Domain.Enum.CodeValueType.ClientIndustrySubClassification, parentID);

    ArrayList array = new ArrayList();

    foreach (CodeValue item in list)
    {
        array.Add(new { value = item.CodeValueID, text = item.Description });
    }

    return Json(array);
}

Open in new window



JQuery AJAX Call:
 
$('select[name="Client.IndustryClassificationCode"]').change(function ()
{
    $.ajax
    ({
        type: 'POST',
        url: '@Url.Action("GetSubClassifications", "Client")' + '?parentID=' + this.value,
        contentType: 'application/json, charset=utf-8',
        dataType: 'json',
        success: function (responseData)
        {
            //alert(responseData);
            var select = $('select[name="Client.IndustrySubClassificationCode"]');
            var options = select.attr('options');

            //clear all current options from subclass select:
            $('option', select).remove();

            //populate subclass select with new options:
            $.each(responseData, function (index, item)
            {
                options[options.length] = new Option(item.text, item.value);
            });
        },
        error: function (xhr, textStatus, errorThrown)
        {
            alert('Status: ' + xhr.status + '\nText: ' + textStatus + '\nError: ' + errorThrown);
        }
    });
});

Open in new window

Avatar of Vipul Patel
Vipul Patel
Flag of India image

Avatar of leakim971
Try : http://api.jquery.com/jQuery.parseJSON/

So line 19 :


$.each($.parseJSON(responseData), function (index, item)

Open in new window

A good test would be to modify the url to a flat file GetSubClassifications.json :
[{"value":353,"text":"15: Building Construction General Contractors And Operative Builders"},{"value":354,"text":"16: Heavy Construction Other Than Building Construction Contractors"},{"value":355,"text":"17: Construction Special Trade Contractors"}]

Open in new window


So line 6 (the last line in the following) :
$.ajax
    ({
        type: 'POST',
        url: "GetSubClassifications.json",

Open in new window

With this simple page it work fine :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script language="javascript" src="http://code.jquery.com/jquery-1.5.1.min.js"></script>
<script language="javascript">
	$(document).ready(function() {
		$("select").change(function() {
			$.ajax({
				type: 'POST',
				//url: '@Url.Action("GetSubClassifications", "Client")' + '?parentID=' + this.value,
				url: "GetSubClassifications.json",
				contentType: 'application/json, charset=utf-8',
				dataType: 'json',
				success: function(responseData) {
					//alert(responseData);
					var select = $('select[name="Client.IndustrySubClassificationCode"]');
					var options = select.attr('options');
	
					//clear all current options from subclass select:
					$('option', select).remove();
					//populate subclass select with new options:
					$.each(responseData, function (index, item) {
					options[options.length] = new Option(item.text, item.value);
					});
				},
				error: function (xhr, textStatus, errorThrown) {
					alert('Status: ' + xhr.status + '\nText: ' + textStatus + '\nError: ' + errorThrown);
				}
			});
		});
	});
</script>
</head>
<body>
<select name="Client.IndustrySubClassificationCode">
	<option>Choose one</option>
	<option>here</option>
</select>
</body>
</html>

Open in new window

Avatar of P1ST0LPETE

ASKER

Leakim971,

I tried your suggestion.  Created a new file named "GetSubClassifications.json" and put the json data inside of it, all on one line with no spaces or carriage returns.  Then I copied and pasted all of your markup above, and the ajax error function is firing a 404 error.
404 error : page not found

Check the filepath
Try to open the file directly in the browser
Yeah, that's what I was trying before I posted my last message.  Know 404 is page not found I tried to amend the ajax call to look like this:

$.ajax({
    type: 'POST',
    //url: '@Url.Action("GetSubClassifications", "Client")' + '?parentID=' + this.value,
    url: "C:/Users/username/Desktop/JQuery%20Test/GetSubClassifications.json",
    contentType: 'application/json, charset=utf-8',


as "C:/Users/username/Desktop/JQuery%20Test/GetSubClassifications.json" is how I can access the file directly in the browser.  However, when I try that, I still get the ajax error function firing off displaying the following message:

Status: 0
Text: error
Error: (blank)
Ajax run with http and https
...and not C:/... or file:///

to test with the json file you need to find its path, it would be a good test
Gave up messing with the .json file.  I was currently using version jquery version 1.5.1 on the server, and I switched the version to 1.4.4, and now every thing works.  So I'm not sure how you were getting your above code to work using 1.5.1 and I can't.  I've checked and double checked, and even pulled over the guys sitting next to me to have a look, and everything works with version 1.4.4 and then breaks with 1.5.1

That being said, I would like for this to work with 1.5.1, I just need to know what I need to change.
ASKER CERTIFIED SOLUTION
Avatar of P1ST0LPETE
P1ST0LPETE
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Solved the problem on my own.