Uploading a file via Yammer API - javascript

I'm able to post a message but when I add either the attachment or pending_attachment, I get an error saying:
TypeError: 'stepUp' called on an object that does not implement interface HTMLInputElement.
function post() {
yam.getLoginStatus( function(response) {
if (response.authResponse) {
yam.request(
{ url: "https://api.yammer.com/api/v1/messages.json" //note: the endpoint is api.yammer...
, method: "POST"
, data: {
"body" : document.getElementById("post_body").value,
"group_id" : document.getElementById("group_id").value
,"attachment1" : document.getElementById("attachment")
}
, success: function (msg) {
alert("Post was Successful!: " + msg.messages[0].id); //id of new message
}
, error: function (msg) { alert("Post was Unsuccessful..." + msg); }
}
);
} else {
yam.login( function (response) {
//nothing
});
}
});
}

yammer's javascript SDK doesn't work with attachment. (at least no working example has been seen on the internet) To upload an attachment, you can either upload the file to your server and then use og_url to post a link to that file on your server, or cook up your own ajax form upload. here is an example:
var data = new FormData();
data.append('body', document.getElementById("post_body").value);
data.append('group_id', document.getElementById("group_id").value);
data.append('attachment1', document.getElementById("attachment"), 'filename_of_your_choice');
$.ajax({
url: "https://api.yammer.com/api/v1/messages.json",
data: data,
beforeSend: function (xhr) {
// set authorization header
xhr.setRequestHeader("Authorization", "Bearer YOUR_AUTHORIZATION_TOKEN");
},
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function (data) {
console.log("ajax post success.");
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("There was an error with the request.");
}
});
Notice that the authorization token is obtained in the response to a successful login. It is not your app ID. Also, I doubt document.getElementById("attachment") will work. You need to convert that object into an byte array blob.

It works for me:
function postAttach() {
var msg = $('#attach_body').val();
var m_data = new FormData();
m_data.append('body', msg);
m_data.append('group_id', 6194208);
m_data.append('attachment1', $('input[name=attachment1]')[0].files[0]);
yam.platform.request({
url: "messages.json",
contentType: "multipart/form-data",
data: m_data,
processData: false,
contentType: false,
type: 'POST',
dataType: 'json',
success: function (user) {
alert("The request was successful.");
},
error: function (user) {console.log(user);
alert("There was an error with the request.");
}
});
}
<div name="postYammer">
<input type="text" name="body" value="" id="attach_body" />
<input type="file" name="attachment1" id="attach_img"/>
<button onclick="postAttach()" type="button">Post</button>
</div>

//Example Nodejs in async function
// nota : you can get token from https://developer.yammer.com/docs/app-registration
const qs = require("qs");
const got = require("got");
const formData = require("form-data");
const fs = require("fs");
var json = {
is_rich_text: true,
topic1: 'tag1',
topic2: 'tag2',
body: 'body body',
group_id: 'group_id',
}
let querystring = qs.stringify(json);
var formData = new formData();
var aHeader = formData.getHeaders();
aHeader['Authorization'] = "Bearer token";
formData.append('attachment1', fs.createReadStream(path));
const response = await got.post('https://www.yammer.com/api/v1/messages.json?' + qs, {
headers: aHeader,
body: formData
});

Related

How to shorten URL with Bitly V4 API and jQuery

So I am trying to shorten an URL with the new V4 Bitly API, but I am getting an JSON error.
My code:
$(function() {
$(".createBitly").on("click", function(e) {
e.preventDefault();
var url = $(this).attr("href");
var accessToken = "xxx";
var params = {
"long_url" : encodeURIComponent(url)
};
$.ajax({
url: "https://api-ssl.bitly.com/v4/bitlinks",
cache: false,
dataType: "json",
method: "POST",
contentType: "application/json",
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Bearer " + accessToken);
},
data: params
}).done(function(data) {
console.log(data);
}).fail(function(data) {
console.error(data);
});
});
});
Results: a 422 http error;
"{"message":"UNPROCESSABLE_ENTITY","resource":"bitlinks","description":"The JSON value provided is invalid."}"
But running it with CURL does work though: How to shorten URL using PHP Bitly v4?
What am I doing wrong? Is it not possible with jQuery only?
TIA.
I had made this edit from your code above and its working well.
1) JSON.stringify before sending request (convert your request to JSON format).
2) No need for encodeURIComponent().
$(function() {
$(".createBitly").on("click", function(e) {
e.preventDefault();
var url = $(this).attr("href");
var accessToken = "token";
var params = {
"long_url" : url
};
$.ajax({
url: "https://api-ssl.bitly.com/v4/shorten",
cache: false,
dataType: "json",
method: "POST",
contentType: "application/json",
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Bearer " + accessToken);
},
data: JSON.stringify(params)
}).done(function(data) {
console.log(data);
}).fail(function(data) {
console.log(data);
});
});
});

Unexpected Token U Posting To Express [duplicate]

I've been having a problem all day sending json data via ajax to Express.
My ajax looks like this:
$('#saveClause').click(function () {
var username = document.getElementById('postUserName').innerHTML;
var clauseTitle = document.getElementById('modalTitle').innerHTML;
var clauseDescription = document.getElementById('modalDescription').innerHTML;
var clauseText = document.getElementById('modalText').innerHTML;
$.ajax({
url: "/classes/updateAssignment",
type: "post",
dataType: "json",
data: {
username: username,
title: clauseTitle,
description: clauseDescription,
text: clauseText
},
cache: false,
contentType: "application/json",
complete: function () {
console.log("complete");
},
success: function () {
console.log("success");
},
error: function () {
console.log("Process Error");
}
});
});
and my Express Classes routes looks like this:
router.post('/updateAssignment', function (req, res) {
console.log(req.body.username)
console.log(req.body.title);
console.log(req.body.description);
console.log(req.body.text);
res.type('json');
res.send({
some: JSON.stringify({
response: 'json'
})
});
});
I issued a postman post request to the url with this JSON object:
{
"username":"testing",
"title":"123",
"description":"j456",
"text":"seven"
}
and Express logged all the details in the console just fine, so it must be a problem with my ajax request as it's giving me an unexpected token u error but I don't know what's causing it. Any ideas?
Try removing the contentType: "application/json",
If you used postman with no headers, most likely this is causing the parser to fail.

Fake path Javascript Issue

When I try to retrieve the File path it's shows me the result like this: "C:\fakepath\amine.jpeg" so the upload in the server is not working as a result of that problem.
$('input[type=file]').change(function () {
var filePath=$('#file-input').val();
$.ajax({
url : "{{path('upload_file')}}",
type : 'POST',
data: {
filePath : filePath,
method: 'post',
params: {
action: "uploadFile"
}
},
success : function(data, textStatus, jqXHR) {
alert(data);
}
});
});
You are doing this all wrong.
You have to create a form object and send it via $.ajax.
And I assume you have written the correct serverside code to save the image.
var f = new FormData();
f.append('img',document.getElementById("file-input").files[0]);
var url= "{{Your URL}}";
$.ajax({
url: url,
type:"post",
data: f,
dataType:"JSON",
processData: false,
contentType: false,
success: function (data, status)
{
console.log(data);
},
error: function (data)
{
if (data.status === 422) {
console.log("upload failed");
} else {
console.log("upload success");
}
});
Your file by default upload to a temporary folder. You need to move it to an actual location to get access to it like in php:
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)
For reference, see http://www.w3schools.com/php/php_file_upload.asp

How to get data from Ajax

I have a variable called sid which handle number of seat. I want to throw sid to TryJSON.aspx method test. then I wanna do manipulate data on method test then throw back the result to this ajax. but I have an error when I just try to throw sid
var sid = jQuery(this).attr('id');
console.log(sid);
$.ajax({
url: "TryJSON.aspx/test",
type: "POST",
data: JSON.stringify({ 'noSeat': sid }),
contentType: "application/json; charset=utf-8",
success: function (response) {
var arr = JSON.parse(response.d);
console.log(arr);
},
error: function () {
alert("sorry, there was a problem!");
console.log("error");
},
complete: function () {
console.log("completed");
}
});
this is my C# code to receive noSeat
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static string test(string noSeat)
{
// return noSeat;
//JavaScriptSerializer serializer = new JavaScriptSerializer();
// return new JavaScriptSerializer().Serialize(new { noSeat = noSeat });
}
I have try return only noSeat and also with Javascript serializer. but it has an error. it says
An attempt was made to call the method 'test' using a POST request, which is not allowed.
I have been tried
return "Success !!"
but it doesn't appear on console and still same error.
what's the matter ?
var sid = jQuery(this).attr('id');
console.log(sid);
$.ajax({
url: "TryJSON.aspx/test",
type: "POST",
data: JSON.stringify({ 'noSeat': sid }),
contentType: "application/json; charset=utf-8",
dataType:'json',
success: function (response) {
var arr = JSON.parse(response.d);
console.log(arr);
},
error: function () {
alert("sorry, there was a problem!");
console.log("error");
},
complete: function () {
console.log("completed");
}
});

Post JSON data along with id in Jquery AJAX

I'm trying to post JSON data along with 2 ids through a Jquery AJAX post. But I am not able to do it.
Following is my code:
try {
var surveyID= localStorage.getItem("surveyId");
var userDetails = jQuery.parseJSON(localStorage.getItem("userdetails"));
var providerKey = userDetails["ProviderUserKey"];
var dataValue = { "str": StringJson};
var url = APP_URL+"EditSurvey?";
var param = "SurveyId="+surveyID+"&JSONData="+JSON.stringify(dataValue)+"&UserId="+providerKey;
$.ajax({
type: "POST",
contentType: "application/json",
url: url,
data: param,
async:true,
success: function (data) {
alert('sucess');
//}
},
error: function (err) {
alert("Err : " + err.error);
},
});
} catch (error) {
alert(error);
}
I get the following error when I debug this in Safari:
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
and in simulator I get the following error:
Where am I getting wrong? How do I solve this? I have to 3 parameters for post
surveyID
JSON data
userID
Edited:
The webservice is now changed and all 3 params- i.e. 2 ids and one whole json data is passed to the webservice. Still jquery ajax post is not working. See my code below:
var surveyID= localStorage.getItem("surveyId");
var userDetails = jQuery.parseJSON(localStorage.getItem("userdetails"));
var providerKey = userDetails["ProviderUserKey"];
var dataValue = {"surveyID":surveyID, "userID":providerKey, "str": StringJson};
alert(dataValue);
var url = APP_URL+"EditSurvey";
var param = dataValue;
$.ajax({
type: 'POST',
contentType: "application/json",
url: url,
data: dataValue,
success: function (data) {
alert('sucess');
//}
},
error: function (err) {
alert("Err : " + err.text);
},
});
edited to include stringJson:
var StringJson = JSON.stringify(MainJSON);
alert(StringJson);
Check if the final json which is being passed is in the exact format as expected by the server.
Try giving:
contentType: 'application/json',
Accept: 'application/json'
See if it helps.
try this one
formData = {
// all your parameters here
param1: param1,
JSONData: formToJSON(),
UserId: providerKey
}
$.ajax({
type: 'POST',
contentType: 'application/json',
url: url,
dataType: "json",
data: formData,
success: function(data) {
//success handling
},
error: function(data) {
alert("Err : " + err.error);
}
});
function formToJSON() {
return JSON.stringify({
dataValue: dataValue
});
}

Categories

Resources