var option; var form; function rebindSubmit() { $("#orderForm").unbind('submit'); $("#orderForm").submit(function(event) { validateForm(event); }); } function loadForm(event) { $("input[name=option]").each(function() { if ($(this).attr("checked")) { option = $(this).val(); } }); form = $("#requested_form").val(); $.ajax({ url: "/centrum-sluzeb/upravy-stehovani/lim-form?option=" + option + "&form=" + form, cache: false, success: function(data) { $("#ajaxBody").html(data); rebindSubmit(); }, error: function(obj, error) { console.log(error); } }); } function validateForm(event) { // prevent the form from actually submitting event.preventDefault(); var formDOM = document.getElementById("orderForm"); var values = {}; $.each($('#orderForm').serializeArray(), function(i, field) { values[field.name] = field.value; }); // submit the form in the background $.ajax({ type: 'POST', data: values, url: "/centrum-sluzeb/upravy-stehovani/lim-form-validate", cache: false, dataType: "json", success: function(data) { if(typeof data == "error") { console.warn("error!",error); } else if (data == "true") { clearFormError(); formDOM.submit(); } else { // show our response var json = eval("(" + data + ")"); clearFormError(); for (var elem in json) { var msg = ""; $("#" + elem + "_error").html(msg); } } } }); } function clearFormError() { var elements = $('#orderForm :input'); elements.each(function() { var errorElem = $("#" + $(this).attr("name") + "_error"); var inputElem = $(this); if (errorElem.size() > 0) { errorElem.html(""); } else if (inputElem.attr("id") == inputElem.attr("name")) { var div = document.createElement("div"); div.setAttribute("id", $(this).attr("name") + "_error"); inputElem.parent().append(div); } }); }