embedded url in javascript code - javascript

i think there is a partial url in here but cant read it. ie
i have www.website.com/
and need the next part
$j('.get-code').live('click', function() {
linkId = $j(this).attr("id");
codeId = linkId.replace("get-code-day-", "");
voucherCode = $j("#voucher-code-day-" + codeId).val();
$j.post("/promotions/ajax/add-user-voucher", {
voucherCode: voucherCode
}, function(xml) {
if ($j("status", xml).text() == "1") {
// do something on success
} else {
showUIDialog("<p>A problem occurred: " + $j("error", xml).text() + "</p>");
}
return false;
});

Related

How to access variable parent scope from an event handler

I have the following piece of code to retrieve a Wikipedia infobox:
function foo() {
var searchTerm = "Something...";
var bnameonly = "Something else...";
var url = "https://en.wikipedia.org/w/api.php?action=parse&format=json&page=" + searchTerm + "&redirects&prop=text&callback=?";
$.getJSON(url, function(data) {
if (typeof(data.parse) !== 'undefined') {
wikiHTML = data.parse.text["*"];
$wikiDOM = $("<table>" + wikiHTML + "</table>");
infobox = $wikiDOM.filter('.infobox.biota');
$("#wiki").contents().find('#myinfobox').html(infobox);
} else {
var url = "https://en.wikipedia.org/w/api.php?action=parse&format=json&page=" + bnameonly + "&redirects&prop=text&callback=?";
$.getJSON(url, function(data) {
if (typeof(data.parse) !== 'undefined') {
wikiHTML = data.parse.text["*"];
$wikiDOM = $("<table>" + wikiHTML + "</table>");
infobox = $wikiDOM.filter('.infobox.biota');
$("#wiki").contents().find('#myinfobox').html(infobox);
}
});
}
});
}
However, if the first query fails (detected by typeof(data.parse) == 'undefined' being true) then the else clause should be executed. The problem is that the bnameonly variable is undefined at that point even when it has been declared in the parent environment.
You can only check to see if the HTML is empty after you know the response has come back from the server (regardless of if it succeeded or failed). You can use jQuery's always method on it's jqXHR to test for this.
function foo() {
var searchTerm = "Something...";
var bnameonly = "Something else...";
function myCallback(data) {
...
}
var url="https://en.wikipedia.org/w/api.php?action=parse&format=json&page=" + searchTerm + "&redirects&prop=text&callback=?";
$.getJSON(url,{data})
.done(myCallback)
.always(function() {
//executed only after $.getJSON succeeds or fails
if ($("#wiki").contents().find('#myinfobox').html() === '') {
var url="https://en.wikipedia.org/w/api.php?action=parse&format=json&page=" + bnameonly + "&redirects&prop=text&callback=?";
$.getJSON(url, {data}, myCallback);
}
})
}
based on the answers I've found in this other forum (https://forum.jquery.com/topic/how-do-i-access-json-data-outside-of-getjson), I've found a solution by using a callback function:
function foo() {
var searchTerm = "Something...";
var bnameonly = "Something else...";
function myCallback(data) {
if (typeof(data.parse) !== 'undefined') {
wikiHTML = data.parse.text["*"];
$wikiDOM = $("<table>"+wikiHTML+"</table>");
infobox = $wikiDOM.filter('.infobox.biota');
$("#wiki").contents().find('#myinfobox').html(infobox);
} else {
$("#wiki").contents().find('#myinfobox').html('');
}
}
var url="https://en.wikipedia.org/w/api.php?action=parse&format=json&page=" + searchTerm + "&redirects&prop=text&callback=?";
$.getJSON(url, {data}, myCallback);
if ($("#wiki").contents().find('#myinfobox').html() === '') {
var url="https://en.wikipedia.org/w/api.php?action=parse&format=json&page=" + bnameonly + "&redirects&prop=text&callback=?";
$.getJSON(url, {data}, myCallback);
}
}

Ajax call at last

in my jquery function i have two ajax call with serverside method and its working fine,
problem is ajax call at last amd after ajax line of code run but this lines of code depand on
function Rbook(b) {
var one = $(b).attr("data-oneislcc");
var two = $(b).attr("data-twoislcc");
var trip1 = $(b).attr("data-oneinfo");
var trip2 = $(b).attr("data-twoinfo");
var owflt = "l";
var inflt = 'r';
var owjdata = $(b).attr("data-ow");
var iwjdata = $(b).attr("data-iw");
var llccreturn, rlccreturn;
var lres, rres;
$("#fadeing").css("display", "block");
$("#fade").css("display", "block").css("height", $(document).height / 2);
if (one == 'true') {
$.ajax({
type: "POST",
url: "Search-RoundResult.aspx/FareQuoteMethod",
data: "{'ALcode':'" + trip1 + "','flt':'" + owflt + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function OnSuccess(response) {
if (response.d != null) {
lres = response.d;
if (response.d == "sessionExpire") {
}
else {
var data = new Array()
data = response.d.split("oldfare=");
llccreturn = owlcc(data[0], data[1])
}
}
else {
alert("Please Try agian.");
}
},
Error: function errer(msg) {
$("#fade").css("display", "none");
$("#light").css("display", "none");
alert(msg.d)
}
});
}
else {
llccreturn = ownonlcc(owjdata);
}
if (two == 'true') {
$.ajax({
type: "POST",
url: "Search-RoundResult.aspx/FareQuoteMethod",
data: "{'ALcode':'" + trip2 + "','flt':'" + inflt + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function OnSuccess(response) {
if (response.d != null) {
if (rres == "sessionExpire") {
}
else {
var data = new Array()
data = response.d.split("oldfare=");
rlccreturn = iwlcc(data[0], data[1])
}
}
else {
alert("Please Try agian.");
}
},
Error: function errer(msg) {
$("#fade").css("display", "none");
$("#light").css("display", "none");
alert(msg.d)
}
});
}
else {
rlccreturn = iwnonlcc(iwjdata);
}
if (llccreturn == 'farechange' || rlccreturn == 'farechange') {
$("#farechange").css("display", "block");
$("#fade").css("display", "block");
}
if (llccreturn == 'nofarechange' || rlccreturn == 'nofarechange') {
window.location = "reviewbooking.aspx?trip1=" + $(b).attr("data-oneinfo") + "&iwlcc=" + $(b).attr("data-oneislcc") + "&trip2=" + $(b).attr("data-twoinfo") + "&owlcc=" + $(b).attr("data-twoislcc");
}}
var owlcc = function (jdata, oldfare) {
//Some Calulation
retrun 'farechange';
}
var ownonlcc = function (jdata) { //Some Calulation
retrun 'nofarechange'}
var iwlcc = function (jdata, oldfare) { //Some Calulation
return 'farechange'}
var iwnonlcc = function (jdata) { retrun 'nofarechange'}
if run this code its run this line of code then rest so condition not validate
i dont know where i m doing wrong
if (llccreturn == 'farechange' || rlccreturn == 'farechange') {
$("#farechange").css("display", "block");
$("#fade").css("display", "block");
}
if (llccreturn == 'nofarechange' || rlccreturn == 'nofarechange') {
window.location = "reviewbooking.aspx?trip1=" + $(b).attr("data-oneinfo") + "&iwlcc=" + $(b).attr("data-oneislcc") + "&trip2=" + $(b).attr("data-twoinfo") + "&owlcc=" + $(b).attr("data-twoislcc");
}
It looks like you don't understand asynchronous javascript. When you do an ajax call, it sends the request, then continues running the code and only later runs the success handler. Otherwise, it wouldn't be able to do anything at all until the response came back, since javascript is single-threaded.
The Rbook function does the following: First, get lots of information from the DOM; then, send some ajax requests (and set handlers to run when the response comes back); then possibly make some changes to the DOM, depending on the values of llccreturn and rlccreturn (but they're still undefined). It's only when the ajax response comes back and the success handler is run that these variables are set, but by then it's too late.
If you want to run some code after hearing the ajax response, put it in the success handler (or call it from the success handler). In this case, it's further complicated by the fact that you don't want to run the code until both ajax responses have arrived, and also by the fact that you might just run iwnonlcc or ownonlcc synchronously instead of doing an ajax call. I'd say the easiest way to fix this would be to wrap the code you want to run at the end inside a function and an if block like this:
function dataWasReceived() {
if (llccreturn !== undefined && rlccreturn !== undefined) {
if (llccreturn == 'farechange' || rlccreturn == 'farechange') {
$("#farechange").css("display", "block");
$("#fade").css("display", "block");
}
if (llccreturn == 'nofarechange' || rlccreturn == 'nofarechange') {
window.location = "reviewbooking.aspx?trip1=" + $(b).attr("data-oneinfo") + "&iwlcc=" + $(b).attr("data-oneislcc") + "&trip2=" + $(b).attr("data-twoinfo") + "&owlcc=" + $(b).attr("data-twoislcc");
}
}
}
Then, every time you set the value of llccreturn or rlccreturn, call this function:
rlccreturn = iwlcc(data[0], data[1])
dataWasReceived();
and:
rlccreturn = iwnonlcc(iwjdata);
dataWasReceived();
etc.
I'm also concerned about this line (appears twice):
data: "{'ALcode':'" + trip2 + "','flt':'" + inflt + "'}",
You probably wanted to apply the argument as an object, not a JSON string representing that object:
data: {ALcode: trip2, flt: inflt},
(Incidentally, the string you gave wasn't valid JSON anyway, since it used ' instead of ".)

Javascript Asynchronous to Synchronous task

I have the following code (these codes are in separated js files ) :
Code 1 (home.js):
alert('1');
BeginGetDashboardsMethod();
alert('5');
Code 2(script.js) :
function BeginGetDashboardsMethod(){
var stop = 'false';
alert('2');
try {
Service.GetDashboardsMobile("" + curr_cod_user, SuccessGetDashboardMethod, ErrorGetDashboardMethod);
}
catch (e) {
}
function SuccessGetDashboardMethod(result) {
alert('3');
json = result;
json = JSON.parse(json);
ListDashboards(json);
}
function ErrorGetDashboardMethod(err) {
alert(JSON.stringify(err));
}
function ListDashboards(json) {
alert('4');
for (var i = 0; i < json.Dashboards.length; i++) {
if (json.Dashboards.length === 1)
Items = "[{key:\'" + json.Dashboards[i].OBV_ST_TITULO + "\', title:\'" + json.Dashboards[i].OBV_ST_TITULO + "\'}]";
else {
if (i == 0) {
Items += "[{key:\'" + json.Dashboards[i].OBV_ST_TITULO + "\', title:\'" + json.Dashboards[i].OBV_ST_TITULO + "\'} ";
}
else if (i + 1 == json.Dashboards.length) {
Items += ",{key:\'" + json.Dashboards[i].OBV_ST_TITULO + "\', title:\'" + json.Dashboards[i].OBV_ST_TITULO + "\'}] ";
}
else {
Items += ",{key:\'" + json.Dashboards[i].OBV_ST_TITULO + "\', title:\'" + json.Dashboards[i].OBV_ST_TITULO + "\'} ";
}
}
}
obj = eval(Items);
} }
My code works asynchronous. After Service.GetDashboardsMobile call the code "skip" Success callback and execute alert(5); while executing callback. Is there a way to make that functions synchronous?
To be more exactly, I want that sequence : alert('1');-->alert('2');-->alert('3');-->alert('4');-->alert('5')
Welcome to the new world of Promises.
script.js
alert("1"); // script 1 loaded
function $dashboard(user) {
function getDashboard(start, limit) {
var user = user;
return new Promise(function(pass, fail) {
if( Math.random()*3 > 2 ) {
fail(new Error("boo hoo"));
} else {
window.setTimeout(pass, 5000, '{"time": 5000, "content": "foo"}');
}
});
}
function parseData(json) {
return new Promise(function(pass, fail) {
try {
pass(JSON.parse(json));
} catch(e) {
fail(e);
}
});
}
function printData(data) {
alert(JSON.stringify(data));
return true;
}
return {
get: getDashboard,
parse: parseData,
print: printData
};
}
home.js
(function(d,w,$) {
alert("2"); // script 2
var dashboard = $("mcfoobar");
dashboard
.get(0, 100)
.then(function(sData) {
alert("3"); // data retrieved
return dashboard.parse(sData);
})
.then(function(oData) {
alert("4"); // data parsed
return dashboard.print(oData);
})
.then(function(result) {
alert("5"); // data printed
})
.catch(function(err) {
alert(JSON.stringify(err)); // Something went wrong
});
}(document, window, $dashboard));
Notes:
Why all the alerts? Surely console.log(..) is a much better solution. Certainly a lot less clicking.
You will have to make sure script.js is loaded. Hopefully home.js has some sort of el.onload event on the <script> element of script.js.
For backward compatibility you will need to have a definition of Promises just in case. But that should be easy to implement. You can use v8 version if it doesn't already exist in some compatibility library.
Make sure you note how values are changed in the chain by returning different values in the .then() function. To keep original values simply forward parameters.

Ajax File Upload Not Working for IE8

I'm having trouble uploading a file using a Javascript function that makes an Ajax call to a servlet. The file is uploaded perfectly when I use chrome, but not when I use IE8 (Go figure).
I used to have a file select button on the bottom of my form. When I clicked that button a function would be called and it would upload the file to the servlet using ajax. This worked perfectly in IE8, but the client wanted links instead. So now I have the links in the form, and the buttons hidden with css. The links call the click event of the buttons. Now the file uploading only works with Chrome, and not IE8.
The request never makes it to the servlet for some reason, and for some reason the ajax request returns success. Any idea what the problem might be?
Here is my code:
//Uploading a file
$("#uploaded_file").change(function() {
var filename = $(this).val();
if(isAcceptable(filename)) {
$.ajaxFileUpload
(
{
type: "POST",
url:'GenerateServlet',
secureuri:false,
fileElementId:'uploaded_file',
dataType: 'json',
success: function (data, status)
{
if(typeof(data.error) != 'undefined')
{
if(data.error != '')
{
alert(data.error);
}else
{
alert(data.msg);
}
}
fillTemplate(data);
}
}
)
}
else if(filename.length > 0){
$("#uploaded_file").val("");
alert("Invalid File! Please select another file")
}
});
$("#upload_link").click(function() {
document.getElementById('uploaded_file').click();
return false;
});
Here is the upload function:
jQuery.extend({
createUploadIframe: function(id, uri)
{
//create frame
var frameId = 'jUploadFrame' + id;
var iframeHtml = '<iframe id="' + frameId + '" name="' + frameId + '" style="position:absolute; top:-9999px; left:-9999px"';
if(window.ActiveXObject)
{
if(typeof uri== 'boolean'){
iframeHtml += ' src="' + 'javascript:false' + '"';
}
else if(typeof uri== 'string'){
iframeHtml += ' src="' + uri + '"';
}
}
iframeHtml += ' />';
jQuery(iframeHtml).appendTo(document.body);
return jQuery('#' + frameId).get(0);
},
createUploadForm: function(id, fileElementId, data)
{
//create form
var formId = 'jUploadForm' + id;
var fileId = 'jUploadFile' + id;
var form = jQuery('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');
if(data)
{
for(var i in data)
{
jQuery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form);
}
}
var oldElement = jQuery('#' + fileElementId);
var newElement = jQuery(oldElement).clone();
jQuery(oldElement).attr('id', fileId);
jQuery(oldElement).before(newElement);
jQuery(oldElement).appendTo(form);
//set attributes
jQuery(form).css('position', 'absolute');
jQuery(form).css('top', '-1200px');
jQuery(form).css('left', '-1200px');
jQuery(form).appendTo('body');
return form;
},
ajaxFileUpload: function(s) {
// TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
s = jQuery.extend({}, jQuery.ajaxSettings, s);
var id = new Date().getTime()
var form = jQuery.createUploadForm(id, s.fileElementId, (typeof(s.data)=='undefined'?false:s.data));
Console.log(form);
var io = jQuery.createUploadIframe(id, s.secureuri);
var frameId = 'jUploadFrame' + id;
var formId = 'jUploadForm' + id;
// Watch for a new set of requests
if ( s.global && ! jQuery.active++ )
{
jQuery.event.trigger( "ajaxStart" );
}
var requestDone = false;
// Create the request object
var xml = {}
if ( s.global )
jQuery.event.trigger("ajaxSend", [xml, s]);
// Wait for a response to come back
var uploadCallback = function(isTimeout)
{
var io = document.getElementById(frameId);
try
{
if(io.contentWindow)
{
xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;
xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;
}else if(io.contentDocument)
{
xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;
xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;
}
}catch(e)
{
jQuery.handleError(s, xml, null, e);
}
if ( xml || isTimeout == "timeout")
{
requestDone = true;
var status;
try {
status = isTimeout != "timeout" ? "success" : "error";
// Make sure that the request was successful or notmodified
if ( status != "error" )
{
// process the data (runs the xml through httpData regardless of callback)
var data = jQuery.uploadHttpData( xml, s.dataType );
// If a local callback was specified, fire it and pass it the data
if ( s.success )
s.success( data, status );
// Fire the global callback
if( s.global )
jQuery.event.trigger( "ajaxSuccess", [xml, s] );
} else
jQuery.handleError(s, xml, status);
} catch(e)
{
status = "error";
jQuery.handleError(s, xml, status, e);
}
// The request was completed
if( s.global )
jQuery.event.trigger( "ajaxComplete", [xml, s] );
// Handle the global AJAX counter
if ( s.global && ! --jQuery.active )
jQuery.event.trigger( "ajaxStop" );
// Process result
if ( s.complete )
s.complete(xml, status);
jQuery(io).unbind()
setTimeout(function()
{ try
{
jQuery(io).remove();
jQuery(form).remove();
} catch(e)
{
jQuery.handleError(s, xml, null, e);
}
}, 100)
xml = null
}
}
// Timeout checker
if ( s.timeout > 0 )
{
setTimeout(function(){
// Check to see if the request is still happening
if( !requestDone ) uploadCallback( "timeout" );
}, s.timeout);
}
try
{
var form = jQuery('#' + formId);
jQuery(form).attr('action', s.url);
jQuery(form).attr('method', 'POST');
jQuery(form).attr('target', frameId);
if(form.encoding)
{
jQuery(form).attr('encoding', 'multipart/form-data');
}
else
{
jQuery(form).attr('enctype', 'multipart/form-data');
}
jQuery(form).submit();
} catch(e)
{
jQuery.handleError(s, xml, null, e);
}
jQuery('#' + frameId).load(uploadCallback );
return {abort: function () {}};
},
uploadHttpData: function( r, type ) {
var data = !type;
data = type == "xml" || data ? r.responseXML : r.responseText;
// If the type is "script", eval it in global context
if ( type == "script" )
jQuery.globalEval( data );
// Get the JavaScript object, if JSON is used.
if ( type == "json" )
eval( "data = " + data );
// evaluate scripts within html
if ( type == "html" )
jQuery("<div>").html(data).evalScripts();
return data;
}
})
That is a typical Microsoft security measure (e.g. to stop automated uploads).
That means you have to originate an upload from an actual user-pressed button click.
Style the button to make it look like a link instead.

Moved code into a function. Now doesn't work. What's wrong?

First a huge code block followed by the actual question.
$(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;
});
});
The same code can be read at
http://pastebin.com/0kXzZGND
with line numbers.
I moved the huge code block from line 205-245 into a function sendData(is_okay) at line 26-65. The function is called at line 181 and 186.
The code that I put in the function uses things like $.ajax({ and $(this)..
Could this be a problem?
If so, how can that be fixed?
Update
The code block should update the HTML, but it doesn't do that anymore.
Update
After applying one patrick dw's solutions I get this error:
result is null
and it points to this code
success: function(result) {
in the newly created function.
Is it because the GET request now doesn't return anything?
Your issue is like with $(this).. If you're just calling a function like normal, the value of this will be window. I'm guessing you're expecting a DOM element.
You can manually set the value of this in the function you're calling by using the .call method.
To do so, call your function as follows:
sendData.call( this, 1 );
Another option would be to have your function accept another argument, and use that:
sendData( 1, this );
function sendData(is_okay, el) {
// ...
data: $(el).serialize(),

Categories