Javascript data check will always return true - javascript

this is my java script, where I am checking if data comes do some thing else do something
function translateData() {
var word = $('#word').val();
var lang = $('#lang').val();
$("#result").html("loading...");
$.post("translateAdmin.action", {
word : word,lang:lang
}, function(data) {
if (data.length > 0) {
$().toastmessage('showSuccessToast', "Translation Done");
//alert("Translation Done");
}
else {
$().toastmessage('showErrorToast', "Translation Not Done");
// alert("Unable to translate");
}
But, it will never go to else, even if it does not return any data in text area, it shows exception in my action class but it give an success message.

Related

Javascript callbacks in asp pages

I've looked at this How-do-i-return-the-response-from-an-asynchronous-call and at why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron , but what I'm trying to do doesn't work.
Since some of our users use IE, it seems that we would have to rely on callbacks.
The background to this question comes from a previous post. Legacy code used VBscript's MsgBox, but now the same functionality must be ported to Javascript.
To provide context, there is a bunch of buttons on a toolbar (hence toolbar.asp) such as "New", "Update", "Delete". The user can navigate to certain parts of the system and for instance create a "New" record for a particular resource/person. The details and functionality are shown on the main part of the screen (hence main.asp).
The system was originally written about 15 years ago (or more).
When the user clicks "Update" on the toolbar.asp, it depends which screen the main.asp was showing. Parts of dovalidation() in main.asp can be swopped (as in a script is fetched from the database) and inserted into dovalidation() depending on what & where the user is.
So some parts are still in Visual Basic 6, but it seems that they are trying to replace the VBscript with Javascript.
So the user is on a specific screen and clicks Update (the toolbar.asp's doupdate() is called).
This doupdate() does a number of checks on the date and other variables and the calls the main.asp's dovalidation().
Depending on where the user finds himself, dovalidation looks different.
In quite a few cases as in the specific example that I am talking about, there used to be a MsgBox in the VBscript code which gave the user a choice depending on the validation done up to that point. However, that VBscript should now be replaced by Javascript. It seems my boss doesn't want to use the normal window.confirm, because she wants to be able to customise the buttons.
VBscript's MsgBox blocked further execution, but now using a jquery confirm doesn't have the same results, because it is non-blocking.
If the validation occurs in such a way that the user is provided with the confirm dialog, and the user clicks on 'Cancel' then the next page should not be shown, but at present, whether the user clicks on 'Cancel' or not, the next page is shown after a couple of seconds.
At the end of the doupdate() function there is:
parentMain.screenform.submit();
Could that be part of why my callbacks don't work?
In a toolbar.asp file, this is called in the doupdate() funtion:
//... Other code that determines variables, fringe scenarios etc.
//...
// Then dovalidation() (in which the blocking MsgBox used to be) is called:
var sErr = parentMain.dovalidation();
if (sErr != ""){
return;
}
//Then the rest of the code which is executed irrespective of the jquery confirm.
//do update
try {
parentMain.document.all("Updating").value = "YES"
parentMain.document.body.scrollTop = 0
parentMain.document.body.scroll = 'no'
parentMain.ShowBusy();
document.getElementById("sysBusy").value = "true";
//parentMain.document.all("clockFrame").style.display = "block";
} catch(e) {
return (e)
}
//do check for resource tag
if (sScreenType.toUpperCase() == "RESOURCE TABLE") {
if (lResource == "0") {
parentMain.document.all("sysresource").value = lDetailResource
}
//alert("looping for resource tag");
var sField = ""
var sCheck = "Resource Tag"
if (!(sScreen == "Resource")) {
/*********************************************************************/
/** loop through the fields and update resouce tag if empty - submit**/
/*********************************************************************/
var elements = parentMain.document.getElementById("screenform").elements;
for (var i = 0, element; element = elements[i++];) {
if ((element.name).indexOf(sCheck) > 0) {
var sValue = element.value
if (sValue.length == 0) {
element.value = lDetailResource
}
}
if ((element.tagName.toUpperCase()) == "SELECT") {
if (element.disabled == true) {
element.disabled = false;
}
}
}
}
}
//submit screen
parentMain.screenform.submit(); //<-- Could this be part of the problem?
}
In the main.asp file the dovalidation function resides. A part of the dovalidation function is swapped out depending on the situation. That is marked between the //################
function dovalidation() {
msErr = "";
//#################
if (msErr.length == 0) {
var vEffectiveDate="";
var vLastRunDate="";
var sStatus="";
var vMsg="";
var sResponse="";
vEffectiveDate = document.getElementById("Smoke.Effective Date").value;
vLastRunDate = document.getElementById("Smoke.Last Run Date").value;
sStatus = document.getElementById("Smoke.Calc Status").value;
vMsg = "";
if ((sStatus).length == 0 ){
sStatus = "SUCCESFUL";
//document.getElementById("Smoke.Calc Status").value= sStatus;
}
if ((vEffectiveDate).length > 0 ){
if (!isDate(vEffectiveDate) ){
vMsg = vMsg+"[Effective Date] Is not a date." + ";\r\n";
} else if ( moment( toDate(vEffectiveDate)).isBefore(toDate(vLastRunDate)) ){
vMsg = vMsg+"[Effective Date] cannot be on/before "+vLastRunDate+"." + ";\r\n";
}
}
if (sStatus.toUpperCase() != "SUCCESFUL") {
$.confirm({
title: "Confirmation",
columnClass: 'col-md-6 col-md-offset-3',
content:"Forecast calculation still busy. Results might not be accurate. Continue?",
buttons: {
confirm: function() {
sResponse= "1";
vMsg = "Response 1";
processMessage(); // <--- added this
},
cancel: function() {
sResponse= "2";
vMsg = "Response 2";
// Moved code here, as it needs to execute when Cancel is clicked
$.alert({
title: "INFORMATION",
columnClass: 'col-md-6 col-md-offset-3',
content: "Screen will refresh. Please click on Update to try again.",
// Code that should execute when alert is closed:
onAction: function () {
document.getElementById("Smoke.Calc Status").value= "REFRESH";
msErr = "ABORT";
processMessage(); // <--- added this
}
});
},
}
});
} else { // <-- added
processMessage();
}
function processMessage() {
// Moved code in a function, as it should only execute after confirm/alert is closed
if (vMsg != "") {
$.alert({
title: 'Validation Message',
columnClass: 'col-md-6 col-md-offset-3',
content: vMsg,
});
msErr = "ERROR";
}
}
}
//#################
return msErr;
}
So I think my problem lies with msErr being returned long before the user has had chance to decide which button on the confirm dialog to choose. If I don't set breakpoints and click on the confirm's cancel then I do see that the alerts are shown, but the page is not refreshed (document.getElementById("Smoke.Calc Status").value= "REFRESH";) and the next page is shown. I think this comes from the sErr == "" in the toolbar.asp file and then the program flow just continues.
Anycase, I tried using callbacks, but the situation hasn't changed.
Here is what I tried to do:
parentMain.dovalidation(function(result){
if (result != ""){
return;
}
});
In main.asp the dovalidation function:
function dovalidation(callback) {
msErr = "";
//#################
if (msErr.length == 0) {
var vEffectiveDate="";
var vLastRunDate="";
var sStatus="";
var vMsg="";
var sResponse="";
vEffectiveDate = document.getElementById("Smoke.Effective Date").value;
vLastRunDate = document.getElementById("Smoke.Last Run Date").value;
sStatus = document.getElementById("Smoke.Calc Status").value;
vMsg = "";
if ((sStatus).length == 0 ){
sStatus = "SUCCESFUL";
document.getElementById("Smoke.Calc Status").value= sStatus;
}
if ((vEffectiveDate).length > 0 ){
if (!isDate(vEffectiveDate) ){
vMsg = vMsg+"[Effective Date] Is not a date." + ";\r\n";
} else if ( moment( toDate(vEffectiveDate)).isBefore(toDate(vLastRunDate)) ){
vMsg = vMsg+"[Effective Date] cannot be on/before "+vLastRunDate+"." + ";\r\n";
}
}
if (sStatus.toUpperCase() != "SUCCESFUL") {
$.confirm({
title: "Confirmation",
columnClass: 'col-md-6 col-md-offset-3',
content:"Forecast calculation still busy. Results might not be accurate. Continue?",
buttons: {
confirm: function() {
sResponse= 1;
vMsg = "Response 1";
processMessage(); // <--- added this
},
cancel: function() {
sResponse= 2;
vMsg = "Response 2";
// Moved code here, as it needs to execute when Cancel is clicked
$.alert({
title: "INFORMATION",
columnClass: 'col-md-6 col-md-offset-3',
content: "Screen will refresh. Please click on Update to try again.",
// Code that should execute when alert is closed:
onAction: function () {
document.getElementById("Smoke.Calc Status").value= "REFRESH";
msErr = "ABORT";
processMessage(); // <--- added this
}
});
},
}
});
} else { // <-- added
processMessage();
}
function processMessage() {
// Moved code in a function, as it should only execute after confirm/alert is closed
if (vMsg != "") {
$.alert({
title: 'Validation Message',
columnClass: 'col-md-6 col-md-offset-3',
content: vMsg,
});
msErr = "ERROR";
}
}
}
//#################
callback(msErr);
}
So, it isn't working as it should, and I don't know what I've done wrong, but I suppose I haven't used the callbacks correctly.
Does it make a difference that it is in two different files?
This has to work given that the parts between the //######### are swopped.
I would appreciate any feedback and guidance.
Well, ok. I started to write a comment, but it is too small for all I need to say, so I will continue in an answer.
I see you added some more code, but... you know, your code are blowing my mind =) what you are trying to do is to get spaghetti-code and make it async.
Throw this away and let's go to the upper level. We call it "program on an interface level".
Example: replace all your big code blocks with functions (with correct name). Like code between //################# will be converted to
function dovalidation(callback) {
msErr = getValidationResult();
callback(msErr);
}
What do I do here is just throw away all your low-level code, because your problem is in the order of execution.
But this is just the first step of converting your code to something other. Next step is realizing that our "virtual" function getValidationResult has some $.confirm and $.alert inside, so it is async. That's why we need to use getValidationResult as async. Two possible ways - convert to Promise or use callbacks. Let's use callbacks. Then our simplified code will convert to:
function dovalidation(callback) {
getValidationResult(callback);
}
That is what I was trying to show on my previous answer.
And now you've added some more code with such a comment: //Then the rest of the code which is executed irrespective of the jquery confirm.. Ok, good, we will name all this code as theRestOfTheCodeIrrespectiveToConfirm(). So your original function call will be converted from this:
//... Other code that determines variables, fringe scenarios etc.
//...
// Then dovalidation() (in which the blocking MsgBox used to be) is called:
var sErr = parentMain.dovalidation();
if (sErr != ""){
return;
}
theRestOfTheCodeIrrespectiveToConfirm();
to this:
//... Other code that determines variables, fringe scenarios etc.
//...
// Then dovalidation() (in which the blocking MsgBox used to be) is called:
parentMain.dovalidation(sErr => {
if (sErr != ""){
return;
}
theRestOfTheCodeIrrespectiveToConfirm(); // <- this will execute only if sErr is empty
});
Am I going to the right direction?
P.S. One thing to ask you - why do you have } in the end of you example code, but no correcsponding {?
Maybe you show us not all code?
There is no need to involve jQuery.
JavaScript has the functions alert, confirm and prompt which are synchronous (i.e. blocking execution until they return) just like MsgBox was.
So if this is easier to you, you can keep your original code structure this way. Because as it was explained in the "how do I return a response from an asynchronous call" article, you cannot make the dovalidation function return anything that depends on the result of an asynchronous operation like the $.confirm that you currently use, since that would require time travel ;) - but you can make it dependent on synchronous operations like JS' built-in confirm.
You are mixing sync code with async... Because $.confirm is async, but you call dovalidation as sync.
Note: your code is very strange, maybe because of small JS experience, so I will try to guess what you need. You can ask if something in my code is incorrect.
Your second example with callback is more close to working solution, but you need to call the callback only if you know the user's answer.
So let's change your code a bit. Extract processMessage function (now it is async) and call processMessage with correct parameters:
function processMessage(vMsg, msErr, callback) {
// Moved code in a function, as it should only execute after confirm/alert is closed
if (vMsg) {
$.alert({
title: 'Validation Message',
columnClass: 'col-md-6 col-md-offset-3',
content: vMsg,
});
msErr = "ERROR";
}
callback(msErr); // <-- return result
}
function dovalidation(callback) {
var vMsg = "", msErr = "";
//#################
if (msErr.length == 0) {
var vEffectiveDate = "";
var vLastRunDate = "";
var sStatus = "";
var sResponse = "";
vEffectiveDate = document.getElementById("Smoke.Effective Date").value;
vLastRunDate = document.getElementById("Smoke.Last Run Date").value;
sStatus = document.getElementById("Smoke.Calc Status").value;
vMsg = "";
if ((sStatus).length == 0) {
sStatus = "SUCCESFUL";
document.getElementById("Smoke.Calc Status").value = sStatus;
}
if ((vEffectiveDate).length > 0) {
if (!isDate(vEffectiveDate)) {
vMsg = vMsg + "[Effective Date] Is not a date." + ";\r\n";
} else if (moment(toDate(vEffectiveDate)).isBefore(toDate(vLastRunDate))) {
vMsg = vMsg + "[Effective Date] cannot be on/before " + vLastRunDate + "." + ";\r\n";
}
}
if (sStatus.toUpperCase() != "SUCCESFUL") {
$.confirm({
title: "Confirmation",
columnClass: 'col-md-6 col-md-offset-3',
content: "Forecast calculation still busy. Results might not be accurate. Continue?",
buttons: {
confirm: function() {
sResponse = 1;
vMsg = "Response 1";
processMessage(vMsg, msErr, callback); // <--- added this
},
cancel: function() {
sResponse = 2;
vMsg = "Response 2";
// Moved code here, as it needs to execute when Cancel is clicked
$.alert({
title: "INFORMATION",
columnClass: 'col-md-6 col-md-offset-3',
content: "Screen will refresh. Please click on Update to try again.",
// Code that should execute when alert is closed:
onAction: function() {
document.getElementById("Smoke.Calc Status").value = "REFRESH";
msErr = "ABORT";
processMessage(vMsg, msErr, callback); // <--- added this
}
});
},
}
});
} else { // <-- added
processMessage(vMsg, msErr, callback); // <--- added this
}
}
//#################
}
Note: this code is not "clean". If this function dovalidation you showed us has full code, then you can clean the code. This code is runnable (better use it in fullscreen), but I still do not understand what you are trying to do...
const isDate = (x) => true; // Mock
const toDate = (x) => x; // Mock
function processMessage(mType, vMsg, msErr, callback, sResponse) {
if (vMsg) {
$.alert({
title: 'Validation Message',
columnClass: 'col-md-6 col-md-offset-3',
content: vMsg,
});
msErr = "ERROR"; // ???
}
callback(mType, msErr, vMsg, sResponse); // <-- return result
}
function dovalidation(callback) {
var sResponse = "";
let vMsg = '';
let msErr = '';
let vEffectiveDate = document.getElementById("Smoke.Effective Date").value;
let vLastRunDate = document.getElementById("Smoke.Last Run Date").value;
let sStatus = document.getElementById("Smoke.Calc Status").value;
if (!sStatus) {
sStatus = "SUCCESFUL";
document.getElementById("Smoke.Calc Status").value = sStatus;
}
if (vEffectiveDate) {
if (!isDate(vEffectiveDate)) {
vMsg = vMsg + "[Effective Date] Is not a date.;\r\n";
} else if (moment(toDate(vEffectiveDate)).isBefore(toDate(vLastRunDate))) {
vMsg = vMsg + "[Effective Date] cannot be on/before " + vLastRunDate + ".;\r\n";
}
}
if (sStatus.toUpperCase() != "SUCCESFUL") {
$.confirm({
title: "Confirmation",
columnClass: 'col-md-6 col-md-offset-3',
content: "Forecast calculation still busy. Results might not be accurate. Continue?",
buttons: {
confirm: () => {
sResponse = 1;
vMsg = "Response 1";
processMessage('Confirm', vMsg, msErr, callback, sResponse);
},
cancel: function() {
sResponse = 2;
vMsg = "Response 2";
$.alert({
title: "INFORMATION",
columnClass: 'col-md-6 col-md-offset-3',
content: "Screen will refresh. Please click on Update to try again.",
// Code that should execute when alert is closed:
onAction: () => {
document.getElementById("Smoke.Calc Status").value = "REFRESH";
msErr = "ABORT";
processMessage('Abort', vMsg, msErr, callback, sResponse);
}
});
},
}
});
} else {
processMessage('Success', vMsg, msErr, callback, sResponse);
}
}
function test() {
dovalidation(function(mType, msErr, vMsg, sResponse) {
console.log('[TYPE]', mType, '[RESULT]', msErr || '?', '[MESSAGE]', vMsg || '?');
//if (result != "") {
// return;
//}
});
}
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.3.2/jquery-confirm.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.3.2/jquery-confirm.min.js"></script>
<input type="text" id="Smoke.Effective Date" value="2020-01-02"/>
<input type="text" id="Smoke.Last Run Date" value="2020-01-01"/>
<input type="text" id="Smoke.Calc Status" value="WTF?"/>
<button onclick="test()">TEST</button>

How to add the value from an input box to an array and then output its contents?

How can I go about adding the value of an input box into an array and then display the contents of that array?
This is what I've come up with and I'm not sure why it's not working - the console.log doesn't post anything to the console, either.
var user = user;
if (!user) {
user = prompt('Please choose a username:');
if (!user) {
alert('Your name has been set to "Anonymous"');
} else {
alert('Your name has been set to "'+ user +'"');
}
}
var items = [];
function userArray() {
items.push(user);
return false;
console.log(items);
}
socket.on('onlineUsers', function (data) {
$('.dispUser').html(items);
});
The rest of the code in the file is below, just in case it helps... (changed the return statement, as per the first answer)
var user = user;
if (!user) {
user = prompt('Please choose a username:');
if (!user) {
alert('Your name has been set to "Anonymous"');
} else {
alert('Your name has been set to "'+ user +'"');
}
}
var items = [];
function userArray() {
items.push(users);
console.log(items);
return false;
}
socket.on('onlineUsers', function (data) {
$('.dispUser').html(items);
});
//Counts the number of users online
socket.on('count', function (data) {
$('.user-count').html(data);
});
//Receives messages and outputs it to the chat section
socket.on('message', function (data) {
$('.chat').append('<p><strong>' + data.user + '</strong>: ' + data.message + '</p>');
$('.chat').scrollTop($('.chat').height());
});
//SENDING OF THE MESSAGE
//Submit the form through HTTPS
$('form').submit(function (e) {
e.preventDefault();
// Retrieve the message from the user
var message = $(e.target).find('input').val();
// Send the message to the server
socket.emit('message', {
user: user || 'Anonymous',
message: message
});
// Clears the message box after the message has been sent
e.target.reset();
$(e.target).find('input').focus();
});
Answer
Your implementation is fine, but you have a bug which is preventing it from working as you've described.
The call to console.log(items) does not print anything, because that line of code never runs.
When you return from a function, the subsequent lines of code will not be ran. You should return as the last line within your function, or wrap it in a conditional.
For example:
function userArray() {
items.push(user);
console.log(items);
return false;
}
How to debug
Learning the techniques to figure this issue out yourself is an invaluable tool. You can leverage a debugger, such as the Chrome Devtools, to add breakpoints to your code. These will allow you to stop execution on a particular line, view the value of variables, and step through the remaining lines of code.
Doing so would make it clearly visible that the line of code is never running.
Find more details here: https://developers.google.com/web/tools/chrome-devtools/javascript

Form click function to check variable before submitting

I am using a $.get function to check the connection to the server before submitting the ASP login form. If the get function is successful and returns a true then the form should submit, otherwise if it fails and returns false, it should not.
I have tried many different configurations, but everything I've tried has either rendered the button inoperable, or only showing a true, and never a false!
Any advice is appreciated. Thanks.
<asp:Button ID="LoginButton" runat="server" CommandName="Login" Text="Enter" ValidationGroup="LoginUserValidationGroup" class="submitButton" />
UPDATE - The code below executes the get function correctly, but I have a feeling the problem lies within $('form').submit();
When true is returned the page refreshes like it sent the data, but the system does not log the user in. Why is this!?
submitButton.click(function () { // capitalize username on login
var url = 'https://examplesite.com/';
$.get(url).done(function () {
if (usernameBox.val() === '') {
usernameBox.attr('placeholder', 'Username Required');
passwordBox.attr('placeholder', '');
usernameBox.focus();
return false;
}
else if (passwordBox.length && passwordBox.val() === '') {
passwordBox.attr('placeholder', 'Password Required');
usernameBox.attr('placeholder', '');
passwordBox.focus();
return false;
}
else if (passwordBox.length && passwordBox.val().length < 6) {
passwordBox.focus();
return false;
}
else {
alert('Successful - Now logging in');
$('form').submit();
}
}).fail(function () {
alert('Failed - No Connection');
});
return false;
});
};
$.get is an async function, so online is never set to what you think it is since the rest of the code is being processed before the call is complete. Move your logic into the .done part of it!
$.get(url).done(function () {
online = true;
if (online == true) {
alert('Success');
$('form').submit();
}
else if (online == false) {
alert('Cannot Connect');
return false;
}
else {
return false;
}
}).fail(function () {
online = false;
});

$.ajax success callback not firing in firefox

I'm having an issue where my call to $.ajax is completing successfully and returning content with a response of 200OK as reported by firebug, but the success,complete and error callbacks do not execute. This is only happening in firefox, in chrome it works fine (i am running firefox22).
$.ajax(site_url+url+'/fetch_salt',{type:'POST',data:data,success:check_salt});
var group = '';
function check_salt(d)
{
console.log(d);
The actual response for the request as reported by firebug is:
choose_login:{"admin":"Admin Zone"}
And response type:
Content-Type text/html
I have tried forcing settings like dataType and contentType in case jquery is assuming json or something and I have tried anonymous functions for the error, success and complete callbacks, but nothing works.
Am posting full function code, just in case its some kind of syntax error quirk:
function prep_login_form(elem,url,challenge)
{
function show_error(msg)
{
$(elem).find('.ecms-error-for-password .ecms-error-text').html(msg).closest('.ecms-error-container').removeClass('ecms-error-hidden');
}
function submit()
{
var data = {email:$(elem).find('input[name="email"]').val()};
data[csfr_token_name] = csfr_hash;
$.ajax({type:'POST',url:site_url+url+'/attempt_login',data:data,success:check_salt});
var group = '';
function check_salt(d)
{
console.log(d);
if (d=='no_email')
{
show_error('Invalid Email address');
}
else if (d=='account_disabled')
{
show_error('This account has been disabled, please contact your administrator');
}
else if (d.substr(0,12)=='choose_login')
{
var cl;
eval('cl = '+d.substr(13));
var cou = 0;
for (p in cl)
{
cou++;
}
if (cou==1)
{
group = p;
var mydata = $.extend(data,{group:p});
$.ajax(site_url+url+'/fetch_salt',{type:'POST',data:mydata,success:check_salt})
}
else
{
var str = '<div class="login-selection-popup"><p>We have detected that your email address is linked to more than one account.<br />Please select which zone you would like to login to.</p><ul class="choose-login-popup">';
for (p in cl)
{
str+='<li><a rel="'+p+'">'+cl[p]+'</a></li>';
}
str+='</ul></div>';
open_modal({heading:'Choose Account',content:str,buttons:function(close_modal)
{
$(this).find('.choose-login-popup').on('click','a',function()
{
group = $(this).attr('rel');
var mydata = $.extend(data,{group:$(this).attr('rel')});
$.ajax(site_url+url+'/fetch_salt',{type:'POST',data:mydata,success:check_salt})
close_modal();
});
}});
}
}
else
{
var salt = d;
var pw = $(elem).find('input[name="password"]').val();
data.password = hex_md5(challenge+hex_md5(salt+pw));
data.group = group;
$.ajax(site_url+url+'/attempt_login',{type:'POST',data:data,success:function(d)
{
if (d=='no_email')
{
show_error('Invalid username or password');//Invalid Email address
}
else if (d=='account_disabled')
{
show_error('This account has been disabled, please contact your administrator');
}
else if (d=='invalid_login')
{
show_error('Invalid username or password');//Email or Password did not match
}
else
{
window.location.href = d;
}
}});
}
}
}
$(elem).on('keyup','input',function(e)
{
if (e.keyCode=='13')
{
submit();
}
});
$(elem).find('.login-submit').on('click',function()
{
submit();
});
}
Sorry for all the trouble guys I recently had addware on my PC and battled to get rid of it. I think that it had damaged/hijacked my firefox. After re-installing firefox the problem has gone away, the callbacks now execute.

Check if a user Is fan of a Facebook page

After logged in I am trying to return if the user is either not a fan of a Facebook page, but the result is always "undefined". But if I replace "return" to "alert" works perfectly.
function pageFan()
{
FB.api({ method: 'pages.isFan', page_id: '175625039138809' }, function(response) {
showAlert(response);
});
}
function showAlert(response)
{
if (response == true) {
return 'like the Application.';
} else {
return "doesn't like the Application.";
}
}
var like = pageFan();
document.getElementById('debug').innerHTML = like; //return undefined
This question has already been answered.
Relevant Javascript:
$(document).ready(function(){
FB.login(function(response) {
if (response.session) {
var user_id = response.session.uid;
var page_id = "40796308305"; //coca cola
var fql_query = "SELECT uid FROM page_fan WHERE page_id = "+page_id+"and uid="+user_id;
var the_query = FB.Data.query(fql_query);
the_query.wait(function(rows) {
if (rows.length == 1 && rows[0].uid == user_id) {
$("#container_like").show();
//here you could also do some ajax and get the content for a "liker" instead of simply showing a hidden div in the page.
} else {
$("#container_notlike").show();
//and here you could get the content for a non liker in ajax...
}
});
} else {
// user is not logged in
}
});
That's because the return in showAlert is not returning "into" the pageFan function. The showAlert function is passed as a callback, meaning it will be called later, outside of pageFan's execution. I think you need to read more about callback functions and asynchronous programming.
function showAlert(response)
{
if (response == true) {
document.getElementById('debug').innerHTML = 'like the Application.';
} else {
document.getElementById('debug').innerHTML = "doesn't like the Application.";
}
}

Categories

Resources