Populate HTML Select with JSON using JQuery

P1ST0LPETE
P1ST0LPETE used Ask the Experts™
on
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

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
leakim971Multitechnician
Top Expert 2014

Commented:
Try : http://api.jquery.com/jQuery.parseJSON/

So line 19 :


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

Open in new window

leakim971Multitechnician
Top Expert 2014

Commented:
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

Success in ‘20 With a Profitable Pricing Strategy

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden using our free interactive tool and use it to determine the right price for your IT services. Start calculating Now!

leakim971Multitechnician
Top Expert 2014

Commented:
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

Author

Commented:
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.
leakim971Multitechnician
Top Expert 2014

Commented:
404 error : page not found

Check the filepath
Try to open the file directly in the browser

Author

Commented:
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)
leakim971Multitechnician
Top Expert 2014

Commented:
Ajax run with http and https
leakim971Multitechnician
Top Expert 2014

Commented:
...and not C:/... or file:///

to test with the json file you need to find its path, it would be a good test

Author

Commented:
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.
Figured out the problem.  I actually had my originally posted code created and working with 1.5.1.  Then the next day I was baffled to see that it was broken, and I couldn't figure out what on earth had happened.  Come to find out a co-worker of mine had added jquery.validate.min.js to the page, which causes the error to happen when using jquery 1.5.1.  So looks like a need to update to the latest version of jquery validate to fix the problem.

Author

Commented:
Solved the problem on my own.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial