cagin cagin - 21 days ago 7
Javascript Question

Ajax post does not work after document ready

I want to make an Ajax call after my document is ready. Here is my code :

<script>

$(window).bind("load", function () {
getCategories();

});
</script>

<script>
function getCategories() {
$.ajax({
type: "POST",
url: '@Url.Action("GetAllCategoryTest", "Category")',
dataType: "html",
contentType: "application/json",
async: false,
success: function (result) {
var categoryList = JSON.parse(result);

$.each(categoryList.result, function (i) {
$("#menuCategory").append('<li>' + categoryList.result[i].CategoryName + '</li>');


});

}
});
}
</script>


My ajax post works without using window.bind but I have to run my ajax post after my document is loaded.

Answer

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
  $(document).ready(function() {
    getCategories();
  });

  function getCategories() {
    $.ajax({
      type: "POST",
      url: '@Url.Action("GetAllCategoryTest", "Category")',
      dataType: "html",
      contentType: "application/json",
      async: false,
      success: function(result) {
        var categoryList = JSON.parse(result);

        $.each(categoryList.result, function(i) {
          $("#menuCategory").append('<li>' + categoryList.result[i].CategoryName + '</li>');


        });

      }
    });
  }
</script>