Skip to content

Instantly share code, notes, and snippets.

@khoand0000
Last active October 7, 2015 06:48
Show Gist options
  • Save khoand0000/67247703d7838e9f4262 to your computer and use it in GitHub Desktop.
Save khoand0000/67247703d7838e9f4262 to your computer and use it in GitHub Desktop.
jquery snippets
  • Send form data using ajax requests
$.post( "test.php", $( "#testform" ).serialize() )
  .done(function( data ) {})
  .fail(function(data){
      console.log(data.responseJSON);
      console.log(data.responseText);
      console.log(data.status); // status code, ex: 400
    }); 
  • Send json data using ajax requests
$.post( "test.php", JSON.stringify({}) ).done(function( data ) {}); 
  • Send json data (convert form data) using ajax requests
var data = {};
$.each($("#form").serializeArray(), function (i, field) {
    data[field.name] = field.value;
});
$.post( "test.php", JSON.stringify(data) ).done(function( data ) {}); 
  • If request return empty response but status is 200 (success), use .always() instead of .done(); .fail() because the case will .fail() is called instead of .done() (I don't know why)
  • Add options to select element after get data from server (data is array)
$.get("/projects", {} ).done(function( data ) {
    $.each(data, function(key, value) {
        $('#project')
            .append($("<option></option>")
                .attr("value",value.id)
                .text(value.name));
    });
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment