How to make a simple AJAX call with JQuery

AJAX Stands for "Asynchronous JavaScript and XML".

Basically we use AJAX to change parts of our web page with loaded data from the server  without reloading the whole page. Google, YouTube, Facebook all use AJAX to display changing data.

What happen in AJAX is we can request HTML,TEXT, XML results from a server using HTTP GET or POST requests and load the response to selected HTML elements in our web page.
JQuery load() method can be easily used to make a AJAX call to server.

HTML code.

<!DOCTYPE html>
<html>
<head>
    <script src="Scripts/jquery-1.11.3.js"> </script>      
</head>
<body>
<div id="div1"> <h2> Let jQuery AJAX Change This Text </h2> </div>
<button>Get External Content</button>         
    <script>   
        $(document).ready(function(){
            $("button").click(function(){
                $("#div1").load("demo_test.txt");
            });
        });                    
    </script>     
</body>
</html>

When you click the button JQuery load() method will load the content of the file demo_test.txt to div element which has ID div1.

NOTE:

  1. If your txt file need to load is not in the same directory as html file you have to give a relative path to the file in to the load method (eg: "Files/demo_test.txt")
  2. If you don't have have a internet connection when you run this example you have  to manually download the JQuery and give the path to JQuery path.

Algorithm : Sort an array according to digit root


In this problem, a given Integer array should be sorted based on their digit roots. Digit root of a positive number is defined as the sum of all its digits.

Ex:-
A=[ 2, 4, 12, 13, 24, 32]
Consider array 'A', Digit root array of array 'A' would be [ 2, 4, 3, 4, 6, 5]
After sorting that array according to digit root of integers result would be like,
 A=[ 2, 12, 4, 13, 32, 24]
Steps to solve

  1. Find digit root of each integer. More details of how to find the digit root of a positive integer can be obtained from my previous post about finding digit root .
  2. After finding the digit roots of numbers next thing has to be done is sort the integers in given array based on their digit roots.

For understand this solution you should have a good understand about Array sort() method in JavaScript and creating objects in JavaScript.

Here is the final solution for sort an integer array based on their digit roots using JavaScript.

function digitRootSort(a) { 
 var digitRoot = function(n) { 
  var root = 0; 
  while (n > 0) { 
   root += n ; 
   n = Math.floor(n / 10); 
  } return root; 
 } var buckets = {}; 

 for (var i = 0; i < a.length; i++) { 
  var root = digitRoot(a[i]); 
  if (!buckets[root]) { 
   buckets[root] = []; 
  } 
  buckets[root].push(a[i]); 
 } 

 var b = []; 
 for (var root in buckets) { 
  var bucket = buckets[root]; 
  bucket.sort(function (a, b) { return a - b; }); 
  for (var i = 0; i < bucket.length; i++) { 
   b.push(bucket[i]); 
  } 
 } 
 return b; 
}


If you have any problem or optimized solution even in another programming language. :)

Algorithm : Sum of integers in a string

This is another tricky programming problem that people think easy. But it is not that easy unless you are a kind of genius.
In string "I spent 2 years and 11 months in Japan" there are two integers, 2 and 11. So some of integers in that string is 13.

In order to calculate the sum correctly,
  1. We should identify Integers
  2. Get the value of Integer precisely. 
Here is the code implemented those functionalities in JavaScipt


function sumUpNumbers(inputString) { 
 var answer = 0, currentNumber = 0; 
 for (var i = 0; i < inputString.length; i++) { 
  if ('0' <= inputString[i] && inputString[i] <= '9') { 
   currentNumber = currentNumber * 10 + inputString.charCodeAt(i) - '0'.charCodeAt(0); 
  } 
  else { 
   answer += currentNumber; 
   currentNumber = 0; 
  } 
 } 
 answer += currentNumber ; 
 return answer; 
} 


Feel free to add any comment and your ideas about this solutiion

How to use Array sort() method in JavaScript


If we want to sort an array using JavaScript easiest way is using sort() method in JavaScript.
By default sort() method get values as strings and sort them in alphabetical and ascending order.
This is how we use this method in JavaScript.

Using sort() method.

var names=['Jack','Eve','Ann','Jane']; 
names.sort(); 

var numbers=[22,56,3,10,6]; 
numbers.sort();

After using sort() method your result arrays will be like,

['Ann','Eve','Jack','Jane']
[10,22,3,56,6]

you will notice that integer array was not sorted correctly. That is because sort() method get values as strings and when comparing 22 is smaller than 3 because 2(first character of 22) is smaller than 3.

Using overloaded method.

To over come this problem there is overloaded method of sort() that take a compare function as a parameter.

var numbers=[22,56,3,10,6];
numbers.sort(function(a,b){return a-b}); 

After using this method your numbers array will be sorted correctly in ascending order as,
[ 3, 6, 10, 22, 56]

As compare function is used to compare integers when comparing 3 and 22,
compare function will be used as function(3,22) and return value 3-22 = -19. 3 will be identified as smaller than 22 because compare function returned a minus value.

If function(a,b){return a-b} is used as compare function integer array will be sorted in descending order.
feel free to comment below if you have any questions or something to add.


Algorithm : Find the Digit root of an integer


Digit root of a positive number is the sum of all of its digits.

Finding this Digit root was needed in many problems which were appear in programming contests.
Here is the simplest algorithm(as I think up to now :-) ) to find the Digit root of any positive integer implemented using JavaScript.
function findDigRoot(n) { 
 var root = 0; while (n > 0) { 
  root += n ; 
  n = Math.floor(n / 10); 
 } 
 return root; 
}

Feel free to comment below the post if you have a better, optimized solution or problems regarding the solution.



Algorithm : Find a sentence is an pangram.

A pangram is a sentence that uses every letter in alphabet at least once. There is a quite popular programming problem to find a given sentence is a pangram or not.
This is an another solution for that problem with JavaScript. Feel free to add a comment if you have any questions or a better, optimized solution.

function isPangram(sentence) {
 var found = [], result = true ; 
 for (var i = 0; i < 26; i++) { 
  found.push(false); 
 } 
 for (var i = 0; i < sentence.length; i++) { 
  var code = sentence.charCodeAt(i); 
  if ('A'.charCodeAt(0) <= code && code <= 'Z'.charCodeAt(0)) { 
   code += 'a'.charCodeAt(0) - 'A'.charCodeAt(0); 
  } 
  if ('a'.charCodeAt(0) <= code && code <= 'z'.charCodeAt(0)) { 
   found[code - 'a'.charCodeAt(0)] = true; 
  } 
 } 
 for (var i = 0; i < 26; i++) { 
  if (!found[i]) { 
   result = false; 
  } 
 } 
 return result; 
}

Algorithm : Maximal possible sum of some consecutive items in an integer array


In array "A" maximum sum of any 2 consecutive numbers is 14(12+2) and maximum sum of any 3 consecutive numbers is 21(8+1+12).
     A=[ 2, 3, 8, 1, 12, 2, 4, 5]

Here is a simple algorithm using JavaScript for find the maximum sum of some consecutive numbers in an integer array. This is just a simple solution for this problem.

Feel free to add a comment if anyone has a optimized solution or anything hard to understand.