Saturday, 18 April 2015

jQuery AJAX POST

Full example use here

Getting the customer list and populating a dropdown box

$.ajax({
    cache: false,
    url: "/Controller/Action", //URL to the action
    type: "POST",
    data: { random: Math.random() },
    error: function (xhr, ajaxOptions, thrownError) { //xhr, status, errorMsg
        //Display some error message here
    },
    success: function (result) {
        if (result.error) {
            //Display some error message here -- result.message
        } else if (result.customer == "" || result.customer == null) {
            //Display some error message here -- result.message
        } else {
            //result.customer is a json string, we'll need to turn this into an object
            var customerList = JSON && JSON.parse(result.customer) || $.parseJSON(result.customer);
            if (!customerList || customerList.length <= 0) {
                //Display some error message here
            } else {
                //create dropdown object
                var customerDropDownList = document.getElementById("DropDownId");
                //clear current items from customer dropdown
                customerDropDownList.options.length = 0;
                //add new customers
                for (var i = 0; i < customerList.length; i++) {
                    var opt = document.createElement("option");
                    opt.text = customerList[i].CustomerName;
                    opt.value = customerList[i].CustomerAlias;
                    customerDropDownList.options.add(opt);
                }
            }
        }
    }
});