how to post content using javascript in linkedin - javascript

I have to login and post content in linkedin using javascript.
Using below code i have login successfully and when i have posted i got below error in firebug .
NetworkError: 403 Forbidden - https://api.linkedin.com/v1/people/~/mailbox
I need to post content in wall.
what is the issue in below code
<script type="text/javascript" src="http://platform.linkedin.com/in.js">
api_key: xxxxxxx
onLoad: onLinkedInAuth
scope: r_network w_messages
authorize: true
</script>
<script type="text/javascript">
function onLinkedInLoad() {
IN.Event.on(IN, "auth", onLinkedInAuth);
}
function onLinkedInAuth() {
var div = document.getElementById("sendMessageForm");
div.innerHTML = '<h2>Send a Message To Yourself</h2>';
div.innerHTML += '<form action="javascript:SendMessage();">' +
'<input id="message" size="30" value="You are awesome!" type="text">' +
'<input type="submit" value="Send Message!" /></form>';
}
function SendMessage(keywords) {
var message = document.getElementById('message').value;
var BODY = {
"recipients": {
"values": [{
"person": {
"_path": "/people/~",
}
}]
},
"subject": "JSON POST from JSAPI",
"body": message
}
IN.API.Raw("/people/~/mailbox")
.method("POST")
.body(JSON.stringify(BODY))
.result(displayMessageSent)
.error(function error(e) { alert ("No dice") });
}
function displayMessageSent() {
var div = document.getElementById("sendMessageResult");
div.innerHTML += "Yay!";
}
</script>
</head>
<body>
<script type="IN/Login"></script>
<div id="sendMessageForm"></div>
<div id="sendMessageResult"></div>

Using below javascript code I posted linkedin
IN.API.Raw("/people/~/current-status") // Update (PUT) the status
.method("PUT")
.body(JSON.stringify("Test Message"))
.result( function(result) { document.getElementById("statusDiv").innerHTML = "Status updated"; } )
.error( function(error) { /* do nothing */ } );

Related

AWS API gateway unreacheable from S3 webpage

I am trying to add a form contact to a AWS S3 static web page with API Gateway, Lambda and SES
I checked and followed many guides, so far the API gateway and Lambda together can send email properly. I even tested successfully with postman APP in my home computer.
I guess the form webpage script does not called or it is bad created, please help on check it. The form does not received fail response only reset itself.
This is AWS lambda function
var AWS = require('aws-sdk');
var ses = new AWS.SES();
var RECEIVER = 'xxxxx#gmail.com';
var SENDER = 'xxxxx#gmail.com';
var response = {
"isBase64Encoded": false,
"headers": { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*'},
"statusCode": 200,
"body": "{\"result\": \"Success.\"}"
};
exports.handler = function (event, context) {
console.log('Received event:', event);
sendEmail(event, function (err, data) {
context.done(err, null);
});
};
function sendEmail (event, done) {
var params = {
Destination: {
ToAddresses: [
RECEIVER
]
},
Message: {
Body: {
Text: {
Data: 'name: ' + event.name + '\nphone: ' + event.phone + '\nemail: ' + event.email + '\ndesc: ' + event.desc,
Charset: 'UTF-8'
}
},
Subject: {
Data: 'Website Referral Form: ' + event.name,
Charset: 'UTF-8'
}
},
Source: SENDER
};
ses.sendEmail(params, done);
}
the form webpage that it called AWS function is
<html>
<head>
</head>
<body>
<form id="contact-form" method="post">
<h4>Name:</h4>
<input type="text" style="height:35px;" id="name-input" placeholder="Enter name here" class="form-control" style="width:100%;" /><br/>
<h4>Phone:</h4>
<input type="phone" style="height:35px;" id="phone-input" placeholder="Enter phone number" class="form-control" style="width:100%;"/><br/>
<h4>Email:</h4>
<input type="email" style="height:35px;" id="email-input" placeholder="Enter email here..." class="form-control" style="width:100%;"/><br/>
<h4>How can we help you?</h4>
<textarea id="description-input" rows="3" placeholder="Enter your message..." class="form-control" style="width:100%;"></textarea><br/>
<div class="g-recaptcha" data-sitekey="6Lc7cVMUAAAAAM1yxf64wrmO8gvi8A1oQ_ead1ys" class="form-control" style="width:100%;"></div>
<button type="button" onClick="submitToAPI(event)" class="btn btn-lg" style="margin-top:20px;">Submit</button>
</form>
</body>
<script>
function submitToAPI(e) {
e.preventDefault();
var URL = "https://"awsdata".amazonaws.com/probado/sndemail";
var name = document.getElementById("name-input").value;
var phone = document.getElementById("phone-input").value;
var email = document.getElementById("email-input").value;
var desc = document.getElementById("description-input").value;
if (name=="" || phone=="" || email=="" || desc=="")
{
alert("Please Fill All Required Field");
return false;
}
nameRE = /^[A-Z]{1}[a-z]{2,20}[ ]{1}[A-Z]{1}[a-z]{2,20}/;
if(!nameRE.test(name)) {
alert("Name entered, is not valid");
return false;
}
phoneRE = /^([0|\+[0-9]{1,5})?([7-9][0-9]{9})$/;
if(!phoneRE.test(phone)) {
alert("Phone number entered, is not valid");
return false;
}
emailRE = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(!emailRE.test(email)) {
alert("Email Address entered, is not valid");
return false;
}
var data = {
name : name,
phone : phone,
email : email,
desc : desc
};
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "<URL for API gateway>");
xmlhttp.setRequestHeader("Content-Type", "application/json");
xmlhttp.send(JSON.stringify(data));
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4) {
var response = JSON.parse(xmlhttp.responseText);
if (xmlhttp.status === 200 ) {
console.log('successful');
document.getElementById("contact-form").innerHTML = "<h1>Thank you for your message/feedback<br>our team will get back to you soon!</h1>";
} else {
console.log('failed');
}
}
}
document.getElementById('contact-form').reset();
}
</script>
</html>
API Gateway CORS
The form has to be inside the body and put the script inside the head...
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</script>
<script> your own script like the one above... </script>
</head>
<body>
<form> user form... </form>
</html>

Not able to send html form data in googlesheet without using script editor and google forms

Here index.html file made for account authentication containing signin and signout button.
Next, sendform.html is the actual page having some fields which needs to be stored when clicked on submit button but when I run this, the data is not sent to googlesheet. I don't want to use google forms and app-script just normal html form and javascript only. Please help!!
index.html
<head></head>
<body>
<script>
function initClient() {
var API_KEY = '<API KEY>';
var CLIENT_ID = '<CLIENTID>';
var SCOPE = 'https://www.googleapis.com/auth/spreadsheets';
gapi.client.init({
'apiKey': API_KEY,
'clientId': CLIENT_ID,
'scope': SCOPE,
'discoveryDocs': ['https://sheets.googleapis.com/$discovery/rest?version=v4'],
}).then(function () {
gapi.auth2.getAuthInstance().isSignedIn.listen(updateSignInStatus);
updateSignInStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
});
}
function handleClientLoad() {
gapi.load('client:auth2', initClient);
}
function updateSignInStatus(isSignedIn) {
if (isSignedIn) {
location.replace("http://localhost:8080/sendform.html");
}
else
alert("Error in Redirecting");
}
function handleSignInClick(event) {
gapi.auth2.getAuthInstance().signIn();
}
function handleSignOutClick(event) {
gapi.auth2.getAuthInstance().signOut();
}
</script>
<script async defer src="https://apis.google.com/js/api.js" onload="this.onload=function(){};handleClientLoad()"
onreadystatechange="if (this.readyState === 'complete') this.onload()">
</script>
<button id="signin-button" onclick="handleSignInClick()">Sign in</button>
<button id="signout-button" onclick="handleSignOutClick()">Sign out</button>
</body>
</html>
sendform.html
<html>
<head>
<title>Bulk Me</title>
</head>
<script>
function makeApiCall() {
var params = {
spreadsheetId: '<SheetID>',
range: 'Sheet1',
valueInputOption: 'RAW',
insertDataOption: 'INSERT_ROWS',
};
var myFormData = [];
var fname = document.getElementById("frml").elements[0].value;
myFormData.push(fname);
var lname = document.getElementById("frml").elements[1].value;
myFormData.push(lname);
var mobile = document.getElementById("frml").elements[2].value;
myFormData.push(mobile);
var valueRangeBody = {
"majorDimension": "ROWS",
"values": myFormData
};
var request = gapi.client.sheets.spreadsheets.values.append(params, valueRangeBody);;
request.then(function (response) {
console.log(response.result);
}, function (reason) {
console.error('error: ' + reason.result.error.message);
});
}
</script>
<body>
<form id=frml>
First Name:<br> <input type="text" id="fname"><br>
Last Name:<br> <input type="text" id="lname"><br>
Mobile:<br> <input type="number" id="mobile"><br>
<input type="submit" value="Submit" onclick="makeApiCall()">
</form>
</body>
</html>

How to send params form web page to parse cloud function?

I make a web form to add some string to database and now my add function is running perfectly but my web does not send params to function when i click submit and console log send undefined to me i dont know what to do please help and thank you
Here my function code and run perfectly
Parse.Cloud.define('addSynonym', function (request, response) {
var SYN = Parse.Object.extend("Synonym");
var CommonwordFromUser = request.params.common_word;
var SynonymwordFromUser = request.params.synonym_word;
console.log(CommonwordFromUser);
console.log(SynonymwordFromUser);
if (CommonwordFromUser == null || SynonymwordFromUser == null) {
response.error("request null values");
} else {
var query = new Parse.Query(SYN)
query.find({
success: function (synResponse) {
var synOBJ = new SYN();
synOBJ.set("common_word", CommonwordFromUser);
synOBJ.set("synonym_word", SynonymwordFromUser);
synOBJ.save(null, {
success: function (success) {
response.success({
"common_word": CommonwordFromUser,
"synonym_word": SynonymwordFromUser
});
},
error: function (error) {
response.error("save failed : " + error.code);
}
});
}
})
}
});
Here my web form my problem
<form id="contact" class="registerForm">
<div class="alert alert-success" id="alertbox">
<strong>Success!</strong> Your Synonym has uploaded.
</div>
<div class="text-center">
<img src="img/icon.png" class="text-center" alt="Responsive image" width="90" height="90">
</div>
<h3 class="text-center font-weight-normal">Welcome to synonym Menu</h3>
<label id="label-tags" for="ask-tags">Common Word :</label>
<fieldset class="form-group">
<input id="common_word" name="common_word" placeholder="Please type some word" type="text" tabindex="1" required>
</fieldset>
<label id="label-tags" for="ask-tags">Synonym Word :</label>
<fieldset class="form-group">
<input id="synonym_word" name="synonym_word" placeholder="Please type some word" type="text" tabindex="2"
required>
</fieldset>
<fieldset class="form-group">
<button name="submit" type="submit" onclick="submitfrom()" id="contact-submit">Submit</button>
</fieldset>
</form>
</div>
<!-- jQuery -->
<script src="js/jquery.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="js/bootstrap.min.js"></script>
<script src="js/standalone/selectize.min.js"></script>
<script src="js/bootstrapValidator.min.js"></script>
<script>
$('.registerForm').bootstrapValidator({
message: 'This value is not valid',
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
common_word: {
validators: {
notEmpty: {
message: 'Require !!'
}
}
},
synonym_word: {
validators: {
notEmpty: {
message: 'Require !!'
}
}
},
}
}).on('success.form.bv', function (e) {
submitfrom();
});
$('#alertbox').hide();
function submitfrom() {
var common_word = $('#common_word').val();
var synonym_word = $('#synonym_word').val();
var obj = [{
"common_word": common_word,
"synonym_word": synonym_word,
}];
var data = '{"objects":' + JSON.stringify(obj) + '}';
callParseServerCloudCode("addSynonym", data, function (response) {
if (response) {
console.log(response);
alert("🤖:Ok !");
location.reload();
}
});
$(this).scrollTop(0);
$('.registerForm').data('bootstrapValidator').resetForm();
$('#alertbox').show();
$('#alertbox').fadeTo(2000, 500).slideUp(500, function () {
$('#alertbox').hide();
});
}
function callParseServerCloudCode(methodName, requestMsg, responseMsg) {
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://xxxxxxxxxxxx.herokuapp.com/parse/functions/' + methodName, true);
xhr.setRequestHeader('Content-type', 'application/json');
xhr.setRequestHeader('X-Parse-Application-Id', 'myAppId');
xhr.setRequestHeader('X-Parse-Master-Key', 'myMasterKey');
xhr.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
responseMsg(myArr.result);
}
};
xhr.send(requestMsg);
}
</script>
</body>
</html>
Option 1:
Just change the lines below and it should work
var obj = {
"common_word": common_word,
"synonym_word": synonym_word,
};
var data = JSON.stringify(obj);
Option 2 (recommended):
Install Parse JS SDK: https://docs.parseplatform.org/js/guide/#getting-started
Call cloud code like this:
Parse.Cloud.run(
"addSynonym",
{
"common_word": common_word,
"synonym_word": synonym_word
}
).then(
function() {
console.log('success');
},
function (error) {
console.error(error);
}
);

Google Calendar API - Request URL 404 Not Found

I am trying to get events from my calendar by using the Google API:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="googleCalendar.js"></script>
<script src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script>
</head>
<body>
<div id="calendarContainer">
<div>
<button type="button" id="authorize-button"><?= _("Google Calendar Events"); ?></button>
</div>
<div id="content">
<h2><?= _("Events"); ?></h2><br>
<ul id="events"></ul>
</div>
</div>
</body>
</html>
googleCalendar.js:
$(document).ready(function() {
var clientId = '{my_client_id}';
var apiKey = '{my_api_key}';
var scopes = 'https://www.googleapis.com/auth/calendar';
$("#authorize-button").click(function(){
handleClientLoad();
});
function handleClientLoad()
{
gapi.client.setApiKey(apiKey);
window.setTimeout(checkAuth,1);
checkAuth();
}
function checkAuth()
{
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: true},
handleAuthResult);
}
function handleAuthResult(authResult)
{
var authorizeButton = document.getElementById('authorize-button');
if (authResult) {
//authorizeButton.style.visibility = 'hidden';
makeApiCall();
} else {
authorizeButton.style.visibility = '';
authorizeButton.onclick = handleAuthClick;
}
}
function handleAuthClick(event)
{
gapi.auth.authorize(
{client_id: clientId, scope: scopes, immediate: false},
handleAuthResult
);
return false;
}
function makeApiCall()
{
gapi.client.load('calendar', 'v3', function() {
var request = gapi.client.calendar.events.list({
'calendarId': 'primary'
});
request.execute(function(resp) {
console.log(resp);
for (var i = 0; i < resp.items.length; i++) {
var li = document.createElement('li');
li.appendChild(document.createTextNode(resp.items[i].summary));
document.getElementById('events').appendChild(li);
}
});
});
}
});
When I click the button in order to get my events I get nothing. Then I inspect my page and I get this:
Request URL:
https://content.googleapis.com/calendar/v3/calendars/primary/events?key={my_api_key}
Status Code: 404 Not found
Pasting that URL in my browser I get this:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "notFound",
"message": "Not Found"
}
],
"code": 404,
"message": "Not Found"
}
}
Why do I get a 404 not found and I don't get the list of events from my calendar?

Buttons not rendering when I try to connect to Dropbox using the Javascript API

I want to connect to Dropbox using Javascript. This is part of a lab that I'm doing.
I have the code below, and I have checked it for syntax errors and haven't found any. However, it doesn't display the buttons I expected.
Here is a JSFiddle demonstrating the code as it is now: https://jsfiddle.net/gv19a3mw/15/
And here is a Fiddle showing the layout I expected (with no Javascript executing): https://jsfiddle.net/gv19a3mw/12/
Can anyone advise me why the buttons are not displaying when my Javascript is executing?
<html>
<head>
<script src="js/jquery-1.11.1.min.js"></script>
<script src="https://www.dropbox.com/static/api/dropbox-datastores-1.2-latest.js">
</script>
<script type="text/javascript">
$(document).ready(function() {
$('#w_area').hide();
$('#r_area').hide();
// Create a dropbox client
var client = new Dropbox.client({key: "pbio1kig5q73lli"});
// Authenticate the client
client.authenticate({interactive: false}, function(error, client) {
if (error) {
alert("Authentication error: " + error);
}
});
// Show w_area if login ok
// alert(client.isAuthenticated());
if (client.isAuthenticated()) {
$('#w_area').show();
};
// Write to myfile.txt in Dropbox
$('#w_button').click(function() {
client.authenticate({interactive: true}, function(error, client) {
if (error) {
alert("Authentication error: " + error);
}
else {
client.writeFile("myfile.txt", $('textarea#w_content').val(), function(error) {
if (error) {
alert("Write error: " + error);
}
else {
alert("File written successfully!");
$('#r_area').show();
}
});
}
});
});
// Read from myfile.txt from Dropbox
$('#r_button').click(function() {
client.authenticate({interactive: true}, function(error, client) {
if (error) {
alert("Authentication error: " + error);
}
else {
client.readFile("myfile.txt", {}, function(error, data) {
if (error) {
alert("Read error: " + error);
}
else {
alert("File read successfully!");
$('textarea#r_content').val(data);
}
});
}
});
});
})
</script>
</script>
</head>
<body>
<h3>File Read/Write in Dropbox</h3>
<div id="w_area">
<textarea id="w_content" cols="50" rows="5">
</textarea>
<button id="w_button">
Write to File in Dropbox
</button>
<br /><br />
</div>
<div id="r_area">
<textarea id="r_content" cols="50" rows="5">
</textarea>
<button id="r_button">
Read from File in Dropbox
</button>
<br /><br />
</div>
</body>
</html>
Remove buttons from element div#w_area and div#r_area
$(document).ready(function() {
$('#w_area').hide();
$('#r_area').hide();
Because of this code your buttons are nor visible.

Categories