Created
May 26, 2015 16:34
-
-
Save Overbryd/04522565cf022b281101 to your computer and use it in GitHub Desktop.
This gives pajax functionality
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// pajax functionality | |
function pajaxForm(form) { | |
var url = form.attr("action"); | |
var target = form.data("pajax"); | |
form.ajaxSubmit({ | |
type: "POST", | |
url: url, | |
target: "*[data-pajax-target=" + target + "]" | |
}); | |
}; | |
$("body").delegate("form[data-pajax]", "submit", function(event) { | |
event.preventDefault(); | |
pajaxForm($(this)); | |
}); | |
// <form data-pajax..> attribute handling | |
$("body").delegate("form[data-pajax] :input[data-pajax-change]", "change", function(event) { | |
var form = $(this).closest("form[data-pajax]"); | |
pajaxForm(form); | |
}); | |
// general purpose ajax form submit, including file upload | |
$.fn.ajaxSubmit = function(options) { | |
if (!this.length) { return this; } | |
this.bind("submit", function(event) { event.preventDefault(); }); | |
var inputs = this.find(':input:enabled'); | |
var formData = new FormData(); | |
$.each(inputs, function() { | |
if (!this.name) { return; } | |
if (this.files) { | |
formData.append(this.name, this.files[0]); | |
} else if (this.type == "radio") { | |
if (this.checked) { | |
formData.append(this.name, $(this).val()); | |
} | |
} else if (this.type == "select-one") { | |
if (this.selectedIndex !== undefined) { | |
formData.append(this.name, this.options[this.selectedIndex].value); | |
} | |
} else { | |
formData.append(this.name, this.value); | |
} | |
}); | |
$.ajax({ | |
type: "POST", | |
url: options.url, | |
beforeSend: function(xhr, o) { | |
o.data = formData; | |
}, | |
success: function(data) { | |
pathToNode(document.activeElement).then(function(refocusPath) { | |
$(options.target).replaceWith(data); | |
$(refocusPath).focus(); | |
}); | |
} | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment