I went through the yammer api's and created an simple html to post the feed into the wall.
But I have not found a clear idea to post to specific group.
I am using the following code to post on the wall.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="generator" content="HTML Tidy for Linux/x86 (vers 11 February 2007), see www.w3.org"/>
<title>A Yammer App</title>
<script src="https://assets.yammer.com/platform/yam.js" type="text/javascript">
</script>
<script type="text/javascript">
//<![CDATA[
yam.config({appId: "hyB2pTvrL36Y50py8EWj6A"});
//]]>
</script>
<title>A Yammer App</title>
</head>
<body>
<button onclick='post()'>Post on Yammer!</button>
<script type="text/javascript">
//<![CDATA[
function post() { yam.getLoginStatus( function(response) { if (response.authResponse) { alert(1); yam.request( { url: "https://www.yammer.com/api/v1/messages.json" , method: "POST" , data: { "body" : "HelloTest"} , success: function (msg) { alert("Post was Successful!: " + msg); } , error: function (msg) { alert("Post was Unsuccessful..." + msg); } } ); } else { alert(2); yam.login( function (response) { if (!response.authResponse) { yam.request( { url: "https://www.yammer.com/api/v1/messages.json" , method: "POST" , data: { "body" : "HelloTest"} , success: function (msg) { alert("Post was Successful!: " + msg); } , error: function (msg) { alert("Post was Unsuccessful..." + msg); } } ); } }); } }); }
//]]>
</script>
<script src="https://assets.yammer.com/platform/yam.js" type="text/javascript">
</script>
<script type="text/javascript">
//<![CDATA[
yam.config({appId: "hyB2pTvrL36Y50py8EWj6A"});
//]]>
</script>
<button onclick='post()'>Post on Yammer!</button>
<script type='' "text/javascript">
function post() { yam.getLoginStatus( function(response) { if (response.authResponse) { alert(1); yam.request( { url: "https://www.yammer.com/api/v1/messages.json" , method: "POST" , data: { "body" : "HelloTest"} , success: function (msg) { alert("Post was Successful!: " + msg); } , error: function (msg) { alert("Post was Unsuccessful..." + msg); } } ); } else { alert(2); yam.login( function (response) { if (!response.authResponse) { yam.request( { url: "https://www.yammer.com/api/v1/messages.json" , method: "POST" , data: { "body" : "HelloTest"} , success: function (msg) { alert("Post was Successful!: " + msg); } , error: function (msg) { alert("Post was Unsuccessful..." + msg); } } ); } }); } }); }
</script>
</body>
</html>
Can anyone guide me on this ?
I have changed the application id with the group application id as well.however it's just getting posted in the same wall with from as embed-widget.
you will have to include the group id in the API request to post the message .. here is an example in c#
StringBuilder data = new StringBuilder();
data.Append("body=" + System.Web.HttpUtility.UrlEncode(reply));
// the below line has the group Id encoded into the URL
data.Append("&group_id=" + System.Web.HttpUtility.UrlEncode(groupId));
//Create byte array of the data that is to be sent
byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());
//Set the content length in the request header
request.ContentLength = byteData.Length;
//write data
using (Stream postStream = request.GetRequestStream())
{
postStream.Write(byteData, 0, byteData.Length);
}
JObject jsonObj = null;
//Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
//get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
jsonObj = JObject.Parse(reader.ReadToEnd());
//Console.WriteLine("Message posted successfully!!");
return jsonObj["messages"][0]["id"].ToString();
}
}
This will post message to the particular group.
You should pass the group ID.
<script>
yam.config({appId: "Your App ID"}); //Your APP ID
</script>
<button style="width:150px" onclick='post()'>Post</button>
<script>
function post() {
yam.getLoginStatus( function(response) {
if (response.authResponse) {
yam.request(
{ url: "https://www.yammer.com/api/v1/messages.json"
, method: "POST"
, data: { "body" : "Posted to the group", "group_id":"UR GROUP ID"} // Pass ur Group ID here
}
);
} else {
yam.login( function (response) {
if (!response.authResponse) {
yam.request(
{ url: "https://www.yammer.com/api/v1/messages.json"
, method: "POST"
, data: { "body" : "Posted to the group", "group_id":"UR GROPU ID"}
}
);
}
});
}
});
}
</script>
I wrote a small API wrapper : Yammer.SimpleAPI.
You can use directly from Nuget
Related
I'm trying to post some data using the fetch() api and I keep receiving a "400 - Bad Request" error.
I don't have any problem using the jQuery's $.ajax() method and I'm wondering what am I doing wrong:
data
let obj = {
id_user: 57,
id_category: 60,
note: 'test'
}
Using jQuery (working)
$.ajax({
url: 'http://localhost:3001/api/devices',
type: 'post',
data: obj
}).fail(function( xhr, status, errorThrown ) {
alert( "Sorry, there was a problem!" );
console.log( "Error: " + errorThrown );
console.log( "Status: " + status );
console.dir( xhr );
})
Using fetch() (not working)
fetch('http://localhost:3001/api/devices', {
method: 'post',
body: JSON.stringify(obj)
}).then(function(response){
console.log(response)
}).catch(function(error) {
console.log(error)
})
Response
Response {type: "basic", url: "http://localhost:3001/api/devices", redirected: false, status: 400, ok: falseā¦}
Am I missing something?
Here is how to use the fetch API:
namespace WebApi.Controllers
{
public class obj
{
public int id_user { get; set; }
public int id_category { get; set; }
public string note { get; set; }
}
public class devicesController : ApiController
{
public string Post([FromBody]obj value)
{
//use newtonsoft json
string json = JsonConvert.SerializeObject(value);
return json;
}
}
}
View:
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index2</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#callAjax").click(function () {
let obj = {
id_user: 57,
id_category: 60,
note: 'test'
}
//this worked for me, FYI, I USE different port than you
//$.ajax({
// url: 'http://localhost:53110/api/devices',
// type: 'post',
// data: obj
//}).done(function (data, textStatus, jqXHR) {
// alert(data);
//}).fail(function (xhr, status, errorThrown) {
// alert("Sorry, there was a problem!");
// console.log("Error: " + errorThrown);
// console.log("Status: " + status);
// console.dir(xhr);
//})
//https://davidwalsh.name/fetch - does not work in ie11
//https://stackoverflow.com/questions/11492325/post-json-fails-with-415-unsupported-media-type-spring-3-mvc
fetch('http://localhost:53110/api/devices', {
//I HAD TO add this headers because 415 unsupported media type
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: 'post',
body: JSON.stringify(obj)
}).then(function (response) {
//alert(response)
//ADDED THIS https://developers.google.com/web/updates/2015/03/introduction-to-fetch
response.json().then(function (data) {
alert(data);
});
}).catch(function (error) {
alert(error)
})
})
})
</script>
</head>
<body>
<div>
<input type="button" value="callAjax" id="callAjax" />
</div>
</body>
</html>
Controller Function Code
public function siteadmin_get_subcategory(Request $request)
{
$product_id = $request->input('product');
$sub_category=array(
'product_id'=>$product_id,
);
$return = Category_model::get_subcategory($sub_category);
//return view('siteadmin.get-subcategory',['sub_category' => $sub_category]);
return view('siteadmin.get-subcategory',['sub_category' => $sub_category]);
}
Model Function Code (which gets subcategory on product id)
public static get_subcategory($sub_category)
{
return DB::table('le_product')->where('product_id', '=', $sub_category)->get();
}
View JavaScript Code
This is my Ajax concept for Dropdown list based on parent
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#product_id').change(function(){
var product = $('#product_id').val();
if(product != 0) {
$.ajax({
type:'post',
url:"<?php echo base_url('SiteadminController/siteadmin_getsub_category')?>",
data: { id:product },
cache:false,
success: function(returndata){
$('#subcategory').html(returndata);
}
});
}
})
})
</script>
You need to call the correct URL in your AJAX:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#product_id').change(function(){
var product = $('#product_id').val();
if(product != 0) {
$.ajax({
type:'post',
url:"<?php echo action('SiteadminController#siteadmin_getsub_category')?>",
data: { id:product },
cache:false,
success: function(returndata){
$('#subcategory').html(returndata);
}
});
}
})
})
</script>
Also AJAX is expecting JSON, from what I see, you will return HTML. So you need to make a Controller action to return JSON.
get_subcategory1
public function get_subcategory1()
{
/*$product_id = $request->input('product_id');
$data=array(
'product_id'=>$product_id,
);*/
//$get_subcategory1 = Category_model::get_subcategory1();
return view('siteadmin.get-subcategory1');
}
I am using ajaxfileupload to upload file , whenever i upload the file it gives me this error . I tried alot to fix it but no luck .
TypeError: $.ajaxFileUpload is not a function
success: function (data, status)
Here is code my code .
$id =$("#id").val();
$.ajaxFileUpload
(
{
type: "POST",
url: "main_page/save_image_data",
secureuri:false,
fileElementId:'userfile'+id,
dataType: 'json',
data: { "image_id":id},
success: function (data, status)
{
if(typeof(data.error) != 'undefined')
{
if(data.error != '')
{
alert(data.error);
}else
{
alert(data.msg);
}
}
},
/*error: function (data, status, e)
{
alert(e);
}*/
}
)
return false;
There is no command $.ajaxFileUpload in the core of jQuery.
So you are probably trying to use an external library and you have not included it in your <head> .
This can be happened if you have include jquery.min.js inside your page.After remove that file problem will be solved.
add this to your file. this method is removed form upper version of jquery.
jQuery.extend({
handleError: function( s, xhr, status, e ) {
// If a local callback was specified, fire it
if ( s.error )
s.error( xhr, status, e );
// If we have some XML response text (e.g. from an AJAX call) then log it in the console
else if(xhr.responseText)
console.log(xhr.responseText);
}
});
this is my solution-----Follow the format of the official:
<script type="text/javascript">
$(document).ready(function() {
var interval;
function applyAjaxFileUpload(element) {
$(element).AjaxFileUpload({
action: "MyJsp.jsp",
onChange: function(filename) {
// Create a span element to notify the user of an upload in progress
var $span = $("<span />")
.attr("class", $(this).attr("id"))
.text("Uploading")
.insertAfter($(this));
$(this).remove();
interval = window.setInterval(function() {
var text = $span.text();
if (text.length < 13) {
$span.text(text + ".");
} else {
$span.text("Uploading");
}
}, 200);
},
onSubmit: function(filename) {
// Return false here to cancel the upload
/*var $fileInput = $("<input />")
.attr({
type: "file",
name: $(this).attr("name"),
id: $(this).attr("id")
});
$("span." + $(this).attr("id")).replaceWith($fileInput);
applyAjaxFileUpload($fileInput);
return false;*/
// Return key-value pair to be sent along with the file
return true;
},
onComplete: function(filename, response) {
window.clearInterval(interval);
var $span = $("span." + $(this).attr("id")).text(filename + " "),
$fileInput = $("<input />")
.attr({
type: "file",
name: $(this).attr("name"),
id: $(this).attr("id")
});
if (typeof(response.error) === "string") {
$span.replaceWith($fileInput);
applyAjaxFileUpload($fileInput);
alert(response.error);
return;
}
$("<a />")
.attr("href", "#")
.text("x")
.bind("click", function(e) {
$span.replaceWith($fileInput);
applyAjaxFileUpload($fileInput);
})
.appendTo($span);
}
});
}
applyAjaxFileUpload("#demo1");
});
</script>
at least ,no more this error. And the action will receive the request
What i want to do:
at page load to automatically pop up a jquery dialog fill in some data, post that to an action and close the dialog (regardless if the action succeeds or not).
in the View in which the pop up should occur i have the following:
<script type="text/javascript">
$(function () {
$('#PopUpDialog').dialog(
{
modal: true,
open: function ()
{
$(this).load('#Url.Action("Subscription", "PopUp")');
},
closeOnEscape: false
}
);
$('.ui-dialog-titlebar').hide();
$('#closeId').live('click',function () {
$('#PopUpDialog').dialog('close');
return false;
}
);
$('#SubscriptionForm').submit(function () {
$("#PopUpDialog").dialog("close");
$.ajax({
url: encodeURI('#Url.Action("Subscription", "PopUp")' ),
type: this.method,
data: $(this).serialize()
})
return fase;
}
);
});
</script>
the Subscription view has the following:
#using (Html.BeginForm( new { id = "SubscriptionForm" }))
{
#Html.ActionLink(Deals.Views.PopUp.SubscriptionResources.AlreadySubscribed, "", null, new { id = "closeId" })
<br />
<br />
#Deals.Views.PopUp.SubscriptionResources.FillEmail
#Html.TextBoxFor(m => Model.Email)
<input type="submit" id="subscribeId" value="#Deals.Views.PopUp.SubscriptionResources.IWantToSubscribe" />
<br />
}
which works fine.
The POST action is defined as follows:
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult Subscription(FormCollection formValues)
//public void Subscription(FormCollection formValues)
{
Deals.ViewModels.PopUpSubscriptionVM VM = new ViewModels.PopUpSubscriptionVM();
TryUpdateModel(VM);
if (!String.IsNullOrEmpty(VM.Email))
{
//do the update to the dbms
}
return Json(new { success = true });
}
The problem is that after posting back i get an empty screen with the success message, which i don't want!
What am i doing wrong?
You can handle the success and error callbacks:
$('#SubscriptionForm').submit(function () {
$("#PopUpDialog").dialog("close");
$.ajax({
url: encodeURI('#Url.Action("Subscription", "PopUp")' ),
type: this.method,
data: $(this).serialize(),
success: function (result) {
//Do Whatever you want to do here
},
error: function (x, e) {
//Do Whatever you want to do here
}
})
return fase;
}
To see what i am doing wrong i set up a small project (ASP.NET MVC 3) with the following ingredients:
<script type="text/javascript">
$(function () {
// Does not cache the ajax requests to the controller e.g. IE7/9 is doing that...
$.ajaxSetup({ cache: false });
var $loading = $('<img src="#Url.Content("~/images/ajax-Loader.gif")" alt="loading" class="ui-loading-icon">');
var $url = '#Url.Action("Subscription", "PopUp")';
var $title = 'Some title';
var $dialog = $('<div></div>');
$dialog.empty();
$dialog
.append($loading)
.load($url)
.dialog({
autoOpen: false
, closeOnEscape: false
, title: $title
, width: 500
, modal: true
, minHeight: 200
, show: 'fade'
, hide: 'fade'
});
$dialog.dialog("option", "buttons", {
"Cancel": function () {
$(this).dialog("close");
$(this).empty();
},
"Submit": function () {
var dlg = $(this);
$.ajax({
url: $url,
type: 'POST',
data: $("#SubscriptionForm").serialize(),
success: function (response) {
//$(target).html(response);
dlg.dialog('close');
dlg.empty();
});
}
});
$dialog.dialog('open');
})
</script>
The controllers' actions:
public ActionResult Subscription()
{
Thread.Sleep(2000); //just for testing
TestModalAjax.ViewModels.PopUpVM VM = new ViewModels.PopUpVM();
return View(VM);
}
//POST
[AcceptVerbs(HttpVerbs.Post)]
//[OutputCache(CacheProfile = "ZeroCacheProfile")]
public ActionResult Subscription(FormCollection formValues)
{
TestModalAjax.ViewModels.PopUpVM VM = new ViewModels.PopUpVM();
TryUpdateModel(VM);
return Json(new { success = true });
}
...and the according View:
#model TestModalAjax.ViewModels.PopUpVM
#{
Layout = null;
ViewBag.Title = "Subscription";
}
<h2>Subscription</h2>
#* ----- NOTICE THE FOLLOWING!!! WITHOUT THIS DATA GETS NOT POSTED BACK!!!! ---- *#
#using (Html.BeginForm("Subscription","PopUp",FormMethod.Post, new { id="SubscriptionForm"}))
{
<h1> Give me your name</h1>
#Html.TextBoxFor(M => Model.Name)
}
...so it seems everything works as expected!
I am in the process of learning how to convert MVC Ajax to jquery ajax so I can do more.
This is the old ajax, I took out the loading stuff
#Ajax.ActionLink("Update Tweets", "Index", "Home",
new AjaxOptions
{
UpdateTargetId = "TweetBox",
InsertionMode = InsertionMode.InsertBefore,
HttpMethod = "Get",
})
I need to convert this to jquery ajax. It seems to be working lets see the code
<script>
$(document).ready(function () {
$("#StartLabel").click(function (e) {
$.ajax({
type: "Get",
url: '/Home/Index',
// data: "X-Requested-With=XMLHttpRequest",
// contentType: "application/text; charset=utf-8",
dataType: "text",
async: true,
// cache: false,
success: function (data) {
$('#TweetBox').prepend(data);
alert('Load was performed.');
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
},
complete: function (resp) {
alert(resp.getAllResponseHeaders());
}
});
});
});
</script>
In the microsoft ajax it sets XML Request in the headers. Do I need to add that too? I am just paging my controller that performs a query to twitter and appends the data to the top.
I am using fiddler to see how the requests are different but the results are the same.
I also noticed if i put the text in the data: object its puts it in the header. i dont think that is right by any means.
You could define a normal anchor:
#Html.ActionLink("Update Tweets", "Index", "Home", null, new { id = "mylink" })
And then unobtrusively AJAXify it:
$(document).ready(function () {
$("#mylink").click(function (e) {
$.ajax({
type: "GET",
url: this.href,
success: function (data) {
$('#TweetBox').prepend(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
},
complete: function (resp) {
alert(resp.getAllResponseHeaders());
}
});
return false;
});
});
Notice that I return false from the click handler in order to cancel the default action. Also notice that I am using the anchor's href property instead of hardcoding it.
The 2 AJAX requests should be identical.
Here is simple example using Ajax with Jason data
// Post JSON data
[HttpPost]
public JsonResult JsonFullName(string fname, string lastname)
{
var data = "{ \"fname\" : \"" + fname + " \" , \"lastname\" : \"" + lastname + "\" }";
return Json(data, JsonRequestBehavior.AllowGet);
}
in the view add a reference to the query as following
#section Scripts{
<script src="~/Scripts/modernizr-2.6.2.js"></script>
<script src="~/Scripts/jquery-1.8.2.intellisense.js"></script>
<script src="~/Scripts/jquery-1.8.2.js"></script>
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
}
in the view add the js
note: (jsonGetfullname).on is a button
<script type="text/javascript">
$("#jsonGetfullname").on("click", function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "#(Url.Action("JsonFullName", "Home"))",
data: "{ \"fname\" : \"modey\" , \"lastname\" : \"sayed\" }",
dataType: "json",
success: function (data) {
var res = $.parseJSON(data);
$("#myform").html("<h3>Json data: <h3>" + res.fname + ", " + res.lastname)
},
error: function (xhr, err) {
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
}
})
});
</script>
you can also use (POST\GET) as following:
[HttpPost]
public string Contact(string message)
{
return "<h1>Hi,</h1>we got your message, <br />" + message + " <br />Thanks a lot";
}
in the view add the js
note: (send).on is a button
$("#send").on("click", function () {
$.post('', { message: $('#msg').val() })
.done(function (response) {
setTimeout(function () { $("#myform").html(response) }, 2000);
})
.error(function () { alert('Error') })
.success(function () { alert('OK') })
return false;
});