How to add input field to Yammer api query - javascript

I am a boiler plate programmer, so not very technical on how scripts work indepthly.
I have a yammer api for pulling user information from Yammer:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<span id="yammer-login"></span>
<script type="text/javascript" data-app-id="bdlZbJHCm1RY8pMUbuoBlQ" src="https://c64.assets-yammer.com/assets/platform_js_sdk.js"></script>
<script>
yam.getLoginStatus(
function (response) {
var result = 1625803434;
if (response.authResponse) {
console.log("logged in");
yam.platform.request({
url: "users/"+result+".json",
method: "GET",
data: { //use the data object literal to specify parameters, as documented in the REST API section of this developer site
"User_Id": result,
},
success: function (user) { //print message response information to the console
str = JSON.stringify(user, null, 4); // (Optional) beautiful indented output.
document.write(str);
},
error: function (user) {
alert("There was an error with the request.");
}
});
}
else {
alert("not logged in")
}
}
);
</script>
</body>
</html>
I have to hard code the Yammer id into it using the result variable.
I tried adding an input box then the yam.getLoginStatus fails with:
alert("There was an error with the request.");
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form id="frm1" action="#" method="post">
Yammer ID: <input type="text" name="y_id"><br><br>
<input type="submit" onclick="yam_id()" value="Submit">
</form>
<span id="yammer-login"></span>
<script type="text/javascript" data-app-id="bdlZbJHCm1RY8pMUbuoBlQ" src="https://c64.assets-yammer.com/assets/platform_js_sdk.js"></script>
<script>
yam.getLoginStatus(
function (response) {
var result = 1625803434;
frm_i=document.getElementById("frm1");
result=frm_i.elements[0].value;
// alert (result);
if (response.authResponse) {
console.log("logged in");
yam.platform.request({
url: "users/"+result+".json",
method: "GET",
data: { //use the data object literal to specify parameters, as documented in the REST API section of this developer site
"User_Id": result,
},
success: function (user) { //print message response information to the console
str = JSON.stringify(user, null, 4); // (Optional) beautiful indented output.
document.write(str);
//console.dir(user);
},
error: function (user) {
alert("There was an error with the request.");
}
});
}
else {
alert("not logged in")
}
}
);
</script>
Does anyone know how to simply add an input box for this script?

Here are two examples I prepared for you.
One is form submit, second is alert prompt. In both cases you need to pass a value into an input otherwise function will fail to run.
Put your authentication into authUser() function. Run example code to see it in action.
// Your auth function
function authUser(id) {
// Lets validate
if (id.length === 0) {
alert('Please enter your data, missing id');
return false;
}
// ur ajax/xhr request here
// Just console log so you can see the data
console.log(id);
}
// Example 1
document.getElementById('login-action2').addEventListener('click', function() {
var id = prompt("Please enter your auth credentials/id");
// then pass your id to your auth function
authUser(id);
});
// Example 2
function formSubmit() {
var id = document.getElementById('login-action1').value;
authUser(id);
// Prevent form from auto submitting
return false;
}
<button id="login-action2" type="button">Log me in</button>
<form action="form-login" onSubmit="return formSubmit();">
<fieldset>
<input id="login-action1" type="text" placeholder="enter auth credentials/id" value="" />
<input type="submit" value="Submit" />
</fieldset>
</form>

Related

Adding User to list after email validation

Tried this a few times but can not get user to add to list after validation
Instructions
PURE JAVASCRIPT
Dynamically add a user to the users list.
Highlight the email input when a user enters an invalid email address and display following message: "please enter a valid email address" in red.
Use the addUser function to submit the user's data.
If the ajax request returns an error, display the error message in red.
Display the newly added user in the users list when the request was successful.
html
<form id = "myForm">
<h2>Add a User:</h2>
<input type="text" name="username" placeholder="name">
<input type="email" name="email" placeholder="email">
<button>add user</button>
<h2>Users:</h2>
<ul id="users"></ul>
Function
// Do not modify this function. Add user service wrapper.
function addUser(username, email, callback) {
var xhr = new XMLHttpRequest();
var response;
var success = (!!Math.round(Math.random()));
if (!success){
response = JSON.stringify({
success: success,
error: "Oups, something went wrong!"
});
} else {
response = JSON.stringify({
success: success,
user: {
username: username,
email: email
}
});
}
xhr.open("POST", "/echo/json/");
xhr.onload = function () {
if (xhr.status === 200) {
callback(JSON.parse(xhr.responseText));
}
}
xhr.send("json=" + response);
};
jsfiddle http://jsfiddle.net/17e59p4w/2/
My code works as far as email validation but I don't understand how to addUser using the given function

Post custom HANDLER URL reCAPTCHA

I am trying to implement reCAPTCHA validation via Marketing Cloud - cloud page.
I have used this guide to do that: https://ampscript.xyz/how-tos/how-to-implement-google-recaptcha-on-marketing-cloud-forms/
What I want to do is to create a post request instead of use the action form property.
My Clint side script:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://www.google.com/recaptcha/api.js"></script>
</head>
<body>
<form id="form" >
<label>Email: </label>
<input type="email" name="EmailAddress">
<div
class="g-recaptcha"
data-sitekey="XXXXXXXXXXXXXXXXXXXXXX"
data-callback="grecaptchaCallback"
data-size="invisible"
></div>
<br>
<button>Send</button>
</form>
<script>
var form = document.getElementById('form');
form.addEventListener('submit', grecaptchaValidate);
function grecaptchaCallback() {
return new Promise(function (resolve, reject) {
if (grecaptcha.getResponse() !== '') {
var x=grecaptcha.getResponse();
console.log(x);
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "https://pub.s7.exacttarget.com/jnmlkgsfquv", true);
xhttp.setRequestHeader("Content-type", 'text/html',['Accept-Encoding'], ['identity'] );
xhttp.send();
http.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var response=this.responseText;
console.log(response);
response=response.split("<script>");
console.log(response);
console.log(response[0].trim());
}
}
}
grecaptcha.reset();
})
}
function grecaptchaValidate(e) {
e.preventDefault();
grecaptcha.execute();
}
</script>
</body>
</html>
</script>
</body>
</html>
And this is my server-side script:
<script runat="server">
Platform.Load("core", "1.1.1");
try {
var g_recaptcha_response = Request.GetFormField("g-recaptcha-response");
var secret = "XXXXXXXXXXXXXXXXXXXXXXXXXXX";
var payload = "secret=" + secret + "&response=" + g_recaptcha_response;
var contentType = "application/x-www-form-urlencoded";
var endpoint = "https://www.google.com/recaptcha/api/siteverify";
var req = HTTP.Post(endpoint, contentType, payload);
if (req.StatusCode == 200) {
var resp = Platform.Function.ParseJSON(String(req.Response));
if (!resp.success) throw "Wrong reCAPTCHA";
} else {
throw "reCAPTCHA API error";
}
/// DO SOMETHING
Write(Stringify(resp));
} catch (error) {
Write(Stringify({ status: "Error", message: error }));
}
</script>
The error I get when I send the request is:
{"status":"Error","message":"Wrong reCAPTCHA"}
<script>(function(a,m,i,g,o,s){o=a.createElement(g);s=a.getElementsByTagName(i)[0];o.src=m.origin+m.pathname+"/_t?eventType=CLOUDPAGESVISIT";o.width=0;o.height=0;o.style.display="none";s.appendChild(o);})(document,window.location,"body","img");</script>
<script src="https://7231513.collect.igodigital.com/collect.js"></script>
<script>
if (_etmc && typeof _etmc.push === 'function') {
_etmc.push(['setOrgId', '7231513']);
_etmc.push(['trackPageView']);
}
</script>
Another conclusion I came to- If I insert manually the value that I received from the client-side from x object (the grecaptcha.getResponse() )
The response correct:
{"success":true,"challenge_ts":"2020-07-29T09:30:03Z","hostname":"pub.s7.exacttarget.com"}
I would love to get an idea of how I create the request from the client-side to the server-side page according to post I am initiating?
Is there anything I'm missing? Or maybe I'm not working correctly?
Edit:
The problem was with the payload at server-side page, because the variable g_recaptcha_response was null.
My workaround is to catch the variable with query string variable:
%%[
set #x = RequestParameter("x")
]%%
<script runat="server">
Platform.Load("core", "1.1.1");
var x = Variable.GetValue("#x");
try {
// var g_recaptcha_response = Request.GetFormField("g-recaptcha-response");
var secret = "XXXXXXXXXXXXXXXXXXXXXXXXX";
var payload = "secret=" + secret + "&response=" + x;
var contentType = "application/x-www-form-urlencoded";
var endpoint = "https://www.google.com/recaptcha/api/siteverify";
var req = HTTP.Post(endpoint, contentType, payload);
if (req.StatusCode == 200) {
var resp = Platform.Function.ParseJSON(String(req.Response));
if (!resp.success) throw "Wrong reCAPTCHA";
} else {
throw "reCAPTCHA API error";
}
/// DO SOMETHING
Write(Stringify(resp));
} catch (error) {
Write(Stringify({ status: "Error", message: error }));
}
</script>
Because there is no way to catch URL data on SSJS I using AMPscript to catch x and pass it to payload, now I get a success response.
But I'm not sure if there have any security problem in this way.
First of all, you need to create your Cloud page using the Content Builder option. This will remove the script tags in your response.
Second, you are sending your data in the content type of text/html, try using application/x-www-form-urlencoded instead.
I believe, your Form Handler doesn't capture the g-recaptcha-response because it can't be retrieved with Request.GetFormField when you are sending text/html content type.
Please have a look at this article: https://ampscript.xyz/how-tos/perform-an-http-request/
Otherwise, use Axios for your client-side requests: https://github.com/axios/axios

Uncaught ReferenceError: Parse is not defined

I unexpectedly received the following error through the debugger when trying to execute parse.
Uncaught ReferenceError: Parse is not defined
I am pretty sure its well defined so not sure where the error derives from.
Essentially what happens here is that a long url gets converted into a short url using google url shorten and then parse grabs the shorten url and stores it.
<html>
<head>
</head>
<script type="text/javascript">
function makeShort()
{
var longUrl=document.getElementById("longurl").value;
var request = gapi.client.urlshortener.url.insert({
'resource': {
'longUrl': longUrl
}
});
request.execute(function(response)
{
if(response.id != null)
{
str ="<a href='"+response.id+"'>"+response.id+"</a>";
document.getElementById("output").innerHTML = str;
Parse.initialize("ID", "ID");
var PDFUpload = new Parse.Object("Scan");
PDFUpload.set("PDFDocument", str);
PDFUpload.save(null,
{
success: function(uploadResult) {
// Execute any logic that should take place after the object is saved.
},
error: function(uploadResult, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and description.
alert('Failed to create new object, with error code: ' + error.description);
}
});
}
else
{
alert("error: creating short url");
}
});
}
function load()
{
gapi.client.setApiKey('ID'); //get your ownn Browser API KEY
gapi.client.load('urlshortener', 'v1',function(){});
}
window.onload = load;
</script>
<script src="https://apis.google.com/js/client.js"> </script>
<body>
URL: <input type="text" id="longurl" name="url" value="yahoo.com" /> <br/>
<input type="button" value="Create Short" onclick="makeShort();" /> <br/> <br/>
<div id="output"></div>
</body>
</html>
In particular, below is the conversation happens, and where I try to store the url to parse:
if(response.id != null)
{
str ="<a href='"+response.id+"'>"+response.id+"</a>";
document.getElementById("output").innerHTML = str;
Parse.initialize("ID", "ID");
var PDFUpload = new Parse.Object("Scan");
PDFUpload.set("PDFDocument", str);
PDFUpload.save(null,
{
success: function(uploadResult) {
// Execute any logic that should take place after the object is saved.
},
error: function(uploadResult, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and description.
alert('Failed to create new object, with error code: ' + error.description);
}
});
}
Maybe you have this in another file but where is your code where you reference Parse http://www.parsecdn.com/js/parse-1.3.5.min.js ?
Maybe you are missing that and that's why you get the error.

Storing items in Parse (Javascript) [duplicate]

This question already has answers here:
Save input into Parse (Javascript)
(3 answers)
Closed 8 years ago.
I want to store two text field (userID, and address), as well as the file the user has uploaded to parse, but despite support, my attempt has been unsuccessful. I am not sure if there a typo that lies in the code, but it just doesn't seem to record in Parse.
<HTML>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script type="text/javascript" src="http://www.parsecdn.com/js/parse-1.2.15.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
// ***************************************************
// NOTE: Replace the following your own keys
// ***************************************************
Parse.initialize("id", "id");
function saveDocumentUpload(objParseFile)
{
var documentUpload = new Parse.Object("Scan");
documentUpload.set("Name", "");
documentUpload.set("DocumentName", objParseFile);
documentUpload.save(null,
{
success: function(uploadResult) {
// Execute any logic that should take place after the object is saved.
},
error: function(uploadResult, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and description.
alert('Failed to create new object, with error code: ' + error.description);
}
});
}
$('#documentFileUploadButton').bind("click", function (e) {
var fileUploadControl = $("#documentFileUpload")[0];
var file = fileUploadControl.files[0];
var name = file.name; //This does *NOT* need to be a unique name
var parseFile = new Parse.File(name, file);
var user_id = $('#user_id').val();
var address = $('#address').val();
parseFile.set('UserId', user_id);
parseFile.set('Address', address);
parseFile.save().then(
function () {
saveDocumentUpload(parseFile);
},
function (error) {
alert("error");
}
);
});
});
</script>
<body><form>
<input type="file" id="documentFileUpload">
<br/>
<input type="text" placeholder="UserID" id="user_id">
<br/>
<input type="text" placeholder="Address" id="address">
<br/>
<input type="submit" id="documentFileUploadButton" value="submit">
</form>
</body>
</HTML>
Update:
<HTML>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script type="text/javascript" src="http://www.parsecdn.com/js/parse-1.2.15.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
// ***************************************************
// NOTE: Replace the following your own keys
// ***************************************************
Parse.initialize("ID", "ID");
function saveDocumentUpload(objParseFile)
{
var documentUpload = new Parse.Object("Scan");
documentUpload.set("Name", "");
documentUpload.set("DocumentName", objParseFile);
documentUpload.save(null,
{
success: function(uploadResult) {
// Execute any logic that should take place after the object is saved.
},
error: function(uploadResult, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and description.
alert('Failed to create new object, with error code: ' + error.description);
}
});
}
$('#myForm').bind("submit", function (e) {
e.preventDefault();
var fileUploadControl = $("#documentFileUpload")[0];
var file = fileUploadControl.files[0];
var name = file.name; //This does *NOT* need to be a unique name
var parseFile = new Parse.File(name, file);
var user_id = $('#user_id').val();
var address = $('#address').val();
parseFile.set('UserId', user_id);
parseFile.set('Address', address);
parseFile.save().then(
function () {
saveDocumentUpload(parseFile);
},
function (error) {
alert("error");
}
);
});
});
</script>
<body><form id='myForm'>
<input type="file" id="documentFileUpload">
<br/>
<input type="text" placeholder="UserID" id="user_id">
<br/>
<input type="text" placeholder="Address" id="address">
<br/>
<input type="submit" value="submit">
</form>
</body>
</HTML>
First, do you have your api keys entered properly? I'm assuming you changed this out to post on here, but if not they need your keys.
Parse.initialize("id", "id");
You're posting the form back normally so your javascript isn't running.
Change your button click to the below - give your form some Id - I gave it an Id of myForm for this example.
Instead of:
$('#documentFileUploadButton').bind("click", function (e) {
//your code to run
});
try:
$('#myForm').bind("submit", function (e) {
e.preventDefault();
//your code to run
});

using WinJS.xhr to post variables to a URL

Am trying to create a login page for my windows 8 app, am using Html5 and javascript.. so have tried to use winjs.xhr to post what is in the textboxes as variables to a specific url which is a php script so this is my example of the url "http://example.com/api/username=username&password=password" am using winjs.xhr to post these variables to the url but am not getting any response even in the console.log
this is my code
<script>
function handlelogin(){
document.getElementById("box").onsubmit = function(){
if(document.getElementById("email_address").value ==""){
document.getElementById("errormessage").innerHTML= "Please Provide Your Email Address";
return false;
}else{
var email_address = document.getElementById("email_address");
var password = document.getElementById("password");
var formparams = "?username=" + email_address.value + "&password=" + password.value;
document.getElementById("errormessage").innerHTML = "";
WinJS.xhr({type: "POST",
url: "http://example.com/api/",
data: formparams,
headers: { "Content-type": "application/x-www-form-urlencoded" }
}).then(
function (success) {
console.log(success.statusText);
if(success == 1703){
WinJS.Navigation.navigate("home.html");
}
},
function (error) {
console.log(error);
}
);
}
};
}
window.onload = function () {
handlelogin();
}
</script>
<form id="box" method="post" name="loginform">
<p>Email address</p>
<div class="email_address"><input type="text" id="email_address" /></div>
<p>Password</p>
<div class="password"><input type="password" id="password" /></div>
<p><span id="errormessage"></span></p>
<div class="button"><input type="submit" id="login" value="Sign In"/></div>
<p>ForgotPassword?</p>
</form>
First - don't use a submit button. Use a input type="button". No submit required, you are simply reading the values on the page.
Second - attach the event handler for the button's click event. Doing this 'onload' for the window isn't the right place.
Third - don't use 'onsubmit' for your 'box' element. There is no form submission going on here. There shouldn't usually be a form submit in WinJS - that's for a browser posting the page to the server. You already are POSTing your data. See the updated code:
I highly recommend putting ALL javascript into separate files, as you'll get bytecode optimization that way. Inline Javascript isn't optimized for the next load. A common way you could do this is include the onload code below (where I assign onclick) in your js file like so
app.onactivated = function (args) {
..
..
..
args.setPromise(WinJS.UI.processAll().then(function () {
document.getElementById("login").onclick = handlelogin;
}));
..
..
}
};
But the answer directly for your question above is:
<script>
function handlelogin() {
if (document.getElementById("email_address").value == "") {
document.getElementById("errormessage").innerHTML = "Please Provide Your Email Address";
return false;
} else {
var email_address = document.getElementById("email_address");
var password = document.getElementById("password");
var formparams = "?username=" + email_address.value + "&password=" + password.value;
document.getElementById("errormessage").innerHTML = "";
WinJS.xhr({
type: "POST",
url: "http://example.com/api/",
data: formparams,
headers: { "Content-type": "application/x-www-form-urlencoded" }
}).then(
function (success) {
console.log(success.statusText);
if (success == 1703) {
WinJS.Navigation.navigate("home.html");
}
},
function (error) {
console.log(error);
}
);
}
}
window.onload = function() {
document.getElementById("login").onclick = handlelogin;
};
</script>
Check out some of the sessions in App Builder where they discuss JavaScript projects http://aka.ms/stackbuilder

Categories