Can not make the settings from the sidebar gadget get applied - javascript

OK, I am not an expert at Sidebar Gadgets, but I have this project I will have to make for school. Have tried to solve it on my own but I got really stuck.
I will have to use the Cirip API (Cirip.ro being a kind of Twitter), and for the use of the API I have to input the username. I do so by means of the Settings, but when closing the settings there is no effect.
Here is the code, but it's pretty messy. I am not a web programmer so javascript/html is new to me.
http://www.box.net/shared/7yogevhzrr
EDIT: Ok, so I have narrowed it down a little and optimized my code here but it is still not working. I have made it as simple as possible.
In the main html I have this:
<script language="javascript">
document.write(getUserName());
</script>
In the gadget.js:
var userName;
document.onreadystatechange = function DoInit() {
document.body.style.width = 251;
document.body.style.height= 351;
document.body.style.margin=2;
userName="danieliuhasz";
System.Gadget.settingsUI = "settings.html";
System.Gadget.onSettingsClosing = settingsClosed;
}
function setUserName(userNameSet){
userName = userNameSet;
}
function getUserName(){
return userName;
}
function settingsClosed()
{
var username = System.Gadget.Settings.read("username");
setUserName(username);
}
In the settings.html:
<body>
Username:<br />
<input name="userBox" type="text" maxlength="50" />
</body>
In settings.js:
document.onreadystatechange = function DoInit()
{
if(document.readyState=="complete")
{
var user = System.Gadget.Settings.read("userName");
if(user != "")
{
userBox.value = user;
}
}
}
System.Gadget.onSettingsClosing = function(event)
{
if (event.closeAction == event.Action.commit)
{
var username = userBox.value;
if(username != "")
{
System.Gadget.Settings.write("username", username);
System.Gadget.document.parentWindow.settingsClosed();
}
}
}
I really can't figure it out. The output of this is "undefined".

I don't have a RAR unpacker on this machine so I can't take a look at the file, but I can give you a little bit of advice about saving settings. If you need further help, try pasting the code into your question (see my comment above).
When working with settings, you need to catch the System.Gadget.onSettingsClosing event in your JavaScript code. In this event handler, you can either make the settings temporary, by setting properties in the gadget window, or you can make them semi-permanent, by using System.Gadget.Settings.write to store the settings. Let's say your username/password html looks like this:
<label for="username">Username: </label><input id="username" type="text"><br/>
<label for="password">Password: </label><input id="password" type="password">
Your JavaScript should look something like this:
System.Gadget.onSettingsClosing = function (event) {
// First, we need to make sure the user clicked the OK button to save
if (event.closeAction == event.Action.commit) {
// If they did, we need to store the settings
var username = document.getElementById("username").value,
password = document.getElementById("password").value;
System.Gadget.Settings.write("username", username);
System.Gadget.Settings.write("password", password);
/* Finally, we can call a function defined in the main gadget window's
JavaScript to let it know that the settings have changed */
System.Gadget.document.parentWindow.settingsHaveChanged();
}
}
In your main gadget's JavaScript, settingsHaveChanged might look something like the following function:
function settingsHaveChanged () {
var username = System.Gadget.Settings.read("username"),
password = System.Gadget.Settings.read("password");
sendAPIRequest(username, password);
}

Related

window.location.href does not work, it always returns an alert

I have been learning HTML/CSS/JS in my free time. I'm still a noobie and I have encountered this problem while practicing.
I want to create a form where you can type what are you searching for and sumbit button redriects you to google and If it's empty it shows an alert. But the redirect does not work, I always get an alert.
Can you guide me what Am I doing work ?
Sorry for my english, It isn't my native langue.
<form id="myform">
<input type="search" name="searchedValue">
<input type="submit" value="Szukaj">
</form>
<script>
$("document").ready(function() {
$("#myform").submit(function(e) {
var searchedValue = $("input[name='searchedValue']").attr("value");
if (searchedValue) {
window.location.href = "http://www.google.pl/#hl=plf&output=search&q="+searchedValue;
} else {
alert("empty string");
}
e.preventDefault();
});
});
</script>
var searchedValue = $("input[name='searchedValue']").val()
you should use val()
instead of attr(). Rest of the things are fine.
<form id="myform">
<input type="search" name="searchedValue">
<input type="submit" value="Szukaj" onclick="search(event)">
</form>
<script>
function search(event) {
// [0] gets the first textbox of current page with name.
var searchedValue = document.getElementsByName('searchedValue')[0].value;
if (searchedValue && event) {
event.preventDefault(); // cancels the event if it is cancelable
var specs = "height=auto,width=auto";
var searchUrl = "http://www.google.pl/#hl=plf&output=search&q=" + searchedValue;
window.open(searchUrl, "_blank", specs);
} else {
alert("empty string");
}
};
</script>
Useful links like window.open() and preventDefault(). I think it's better to practice with pure javascript and DOM manipulations when you are learning. Anyway, keep up the hard work. :)
Code is fine, i think your browser is blocking your redirect to
http://www.google.pl/#hl=plf&output=search&q="+searchedValue;
It may happen when you have https website and want to redirect to http.
Console will silently display error regarding insecure redirect.

Resetting/Clearing Form Upon Button Click w/ Firebase

I'm having trouble actually clearing the content of a form upon button click with Firebase. I'm able to use type="reset"on another form I have that just has one text field, however, the second form has two text fields and when I try the following:
function clearFields() {
document.getElementById(userCityEmail).value = "";
document.getElementById(cityTextField).value = "";
}
or I try this (something just using reset()):
function clearFields() {
document.getElementById(userCityEmail).reset();
document.getElementById(cityTextField).reset();
}
The page will reload but nothing is sent to the Firebase. If I don't use the above functions and leave the text within the text field, it sends the content to Firebase. Where am I going wrong? Thanks in advance!
Here's my HTML form:
<form id="myform" method="post">
<input type="email" class="contactUsEmail" id="userCityEmail" placeholder="Enter email" name="contactUsEmail">
<input type="text" class="contactUsEmail" id="cityTextField" placeholder="City" name="contactUsCity">
<button type="submit" id="citySubmitButton" onclick="submitCityClick(); clearFields(); return false;" class="btn btn-primary contactUsButton">Submit</button>
</form>
Javascript:
var userCityEmail = document.getElementById('userCityEmail');
var cityTextField = document.getElementById('cityTextField');
var citySubmitButton = document.getElementById('citySubmitButton');
function submitCityClick() {
var firebaseRef = firebase.database().ref();
var userEmail = userCityEmail.value + " " + cityTextField.value;
firebaseRef.child("potentialCities").push().set(userEmail);
}
function clearFields() {
document.getElementById(userCityEmail).value = "";
document.getElementById(cityTextField).value = "";
}
Figured out what happened now.
The problem you had was that you were calling
firebaseRef.child("potentialCities").push().set(userEmail);
This doesnt make sense. Either use just push(userEmail) or set(userEmail).
The difference between these two things is that push will create a random ID under the potentialCities tree node, and set will put user email data right under the same object. It probably will be overwritten. Push is recomended for this case.
To explain the field clearing, still have the clearfields method in the submit click method. Code beneath
function submitCityClick() {
var firebaseRef = firebase.database().ref();
var userEmail = userCityEmail.value + " " + cityTextField.value;
firebaseRef.child("potentialCities").push(userEmail);
clearFields()
}
This also expects that you have the right firebase ref, have you checked the url you are using?
Another thing you are doing wrong is that you are declaring these variables:
var userCityEmail = document.getElementById('userCityEmail');
var cityTextField = document.getElementById('cityTextField');
Then trying to get the elementById, with that variable, in clearFields:
document.getElementById(userCityEmail).value = "";
document.getElementById(cityTextField).value = "";
This doesnt work, you have to either get it by string in clearFields or just use the variable you declared:
userCityEmail.value = "";
or
document.getElementById('userCityEmail').value = "";
I would not recommend to just pull in jQuery just for that reason. It's a big library, and if you can suffice with vanilla javascript, do that!

Facebook Accountkit JAVASCRIPT Implementation

I am trying to implement the facebook accountkit using javascript. I followed the documentation on https://developers.facebook.com/docs/accountkit/web/integrating.
AccountKit login form
Enter country code (e.g. +1):
<input type="text" id="country_code" />
Enter phone number without spaces (e.g. 444555666):
<input type="text" id="phone_num"/>
<button onclick="phone_btn_onclick();">Login via SMS</button>
Enter email address
<input type="text" id="email"/>
<button onclick="email_btn_onclick();">Login via Email</button>
Below is the javascript code on my app
<script src="https://sdk.accountkit.com/en_US/sdk.js"></script>
<script>
// initialize Account Kit with CSRF protection
AccountKit_OnInteractive = function(){
AccountKit.init(
{
appId:'facebook_app_id',
state:"csrf",
version:"accountkit_version"
}
);
};
// login callback
function loginCallback(response) {
console.log(response);
if (response.status === "PARTIALLY_AUTHENTICATED") {
document.getElementById("code").value = response.code;
document.getElementById("csrf_nonce").value = response.state;
document.getElementById("my_form").submit();
}
else if (response.status === "NOT_AUTHENTICATED") {
// handle authentication failure
}
else if (response.status === "BAD_PARAMS") {
// handle bad parameters
}
}
// phone form submission handler
function phone_btn_onclick() {
var country_code = document.getElementById("country_code").value;
var ph_num = document.getElementById("phone_num").value;
AccountKit.login('PHONE',
{countryCode: country_code, phoneNumber: ph_num}, // will use default values if this is not specified
loginCallback);
}
// email form submission handler
function email_btn_onclick() {
var email_address = document.getElementById("email").value;
AccountKit.login('EMAIL', {emailAddress: email_address}, loginCallback);
}
</script>
After setting the required values for appId, state and version. I tried filling the form but I was redirecting to account kit page saying
we are sorry, something went wrong, try again
Any help in the implementation will be highly appreciated. Thanks in advance
The problem has been resolved. On account kit page on facebook developer site, I pointed the server url on web login settings to all occurrence of the domain i.e http://domain.com, http://www.domain.com including https if available. This resolved the problem. THANKS ALL.

JavaScript simple login from an array

I have very little experience with JavaScript and can't figure out how to get this to work, it may be a very small fix or it may be something major I have absolutely no clue...
I am trying to just create a really simple login for my assignment, security is not an issue as it is not required in the brief. The event of the user clicking the submit button should either grant or deny the user entry into the site. I have commented throughout the code so hopefully this will be a quick job to spot whatever is going wrong.
It possibly may be the "&" i included in the IF statement, I wasn't entirely sure if it would work in JavaScript or not. Or it may possibly be the calling of the users input, as I am not sure if I did that right either; i.e pass = password (from the form)
JavaScript:
<script>
function loadpage() {
var user = username; //assigns user input to variable
var pass = password; //^^
var storedus = ["Jordan", "Marzia", "Ryan"]; //array of acceptable usernames
var storedps = ["123", "cat", "seven"]; //array of acceptable passwords
if (user = storedus & pass = storedps) //condition must include both an acceptable username and password to >>
{
window.location.href = "home.html"; // >> proceed to next the portal page(home.html)
}
else
{
window.alert("An invalid username or password was entered."); //if the users input was not acceptable then display a popup informing them so.
}
}
</script>
HTML table and form:
<table style="position: absolute; left: 35%; top: 20%;"> <!- table to layout the form to take the users username and password to allow them to
gain entry into the site-!>
<form>
<tr><td><h2>Sign in</h2></td></tr>
<tr><td>Username*: </td><td><input type="username*" name="username" required></td></tr>
<tr><td>Password*: </td><td><input type="password*" name="password" required></td></tr>
<tr><td><input type="submit" name="signin" onclick="loadpage()"</td></tr>
</form>
</table>
Thank you in advance for your help!
You are trying to compare an array with what I'd guess to be a string. Instead, you should loop through the array and compare the values with the username and password.
var usernames = [
'Script47',
'SomeUsernname'
];
var passwords = [
'somePassword',
'password'
];
var username = 'Script47';
var password = 'somePassword'
for (var i = 0; i < usernames.length; i++) {
if (username == usernames[i] && password == passwords[i]) {
alert('Successful!');
break;
} else {
alert('Failed!')
}
}
Notice how I am using &&.
Example
JSFiddle

Need help Modifying how data is displayed via javascript and jquery

I have the code below and I need a little help in modifying the code output.
The code below is for a Codeigniter chat application where the user enters their message in the text box (#text) and the message is output, the message is saved in a MySQL database via PHP and then output to the textbox (#received).
I would like to modify the code to include the message sender and also show the messages with differentiation between the sender and recipient like google chat or Text message threads. The data output is via javascript and I am still a novice in the language.
This is the current chat thread output. Current Chat Output. For the full CodeIgniter project code, Click this link. Any help or pointers will be appreciated.
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script>
var time = 0;
var updateTime = function(cb) {
$.getJSON("index.php/chat/time", function(data) {
cb(~~data);
});
};
var sendChat = function(message, cb) {
$.getJSON("index.php/chat/insert_chat?message=" + message, function(data) {
cb();
});
}
var addDataToReceived = function(arrayOfData) {
arrayOfData.forEach(function(data) {
$("#received").val($("#received").val() + "\n" + data[0]);
});
}
var getNewChats = function() {
$.getJSON("index.php/chat/get_chats?time=" + time, function(data) {
addDataToReceived(data);
// reset scroll height
setTimeout(function() {
$('#received').scrollTop($('#received')[0].scrollHeight);
}, 0);
time = data[data.length - 1][3];
});
}
// using JQUERY's ready method to know when all dom elements are rendered
$(document).ready(function() {
// set an on click on the button
$("form").submit(function(evt) {
evt.preventDefault();
var data = $("#text").val();
$("#text").val('');
// get the time if clicked via a ajax get query
sendChat(data, function() {
alert("dane");
});
});
setInterval(function() {
getNewChats(0);
}, 1500);
});
</script>
<textarea id="received" rows="10" cols="50"></textarea>
<form>
<input id="text" type="text" name="user">
<input type="submit" value="Send">
</form>
According to the link it looks like it is impossible to differentiate messages by sender. Your application simply doesn't know who has sent a message.
So, first of all, you have to add a field in DB to store information about a sender. Most likely you'll have to implement some sort of authentication in the application. After that you'll be able to make differentiation on the client side.
On the client side you have to change the #received textbox to a div or some other block element. Doing this you'll be able to apply CSS styles to individual messages. Than you will need to change your addDataToReceived function in this way:
var addDataToReceived = function (arrayOfData) {
arrayOfData.forEach(function (data) {
var message = $('<div>');
message.html(data[0]);
if (data[2] === username) {
// data[2] is a new element, it points to an author of the message
//
// username indentificates a current user
// you'll save it to a variable after authentication somehow
message.addClass('self-message');
} else {
message.addClass('other-message');
}
$("#received").append(message);
});
}
It highly depends on a concrete realization, but all in all something like that.

Categories

Resources