Updated: jQuery to C# – AJAX (with data)

[WebMethod]
public static string testingWebMethod(string name) {

  //Do something with name? 

  string someString = "Woah";

  return someString;
}
var dataToSend = JSON.stringify({
  "name": "foo"
});

$.ajax({
  type: "POST",
  url: "page.aspx/testingWebMethod",
  dataType: "json",
  data: dataToSend,
  contentType: "application/json",
  success: function(response) {
    alert(response.d);
  },
  error: function(err) {
    alert(err.d);
  }
});
Advertisements

Testing Javascript and jQuery array loops

(by axds)

https://jsfiddle.net/s7bn7cfr/

The simple for loop seems to win the speed tests:

let arrLen = test.length; for( let i = 0; i < arrLen; i++ ){  }

Although this method is less DRY as the length of the the array has to be known. JS’s forEach() or jQuery’s $.each() are good alternatives that are dynamic.

The clear worst is the ‘for x in y’ loop. Which has bulky syntax and is slow.

 

 

 

Nice Random Colors in Javascript

I needed to generate random colours for series in a chart, so my initial start was generating a random RGB hex string. However, this resulted in 2 problems:

  1. RGB definitions seem to skew dark, and
  2. No guarantee that similar shades wouldn’t be chosen

To solve 1, instead of using RGB I used HSL. This allows you to fix the Saturation and Light, and just change the Hue (a value between 0-360), meaning the colours can be set to be a bit lighter.

For 2, since the HSL definition automatically takes the modulo of the value passed through, if we are able to find a suitable value we can just increment it by this each time and generate colours that are different enough.

So we have the following code:

var hue = 0;

function getRandomishColor() {
     hue += 222.5;
     return 'hsla(' + hue + ', 75%, 50%, 0.5)';
}

Ordinal Indicator/Suffix for numbers in Javascript

Input | Output

1 => 1st
2 => 2nd
3 => 3rd
4 => 4th
0 => Not Placed
21 => 21st
etc…


function ordinalSuffixGen(inputVal) {
var mod10 = inputVal % 10,
mod100 = inputVal % 100;
if (inputVal <= 0) {
return "Not placed";
}
if (mod10 == 1 && mod100 != 11) {
return inputVal + "st";
}
if (mod10 == 2 && mod100 != 12) {
return inputVal + "nd";
}
if (mod10 == 3 && mod100 != 13) {
return inputVal + "rd";
}
return inputVal + "th";
}

ES2015 (ES6) Template Strings

Example: https://jsfiddle.net/ehdgpvyb/

ES2015 provides a better way to use variables inside strings.


function exampleJS5( name , age ) {
console.log("Hello " + name + ", you are " + age + "!");
}

function exampleJS6( name , age ) {
console.log(`Hello ${name}, you are ${age}!`);
}

exampleJS5('Bob', 20);
//Hello Bob, you are 20!
exampleJS6('Bob', 20);
//Hello Bob, you are 20!