Share Coding

Tutorials, Problems, Stuffs …

Category Archives: Javascript

Refresh global variable by request

To renew a global variable such as a token, it is possible to do it by “Tests” function.

var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("token", jsonData.access_token);

The code should be in “Tests”.

{
  "access_token": "780fe237-b0c0-45fa-8fde-e856206f0fce",
  "token_type": "bearer",
  "refresh_token": "bac7223d-68a0-4c5a-ae6b-62071dcb187c",
  "expires_in": 6695,
  "scope": "read write"
}

The JSON respond body.

After you click send button, the global variable “token” will update it’s value with “access_token”.

jQuery scroll to top not working

var $container = $('html, body, .divProductList');	

$scrollToTop.on('click',function(){
    
    $container.animate({
        scrollTop : 0
    }, 300);
    return false;
});

The magic is in the $container selector. Put your list, html, body into the target.

AngularJS – Cross Domin Get data by $resource

For reference:

http://docs.angularjs.org/api/ngResource.$resource

Required:

http://code.angularjs.org/1.2.0rc1/angular-resource.js

Module Configuration:

var myApp = angular.module('MyApp', ['ngResource']);
myApp.config(['$routeProvider', ,'$httpProvider', function($routeProvider, $httpProvider) {
    $httpProvider.defaults.useXDomain = true;
    delete $httpProvider.defaults.headers.common['X-Requested-With'];
    ....
  }
]);

function: $resource(url[, paramDefaults][, actions]);

var User = $resource('http://localhost:port/sil/SilUserAuth.svc/Login', {port:':59217'}, { });
User.get({
       name: document.loginForm.email.value,
       password: document.loginForm.password.value
}, function (data) {
       alert(JSON.stringify(data));
});

Result on Firebug View:

GET http://localhost:59217/sil/SilUserAuth.svc/Login?name=abc&password=abc   200s OK 12ms

In ASP.NET MVC 4:

<script type="text/javascript" src="@Url.Content("~/Scripts/angular.js")"></script>
<script type="text/javascript" src="@Url.Content("~/Scripts/angular-resource.js")"></script>

Set httpProtocol on Web.config

    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Content-Type" />
      </customHeaders>
    </httpProtocol>

Problem 1

OPTIONS xxxxxxxxx (405 Method Not Allowed)

Solution
Remove the header from all requests :

"delete $httpProvider.defaults.headers.common['X-Requested-With'];"

Problem 2

Angularjs Error: destination.push is not a function

Solution
Define action type get / query / update / delete and  add isArray: true:

    var Papers = $resource('http://localhost:port/Sil/SilUserPaper.svc/UserPapers/:id', { port: ':59217' }, {
        get: { method: 'GET', params: {}, isArray: true }
    });
    Papers.get({
        id: 2
    }, function (data) {
        $scope.papers = data;
    });

How to improve your jQuery

1. Use unique ‘id’ when selecting (Fastest)

$('#btnTest'); //Correct
$('input#btnDiv'); //Wrong
$('#btnDiv #btnTest'); //Wrong

 
2. Use ‘tag’ before select ‘class’

$('input.setOfButton');

 
3. One select to do all works

// Correct
$('#btnTest')
	.val('Test')
	.css('color', 'red');
	.show();

// Wrong
$('#btnTest').val('Test');
$('#btnTest').css('color', 'red');
$('#btnTest').show();

 
4. Reduce append times

// Correct
var appendHTML = '';
for(var i=0; i<10; i++) {
	appendHTML += '<p>' + i + '</p>';
}
$('#divTest').append(appendHTML);

// Wrong
var $divTest = $('#divTest');
for(var i=0; i<10; i++) {
	$divTest.append('<p>' + i + '</p>');
}

Select excetly parent

Basically, this is the jQuery basic selector to select a html object.

$('#btnSubmit')

 

How to select a parent?

$('#btnSubmit').parent() // my parent
$('#btnSubmit parent') // my top parent

 

But browser will add <tbody> to our <table>, so that we can’t select excetly parent by

$('#btnSubmit').parent().parent().parent().parent().parent()

 

Solution:

$('#btnSubmit').closest('table')

Select the closest table parent, you may use class to instead table