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.";
}
}
Related
I am using the functions below for showing project info in popup which is working fine.The 2nd function is used to delete only the Document files for that particular project.I want to disable this function for Users with role "Manager".
function openShowProjectModal(id) {
$.post("/get-project-info", {ID: id}, function (res) {
var project = JSON.parse(res);
$("#job-name-show").text(project.JobName);
$("#job-number-show").text(project.JobNumber);
$("#location-show").text(project.Location);
var files = "";
for (var i = 0; i < project.Docs.length; i++) {
var filename = project.Docs[i].Document;
var id = project.Docs[i].ID;
// I want to disable the Delete function or to hide this Trash icon.
files += i+1 + ". " +(''+filename+'' ) +" " + '</i> <br/>';
$("#project-files").html(files);
}
});
}
function deleteDoc(id) {
if(confirm("Are you sure to delete?")){
$.post("/remove-doc",
{
ID :id
}, function (res) {
if (res == "removed") {
window.location.href = '/projects';
} else {
console.log("not removed");
}
});
}
}
I do not know where do you store roles. Maybe something like this will work:
function deleteDoc(id) {
if(user.role === "Manager") return;
if(confirm("Are you sure to delete?")){
$.post("/remove-doc",
{
ID :id
}, function (res) {
if (res == "removed") {
window.location.href = '/projects';
} else {
console.log("not removed");
}
});
}
I perform an edit to ensure against duplicate emails by making an ajax call and supplying a callback. If a duplicate exists, I want to return false from submit event. Is there an elegant way to achieve this without setting async=false? What I tried (see emailCallback) is not working.
submit event
EDIT (included the rest of the submit handler).
$("#form-accounts").on("submit", function (e) {
e.preventDefault();
if (!$(this).get(0).checkValidity()) return false;
if (!customValidation(true, false)) return;
checkDupEmail(emailCallback);
function emailCallback(result) {
if (result) return (function () { return false } ());
}
if ($("#submit").text() == "Create Account") {
var formData = $("#form-accounts").serialize().replace("''", "'");
ajax('post', 'php/accounts.php', formData + "&action=create-account", createSuccess);
function createSuccess(result) {
if (isNaN(result)) {
showMessage(0, result);
return;
}
localStorage.setItem("account-id", result);
debugger
setUsertype($("input[name=user-type]:checked").val());
showMessage(1, "Account Created");
};
return
}
var rString = randomString(32, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');
function randomString(length, chars) {
var result = '';
for (var i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
return result;
};
var anRandom = randomString(14, rString);
$("#code").val(anRandom);
console.log("v-code=" + anRandom);
$("#submit").css({ 'display': 'none' });
$("#verify").css({ 'display': 'block' });
var subject = "Writer's Tryst Verification Code"
$("#subject").val(subject);
var msg = "This mail is intended for the person who requested verification of email ownership at Writers-Tryst (" + getWriterTrystURL() + ").\n\n" + "Double click on the code below and then copy it. Return to our website and and paste the code.\n\nYour verification code: \n\n" + anRandom;
$("#msg").val(msg);
var formData = $("#form-accounts").serialize().replace("''", "'");
ajax('post', 'php/sendmail.php', formData, successMail, "create-account error: ");
function successMail(result) {
$("#ver-email-msg").val("An email has been sent to you. Double-click the verification code then copy and paste it below.").css({ 'display': 'block' });
}
});
function checkDupEmail(callback) {
var data = {};
data.action = "validate-email";
data.email = $("#email").val();
ajax('post', 'php/accounts.php', data, emailSuccess);
function emailSuccess(result) {
if (parseInt(result) > 0) {
showMessage(0, "The email address is in use. Please supply another or login instead of creating a new account.")
callback(true);
} else callback(false);
}
}
Instead of passing a callback, why don't you just submit the form when your Ajax call completes successfully?
$("#form-accounts").on("submit", function (e) {
// Always cancel the submit initially so the form is not submitted until after the Ajax call is complete
e.preventDefault();
...
checkDupEmail(this);
...
});
function checkDupEmail(form) {
var data = {};
data.action = "validate-email";
data.email = $("#email").val();
ajax('post', 'php/accounts.php', data, function(result) {
if (parseInt(result) > 0) {
showMessage(0, "The email address is in use. Please supply another or login instead of creating a new account.")
} else {
form.submit();
}
}
}
A better approach than that would be to submit your form using Ajax. That would eliminate the need for two calls to the server.
Please help me, How to use two ajax field validation on button (if data already exist don't click on button or redirect same page) redirection stop?
This is my ajax code:
function validate()
{
return (chkunm() && chkemail());
}
function chkunm()
{
// alert ("hello");
var unm, http;
unm = document.getElementById("pupilname").value;
http= new XMLHttpRequest();
http.onreadystatechange=function(){
if (http.readyState==4 && http.status==200){
document.getElementById("s1").innerHTML=http.responseText;
}
if(http.responseText==true)
{
// alert ("Welcome");
return true;
}
else
{
// alert ("username already exists");
return false;
}
}
http.open("GET","getunm.php?unm="+unm,true);
http.send();
}
function chkemail()
{
// alert("hello");
// die();
var email, http;
email = document.getElementById("pupilpass").value;
http= new XMLHttpRequest();
http.onreadystatechange=function(){
if (http.readyState==4 && http.status==200){
document.getElementById("s2").innerHTML=http.responseText;
if(http.responseText==true)
{
// alert ("welcome");
return true;
}
else
{
//alert ("email already exists");
return false;
}
}
}
http.open("GET","getemail.php?email="+email,true);
http.send();
}
I want, if data is already exist...!! SO don't click on button .. How can possible.. Help me
Thanks
This answer might help you:
Basically you will have multiple ajax calls that bring back their check results. You will use when to wait for both before checking if you want to redirect or not.
Code:
$(document).ready(function(){
var check1, check2;
$("yourElement(s)").click(function(){
$.when(ajax1(), ajax2()) {
if(check1 || check2) {
// window.location - whatever your soul desires
}
}
}
function ajax1() {
return $.ajax({
url: "someUrl",
dataType: "json",
data: yourJsonData,
// whatever else you need,
success: function(result){
check1 = result;
}
});
}
// idem ajax 2 to get check2 value.
}
As you might have guessed, this code is not quite tested.
I hope this helps.
I am trying to develop a login process using json.
My problem is that when I make many login attempts , parameters are not overriden but concatenated.
Below is the code I'm writing.
I do not see where the problem is.
Thank you in advance .
var loginReq = Titanium.Network.createHTTPClient();
loginReq.onload = function() {
var json = this.responseText;
Titanium.API.info("step 1 done");
var response = JSON.parse(json);
if (response.status == true) {
Titanium.App.Properties.setString("key", response.key);
alert("Success");
} else {
alert("Email or password wrong");
}
};
function doConnVerif() {
if ($.email.value != '' && $.password.value != '') {
loginReq.open("POST", "URL");
loginReq.send({
'email' : $.email.value ,
'password' : $.password.value
});
} else {
alert("Enter email and password");
}
}
By your question I can't grasp the full aspect of the problem, but definitely a good idea would be only allow one login attempt at a time.
Something like:
var pendingRequest = false;
// ...
if(!pendingRequest) {
loginReq.send({
'email' : $.email.value ,
'password' : $.password.value
});
pendingRequest = true
}
// ...
loginReq.onload = function() {
pendingRequest = false
// ...
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.