Сначала огромный блок кода, за которым следует фактический вопрос.
$(document).ready(function(){
// debug. takes an object as argument and prints its content
function printObject(o) {
var out = '';
// for (var p in o) {
// out += p + ': ' + o[p] + '\n';
// }
for (var p in o) {
if (!o.hasOwnProperty(p)) out += '(inherited) ';
out += p + ': ' + o[p] + '\n';
}
alert(out);
}
function makeDialogTable(users) {
var result = '<table>\n<tr><td>Initials</td><td>Full Name</td></tr>\n';
$.each(users, function(index, value) {
result += '<tr><td>' + index + '</td><td>' + value + '</td></tr>\n';
});
result += '</table>';
return (result);
}
function sendData(is_okay) {
// if all form fields have been filled out
if (is_okay == 1) {
$.ajax({
type: "GET",
url: "/cgi-bin/ajax.pl",
contentType: "application/json; charset=utf-8",
dataType: "json",
// generate and send parameters to server-side script
data: $(this).serialize(),
// script call was *not* successful
error: function(XMLHttpRequest, textStatus, errorThrown) {
$('div#create_result').text("responseText: " + XMLHttpRequest.responseText + ", textStatus: " + textStatus + ", errorThrown: " + errorThrown);
$('div#create_result').addClass("error");
}, // error
// script call was successful
// result contains the JSON values returned by the Perl script
success: function(result){
if (result.error) { // script returned error
$('div#create_result').text("result.error: " + result.error);
$('div#create_result').addClass("error");
} else { // perl script says everything is okay
$('div#create_result').text("result.success: " + result.success + ", result.id: " + result.id);
$('div#create_result').addClass("success");
} //else
} // success
}); // ajax
} else { // if (is_okay) { ...
$('div#create_result').text("Submission cancelled. Changes have not been saved.");
$('div#create_result').addClass("error");
} // if/else
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// required for $(this) to work for save bottons
$('form').live('submit', function(){
var title = this.elements.title.value;
var owner = this.elements.owner.value;
var users = this.elements.users.value;
var groups = this.elements.groups.value;
var begin_date = this.elements.from.value;
var end_date = this.elements.to.value;
var anchor = this.elements.anchor.value;
// get selected radio button using name instead if ID
var type = $(this).find('input:radio[name="ctype"]:checked').val() || '';
// check value
var is_okay = 0;
if (title == '') {
alert('Title is required');
} else if (!(/[A-Za-z0-9]|\s/.test(title))) {
alert('Illegal characters in title. Only a-z A-Z and space is allowed');
} else if (owner == '') {
alert('Owner is required');
} else if (!(/[A-Za-z]|,/.test(owner))) {
alert('Illegal characters in owner. Only a-z A-Z and , is allowed');
} else if (begin_date == '') {
alert('Begin Date is required');
} else if (!(/\d{2}\/\d{2}-\d{4}/.test(begin_date))) {
alert('Illegal characters in Begin Date. Format must be: dd/mm-yyyy');
} else if (end_date == '') {
alert('End Date is required');
} else if (!(/\d{2}\/\d{2}-\d{4}/.test(end_date))) {
alert('Illegal characters in End Date. Format must be: dd/mm-yyyy');
} else if (type == '') {
alert('Type is required');
} else if (type == "individuel" && groups != '') {
alert('Groups are not allowed for individuel');
} else if (type == "individuel" && users == '') {
alert('Users is required');
} else if (type == "individuel" && groups == '' && !(/[A-Za-z]|,/.test(users))) {
alert('Illegal characters in users. Only a-z A-Z and , is allowed');
} else if (type == "course" && users != '') {
alert('Users are not allowed for course');
} else if (type == "course" && groups == '') {
alert('Groups is required');
} else if (type == "course" && users == '' && !(/[A-Za-z]|,/.test(groups))) {
alert('Illegal characters in groups. Only a-z A-Z and , is allowed');
} else {
is_okay = 1;
}
// if all form fields have been filled out
// send the form data for varification and look up display names and show in a confirm box
if (is_okay == 1) {
$.ajax({
type: "GET",
url: "/cgi-bin/ajax_confirm.pl",
contentType: "application/json; charset=utf-8",
dataType: "json",
// generate and send parameters to server-side script
data: $(this).serialize(),
// script call was *not* successful
error: function(XMLHttpRequest, textStatus, errorThrown) {
$('div#create_result').text("responseText: " + XMLHttpRequest.responseText +
", textStatus: " + textStatus +
", errorThrown: " + errorThrown);
$('div#create_result').addClass("error");
alert("Error occured in ajax.js confirm code. Report this to mj@imm.dtu.dk");
}, // error
// script call was successful
// result contains the JSON values returned by the Perl script
success: function(result){
if (result.error) { // script returned error
$('div#create_result').text("result.error: " + result.error);
$('div#create_result').addClass("error");
} else { // perl script says everything is okay
// decode JSON string into arrays
var users = $.parseJSON(result.users);
var owners = $.parseJSON(result.owners);
// a workaround for a flaw in the demo system (http://dev.jqueryui.com/ticket/4375), ignore!
$("#dialog:ui-dialog").dialog("destroy");
$("#dialog-confirm").dialog({
resizable: false,
height: 600,
modal: true,
open: function() {
$(this).children('div.dialog-text').replaceWith("<h3><b>Users</b></h3>" + makeDialogTable(users) + "<h3><b>Owners</b></h3>" + makeDialogTable(owners));
},
buttons: {
Okay: function() {
$(this).dialog("close");
sendData(1);
},
Cancel: function() {
is_okay = 0;
$(this).dialog("close");
sendData(0);
}
} // buttons
}); // dialog
} //else
} // success
}); // ajax
} else { // if (is_okay) { ...
$('div#create_result').text("Fill out the form to create an activity");
$('div#create_result').addClass("error");
is_okay = 0;
} // else
// // if all form fields have been filled out
// if (is_okay == 1) {
// $.ajax({
// type: "GET",
// url: "/cgi-bin/ajax.pl",
// contentType: "application/json; charset=utf-8",
// dataType: "json",
// // generate and send parameters to server-side script
// data: $(this).serialize(),
// // script call was *not* successful
// error: function(XMLHttpRequest, textStatus, errorThrown) {
// $('div#create_result').text("responseText: " + XMLHttpRequest.responseText + ", textStatus: " + textStatus + ", errorThrown: " + errorThrown);
// // extract error message
// // var pattern = new RegExp(": \"(.+)\"}");
// // var match = pattern.exec(XMLHttpRequest.responseText);
// // $('div#create_result').text(match[1]);
// $('div#create_result').addClass("error");
// }, // error
// // script call was successful
// // result contains the JSON values returned by the Perl script
// success: function(result){
// if (result.error) { // script returned error
// $('div#create_result').text("result.error: " + result.error);
// $('div#create_result').addClass("error");
// } else { // perl script says everything is okay
// $('div#create_result').text("result.success: " + result.success + ", result.id: " + result.id);
// $('div#create_result').addClass("success");
// } //else
// } // success
// }); // ajax
// } else { // if (is_okay) { ...
// $('div#create_result').text("Fill out the form to create an activity");
// $('div#create_result').addClass("error");
// } // else
$('div#create_result').fadeIn();
return false;
});
});
Тот же код можно прочитать на
http://pastebin.com/0kXzZGND
с номерами строк.
Я переместил огромный блок кода из строки 205-245 в функцию sendData(is_okay)
в строке 26-65. Функция вызывается в строках 181 и 186.
Код, который я вставил в функцию, использует такие вещи, как $.ajax({
и $(this).
.
Может ли это быть проблемой?
Если так, как это можно исправить?
Обновление
Блок кода должен обновить HTML, но он больше этого не делает.
Обновление
После применения одного решения Патрика Д. я получаю эту ошибку:
result is null
и он указывает на этот код
success: function(result) {
во вновь созданной функции.
Это потому, что запрос GET теперь ничего не возвращает?