Periodically send ajax request to server from JavaScript

<script>
    function executeQuery() {
        $.ajax({
            url: 'http://localhost:54802/Calls/CheckNewVoices/',
            type: 'POST',
            data: "{'lastcheckdatetime':'" + lastCheckDateTime + "'}",
            dataType: 'json',
            contentType:'application/json; charset=utf-8',
            success: function (response) {
                lastCheckDateTime = response.lastcheckdatetime;
                console.log(lastCheckDateTime);
                var files = response.files;
                files.forEach(function (file, index) {
                    //Do something
                });
                setTimeout(executeQuery, 30000); //Call after 30 seconds.
            }
        });
    }

    $(function () {
        setTimeout(executeQuery, 30000); //Call after 30 seconds.
    });
</script>

Advertisements

Standard JQuery-Ajax Code Template (v.2)

$.ajax({
    type: 'POST',
    url: '../../../../AreaName(If any)/ControllerName/MethodName/',
    //If datatype is of FormCollection, following 3 lines are not needed-
    //====================================================
    //contentType: 'application/json; charset=utf-8',
    //data: "{'agentdata':'"+ agentdata +"'}",
    //OR, data:JSON.stringify({ key1: value1, key2: value2}),
    //dataType: 'json',
    //====================================================
    //If datatype is of FormCollection, following 3 lines are needed-
    //====================================================
    //processData: false,  // tell jQuery not to process the data
    //contentType: false,   // tell jQuery not to set contentType    
    //data: Data,
    //====================================================
    beforeSend: function () {
        $('SubmitButton').attr('disabled', 'disabled');
        $('SubmitButton').html('Working…');
    },
    success: function (result) {
        if (result == 'Success') {
            SuccessfullSaveNotification();
            ResetMainForm(MainForm);
        }
        else {
            ShowRegularError(result);
        }
    },
    error: function (request, status, error) {
        ShowRegularError('Failed to save. Error Details – Request: ' + request + ', Status: ' + status + ', Error: ' + error);
    },
    complete: function () {
        $('SubmitButton').removeAttr('disabled');
        $('SubmitButton').html('Save changes');
    }
});

Create JavaScript Array in ASP.NET MVC Razor

Let’s you need to populate this variable in javascript-

Divisions= ["Dhaka", "Khulna", "Rajshahi"];

Way 1: Done in javascript tag.

<script>
  //first declare an empty array
  var Divisions = []; 
  
  //Razor Loop
  @foreach (var row in ViewBag.DivisionTable.Rows)
  {
     <text>
       Divisions.push('@row["DisionName"].ToString()');
     </text>
  }
</script>

Way 2: Done in C#

string[] Divisions = new string[qty];
//int[] data = new int[qty];

for (int i = 0; i < DivisionQty; i++)
{
   Divisions[i]= Table.Rows[i]["DivName"].ToString();
}

ViewBag.Divisions=Divisions;

//Now in javascript-
var Divisions = @Html.Raw(Json.Encode(ViewBag.Divisions));

Create GUID / UUID in JavaScript

    function generateUUID() {
        var d = new Date().getTime();
        if (window.performance && typeof window.performance.now === "function") {
            d += performance.now();; //use high-precision timer if available
        }
        var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
            var r = (d + Math.random() * 16) % 16 | 0;
            d = Math.floor(d / 16);
            return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
        });
        return uuid;
    };

 var guid = generateUUID();

Taken from a question from stackoverflow.com-
http://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript

Auto complete search textbox like google in a simple & easy way.

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>AutoComplete Box with jQuery</title>
    <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
    
</head>
<body>
    <div class="demo">
        <div class="ui-widget">
            <label for="tbAuto">Enter UserName: </label>
            <input type="text" id="txtSearch" class="autosuggest" style="width:300px;" />
        </div>
        </div>
</body>
</html>

Place the script in head tag

<script type="text/javascript">
        $(document).ready(function () {
            SearchText();
        });
        function SearchText() {
            $(".autosuggest").autocomplete({
                source: function (request, response) {
                    $.ajax({
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        url: "/Home/GetAutoCompleteData",
                        data: "{'username':'" + document.getElementById('txtSearch').value + "'}",
                        dataType: "json",
                        success: function (data) {
                            response(data.d);
                        },
                        error: function (result) {
                            alert("Error");
                        }
                    });
                }
            });
        }
    </script>
    public class HomeController : Controller
    {
        //
        // GET: /Home/
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult GetAutoCompleteData(string username)
        {

            List<string> result = new List<string>();

            result.Add("Hello");
            result.Add("World");
            return Json(new { d = result }, JsonRequestBehavior.AllowGet);
        }
    }

Working with HTML data- attribute

Sample HTML –

 
<td class="areaCell" data-expandstatus="false">Some text</td>

JQuery part –

 
//getter
var expandstatus = currentRow.attr('data-expandstatus');
//setter
currentRow.attr("data-expandstatus", "true"); 

//Or
//getter
var expandstatus = $(this).data('expandstatus');
//setter
//Functionable setter not found.

JavaScript form validation

<form name="myform" onsubmit="return validateForm()">
   <!-- No space or no other tag can exist between input and img tags. -->
   <input type="text" name="FullName"/><img style="position:absolute; display:none;"   
       src="~/Assets/MyImages/FormValidationError.png" />
</form>
<script>
    function validateForm() {

        var form = document.forms["myform"];
        var fullNameTextBox = form["FullName"];            
        var fullName =fullNameTextBox.value;      
        if (fullName == null || fullName == "") {
            alert("Name must be filled out.");
            
            var errorImageElement= fullNameTextBox.nextSibling; // no space/tag allowed between input and img
            //OR, var errorImageElement= fullNameTextBox.nextElementSibling; //space(s) allowed between input                  
                                                                             and img
   
            errorImageElement.style.display = 'inline';
            //OR, errorImageElement.setAttribute('class', 'visible');
            return false;
        }

        return true;
    }

    //Code to validate file input.
    //if (document.getElementById("UploadFile").files.length == 0) {
    //    console.log("no files selected");
    //}
</script>

JavaScript form validation

<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
    var x = document.forms["myForm"]["fname"].value;
    if (x == null || x == "") {
        alert("Name must be filled out");
        return false;
    }
}
</script>
</head>
<body>

<form onsubmit="return validateForm()">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>

</body>
</html>

HTML Checkbox Tips and Tricks

//Checkbox checked change event handler
$('#CheckBox').click(function () 
{
    var thisCheck = $(this);

    if (thisCheck.is(':checked')) 
    {
       $('#span2').hide();
    }
    else
    {
       $('#span2').show();
    }
});

//Get checkbox value (checked/unchecked)
var checkBoxValue = $('#CheckBox').is(':checked');