Skip to main content

Posts

Showing posts with the label JavaScript

JavaScript : What is Javascript Hoisting

What is Hoisting in Javascript ?? In Javascript the variable declaration can be done at any place inside the function or inside the script. Where a variable is declared makes no difference because the javascript interpreter always move the variable declarations silently to the top of the scope where the variable is used. For example, everyone will be fine the following javascript code. <script> var num; num = 5; function foo(){ alert(num); } foo(); </script> And, all will be able to guess that the function foo() will alert value 5 . However, the following code will confuse a lot of the developers, since the variable num is used before it is declared. <script> num = 5; function foo(){ alert(num); } foo(); var num; </script> The above code will run absolutely fine and will alert 5 just as in the previous example. So what happened in example 2 ? What happened is Javascript Hoisting  and it happened automatically behind the ...

OOJS : Create an Object in Javascript

Points To Remember You can create objects of a function in javascript. Function can have both private and public methods. Functions can inherit other functions Create an Object in Javascript Let us create a User object in javascript. var User = function() { _self = this; var _name; _self.getName = function() { return _name; } _self.setName = function(name) { _name = name; } _self.toString = function() { return "Person{name::" + _name + "}"; } } Here User is a function name is a private variable and will not be accessible outside the User function. _self is used to save the this  reference, this is done so that it does not mix with the this  of the inner functions. getName, setName and toString are the public functions that can be called from an object of User function. typeof User "function" Now let us create two Objects of the User function. var user1 = new User(); var user2 = new User(); Both user1...

Send JSON object as data in Ajax POST/ GET call

Send JSON object as data in Ajax call. Suppose you have  a JSON object associated with a variable say json  in our case, you can send this json value as data in the ajax call as follows. var json = [{'id':1,'name':'user1'},{'id':2,'name':'user2'},{'id':3,'name':'user3'},{'id':4,'name':'user4'}] function demo(url){ $.ajax({ method : 'POST', url : url, dataType: 'json', data : { objects :JSON.stringify(json)}, success : function(data){ console.log(data); }, error : function(error){ alert('OOps Something went wrong, please contact admin'); } }); } JSON.stringify()  method will parse the json object and convert it to a string format that can be sent as data in the Ajax call. you can also send other data with the json as follows var json = [{'id':1,'name':'us...