I have a function in java script, that I used it to take the JSON from my asp.net mvc controller, to display the item in my view :
<script type="text/javascript" language="javascript">
var k = 0;
var record_count = 0;
var col_count = 3;
var row_count = record_count / col_count;
var str = "<table>";
function itemTemplate() {
var url = '<%: Url.Content("~/") %>' + "ProductListing/AllProductListing/0";
$.getJSON(url, function (product) {
$.each(product.ja, function (index, value) {
//append rows and column to my table by concat the string of 'str'
});
});
str += '</table>';
alert(str);
return (str);
}
$(document).ready(function () {
alert(itemTemplate());
});
</script>
Problem : when I alert the function in $(document).ready function, first it is alert <table></table> and then continue to alert the full string that I concatenate it in my $.getJSON function. So the function is return before taking JSON.
Anyone have any idea about it?
Thanks.
try setting
asyncto false, then make your$.getJSONcallCode:
Reference: http://api.jquery.com/jQuery.ajax/
Note: As of jQuery 1.8, the use of async: false is deprecated.
Alternate Solution