jQuery Review

Posted on Thu 05 March 2015 in Programming

ajax usage

Get

  • jQuery.get( url [, data ] [, success ] [, dataType ] )

equals:

$.ajax({
  url: url,
  data: data,
  success: success,
  dataType: dataType
});

Post

jQuery.post( url [, data ] [, success ] [, dataType ] )

  • url
    • Type: String
    • A string containing the URL to which the request is sent.
  • data * Type: PlainObject or String * A plain object or string that is sent to the server with the request.
  • success * Type: Function( Object data, String textStatus, jqXHR jqXHR ) * A callback function that is executed if the request succeeds. Required if dataType is provided, but can be null in that case.
  • dataType * Type: String * The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html).

Example

Login

  1. construct a form and a submit button

  2. set the button handler function

  3. in the function:

    $.post(url, $(this).serialize(), function(data) {
        $("#retDiv").html(data);
    });
    
  • refer to http://hayageek.com/jquery-ajax-form-submit/:

    //callback handler for form submit
    $("#ajaxform").submit(function(e)
    {
        var postData = $(this).serializeArray();
        var formURL = $(this).attr("action");
        $.ajax(
        {
            url : formURL,
            type: "POST",
            data : postData,
            success:function(data, textStatus, jqXHR)
            {
                //data: return data from server
            },
            error: function(jqXHR, textStatus, errorThrown)
            {
                //if fails
            }
        });
        e.preventDefault(); //STOP default action
        e.unbind(); //unbind. to stop multiple form submit.
    });
    
    $("#ajaxform").submit(); //Submit  the FORM
    

Single page security

  1. The user navigates in their browser to the application
  2. The server returns a basic web page and a JavaScript application
  3. The JavaScript application can’t find an authentication token in the web site’s cookies
  4. The JavaScript application displays a login form
  5. The user enters correct login credentials and then submits the form
  6. The server validates the login information and creates an authentication token for the user
  7. The server sets the authentication token in a cookie and returns it to the JavaScript application
  8. The JavaScript application makes a request for some protected data, sending the authentication token in a custom header
  9. The server validates the token and then returns the data