Is there a way to load the first post from a facebook page into my website?
I know .load() does the trick, but not for other websites. Maybe .get() can be used somehow, but I don't know if there's a way to use just a part of the page.
You can use the Facebook API to fetch the latest post id:
FB.api(
"/{page-id}/feed",
function (response) {
if (response && !response.error) {
var latestPostId = response.data[0].id.split('_')[1];
}
}
);
Then you can embed the post dynamically like this:
// Create an element, you could use jQuery for this as well.
var embed = document.createElement('div');
embed.className = 'fb-post';
embed.setAttribute('data-href', 'https://www.facebook.com/{page_id}/posts/{post_id}/');
// Place it on the page somewhere.
document.body.appendChild(embed);
// You might have to let FB parse your page again.
FB.XFBML.parse();
Related
I am hosting xtext's orion editor using iframe in my angular application. I need to save the content written from my angular application side to a backend (Java application). Can anyone help me with what API calls or approach should I make from my angular side so that I can save the content written in the editor.
What I have already done :
1 .I tried extracting the content from the iframe from my angular side , but the data so extracted is partial as it only extracts data what is only visible through the iframe at once and not the whole content which one has to scroll to view .
2 . I tried making 'save' API calls that the xtext makes while saving, but it requires some stateId as its request body . I need to understand what is this state Id and how is it evaluated ?
I am making this call from my angular application
_this.saveEditor = function(args) {
var params = {
requiredStateId: args.stateId
}
_this.saveUrl = XTEXT_URL + '/save?resource=' + args.resourceId;
return $http({
method: 'POST',
url: _this.saveUrl,
data: params
});
};
my request body is :
{"requiredStateId":"-80000000"}
And this is the state Id i am obtaining by making a prior load api call which.returns state Id in its response.
may this snipped can help you, i dont know how you can wire this up with your stuff though
require(["orion/code_edit/built-codeEdit-amd"], function() {
require(["xtext/xtext-orion"], function(xtext) {
var editors = xtext.createEditor({
baseUrl: baseUrl,
syntaxDefinition: "xtext-resources/generated/mydsl-syntax"
}).done(function(editorViewer) {
$("#save-button").click(function() {
editorViewer.xtextServices.saveResource();
});
$("#log-button").click(function() {
console.log(editorViewer.xtextServices.editorContext.getServerState());
});
});
});
});
where i do the simple log you can query and then call save manually.
I've been trying to figure out how to reload a page and pull dynamic info from a server without users noticing the page has been reloaded. For instance, if I want to create a 'live' message board system when the board updates every time other people make a comment or post a message.
I noticed that Javascript has a boolean function .reload() that when set to false reloads the page from the cache and when set to true reloads the page from the server, but from what it looks like, the function does something similar to reloading the browser. Is there another way do what I'm trying to do?
Something like this...
function getContent()
{
return new Promise(function(resolve, reject){
var url = "http://yourendpoint.ext"
$.ajax({
url: url,
success: function(data)
{
resolve(data);
},
error: function(err)
{
reject(err);
}
});
}));
}
// Usage
getContent()
.then(function(data)
{
$('#some-element').html(data);
});
Are you sure you really want to do an reload?
What you could do is make an AJAX Request to the server and display the result, without even reloading the Page. I would recommend using jQuery for this, just out of comfort.
AJAX stands for Asynchronous JavaScript and XML. In a simple way the process could be:
User displays page, a timer is started
Every 10s (or 20s or whatever) you do an AJAX Request using JavaScript, asking the server for new data. You can set a callback function that handles the result data.
Server answers with result data, your callback function inserts the new data.
Code Example (taken from jQuery Docs):
$.ajax({
method: "POST",
url: "target.php",
// Data to be sent to the server
data: { name: "John", location: "Boston" },
// success will be called if the request was successfull
success: function( result ) {
// Loop through each Element
$.each(result.newElements, function(index, value) {
// Insert the Element to your page
$('.classOfYourList').append(value);
}
});
});
Just set the proper endpoint of your server as the target and insert whatever you want to do in the success function. The function will get an answer containing whatever you sent to it from the server. More Information in the jQuery Documentation:
You can Achive what you want using AJAX. you can use ajax with either javascript or jquery. You can load the content you want dynamically without reloading the entire page. here is a quick example.
Here is a <div> with id load where your content will be loaded.
<div id="load">Loaded Content:</div>
<button id="load_more">load more</button>
JQuery to request for the data, where getdata.php is the php file which will send data you want to display.
<script type="text/javascript">
$(document).ready(function(){
$("#load_more").click(function (){
$.post("getdata.php", {variable1:yourvariable, variable2:ifneeded},function(data){
//data is the string or obj or array echoed from getdata.php file
$('#load').append(data); //putting the data into the loaded div.
}
});
});
});
</script>`
finally getdata.php file
<?php
//fetch data from Databas eif needed. or echo ut what you want to display in the div.
echo "This is a small example of using JQuery AJAX post request with PHP.";
?>
Hope that helps!
I have a working JavaScript on a web page that gets my blog from a blog site and displays it in a sidebar on my web page. In other words I blog in one place, but also display my blog content in another place (my web page).
The script uses Cross Origin Sharing (CORS) and looks like this:
$(
function () {
$.get(
'http://www.corsproxy.com/my_name.soup.io/rss/original',
function (data) {
var items = data.getElementsByTagName('item');
var thoughts = $('#activity ul');
var count = 0;
$(items).each(function (i, e) {
count++;
if (count > 10) return;
thoughts.append('<li>'
+ e.getElementsByTagName('description')[0].textContent
+ '<small>'
+ $.timeago( new Date(e.getElementsByTagName('pubDate')[0].textContent) )
+ '</small></li>');
});
}, 'xml'
);
}
);
I want to move my blog to Google blogging and have an account URL that looks like this: http://my_name.blogspot.com/feeds/posts/default
But I think I still need to invoke CORS so that the JavaScript on the web site can cross domains to the Google site. I have tried using the Google URL directly but the script does not get the content.
How should I change the JavaScript so that my web page running the JavaScript will display the content from the Google blog?
As an aside: using the same JavaScript, I am able to display content (the title of the commit) from my Github account on my web page. In this case I do not use CORS; the following JavaScript works as expected:
$.getScript(
'/public/bin/jquery.timeago.js',
function () {
$.getScript(
'/public/bin/jquery.github-activity.js',
function () {
$("#gh-activity ul").githubActivityFor("my_name", { limit: 10 });
}
);
}
);
Why does the Github get work without using CORS?
Can I reconfigure the get for the Google blog to act in the same way as get for my Github account?
Examining the code for the githubActivityFor call, we see:
$.get('https://api.github.com/users/' + username + '/events?callback=?', function(activity) {
...
},
"jsonp");
The "jsonp" argument tells jQuery that that JSONP is being used here, and the resource should be loaded inside of <script> tag instead of fetched with Ajax. Sure enough, we we actually look at a user's activity feed from that URL template, it's a script. jQuery can therefore perform a JSONP script load in the usual way:
storing the callback function (i.e., the second argument) in a variable with a random, long name like jQuery35758395
replacing the ? in callback=? with the same value (e.g., jQuery35758395)
loading the script resource in a <script> tag
The Github resource (like any traditional JSONP server-side endpoint) is set up to use value of the callback parameter in a function call in the beginning of the script (e.g., jQuery35758395({ 'some': 'data' }). When script runs, the function call is executed, and it triggers the randomly-named callback we set up before the fetch.
Turns out Blogger supports JSONP on their server already. If you visit http://foobar.blogspot.com/feeds/posts/default?callback=foobaz you'll see the feed data wrapped inside of a function call. To take advantage of this, simply perform your $.get with a callback=? parameter:
$.get(
'http://my_name.blogspot.com/feeds/posts/default?callback=?',
function (data) {
...
},
"jsonp");
This will automatically do JSONP behind the scenes and correctly invoke your callback function with the XML string. Unfortunately, the string won't be parsed into a DOM structure for you already, but the jQuery function (a.k.a., $) can parse the data string for you:
var feedDOM = $(data).get(1);
The get call pulls the DOM structure out of the jQuery object, but you can also keep it in the jQuery object and use jQuery functions to examine it. Alternatively, you can supply the XML string as a context argument for a jQuery selector:
var authorTags = $("author", data);
I have two HTML pages that work in a parent-child relationship in this way:
The first one has a button which does two things: First it requests data from the database via an AJAX call. Second it directs the user to the next page with the requested data, which will be handled by JavaScript to populate the second page.
I can already obtain the data via an ajax call and put it in a JSON array:
$.ajax({
type: "POST",
url: get_data_from_database_url,
async:false,
data: params,
success: function(json)
{
json_send_my_data(json);
}
});
function json_send_my_data(json)
{
//pass the json object to the other page and load it
}
I assume that on the second page, a "document ready" JavaScript function can easily handle the capture of the passed JSON object with all the data. The best way to test that it works is for me to use alert("My data: " + json.my_data.first_name); within the document ready function to see if the JSON object has been properly passed.
I simply don't know a trusted true way to do this. I have read the forums and I know the basics of using window.location.url to load the second page, but passing the data is another story altogether.
session cookie may solve your problem.
On the second page you can print directly within the cookies with Server-Script tag or site document.cookie
And in the following section converting Cookies in Json again
How about?
Warning: This will only work for single-page-templates, where each pseudo-page has it's own HTML document.
You can pass data between pages by using the $.mobile.changePage() function manually instead of letting jQuery Mobile call it for your links:
$(document).delegate('.ui-page', 'pageinit', function () {
$(this).find('a').bind('click', function () {
$.mobile.changePage(this.href, {
reloadPage : true,
type : 'post',
data : { myKey : 'myVal' }
});
return false;
});
});
Here is the documentation for this: http://jquerymobile.com/demos/1.1.1/docs/api/methods.html
You can simply store your data in a variable for the next page as well. This is possible because jQuery Mobile pages exist in the same DOM since they are brought into the DOM via AJAX. Here is an answer I posted about this not too long ago: jQuery Moblie: passing parameters and dynamically load the content of a page
Disclaimer: This is terrible, but here goes:
First, you will need this function (I coded this a while back). Details here: http://refactor.blog.com/2012/07/13/porting-javas-getparametermap-functionality-to-pure-javascript/
It converts request parameters to a json representation.
function getParameterMap () {
if (window.location.href.indexOf('?') === (-1)) {
return {};
}
var qparts = window.location.href.split('?')[1].split('&'),
qmap = {};
qparts.map(function (part) {
var kvPair = part.split('='),
key = decodeURIComponent(kvPair[0]),
value = kvPair[1];
//handle params that lack a value: e.g. &delayed=
qmap[key] = (!value) ? '' : decodeURIComponent(value);
});
return qmap;
}
Next, inside your success handler function:
success: function(json) {
//please really convert the server response to a json
//I don't see you instructing jQuery to do that yet!
//handleAs: 'json'
var qstring = '?';
for(key in json) {
qstring += '&' + key + '=' + json[key];
qstring = qstring.substr(1); //removing the first redundant &
}
var urlTarget = 'abc.html';
var urlTargetWithParams = urlTarget + qstring;
//will go to abc.html?key1=value1&key2=value2&key2=value2...
window.location.href = urlTargetWithParams;
}
On the next page, call getParameterMap.
var jsonRebuilt = getParameterMap();
//use jsonRebuilt
Hope this helps (some extra statements are there to make things very obvious). (And remember, this is most likely a wrong way of doing it, as people have pointed out).
Here is my post about communicating between two html pages, it is pure javascript and it uses cookies:
Javascript communication between browser tabs/windows
you could reuse the code there to send messages from one page to another.
The code uses polling to get the data, you could set the polling time for your needs.
You have two options I think.
1) Use cookies - But they have size limitations.
2) Use HTML5 web storage.
The next most secure, reliable and feasible way is to use server side code.
In my app, I have a facebook field that can refer to a facebook user or to a facebook user fanpage.
I want to render the facebook fan page like box only if the fanpage exists in Facebook. Is there a way to do this with the Javascript SDK?
If you use jQuery and can figure out the pattern for the URL of those pages, you can use jQuery.get to check whether they exist or not. If you don't use jQuery, you can do the same thing with raw XmlHttpRequests.
For example, if the URL is "www.facebook.com/fanpage/{{username}}", you can do:
function startCheckForFanPage(username) {
$.get("www.facebook.com/fanpage/" + username, function(response) {
// if response.showsThere'sAPageThere, do X
// otherwise, do Y
}
}
if you use the Facebook JS SDK you can do this after initializing the FB object
FB.api('/the_fanpage_path', function(response) {
if(response.is_published) {
// it is a Fan Page!
}
});
If you don't want to load the FB SDK, you can do an AJAX get request to eg. http://graph.facebook.com/facebook. This works with the cross origin policy because graph.facebook.com allows different domains.
The response is in JSON so something like this would work:
function startCheckForFanPage(username) {
$.get("graph.facebook.com/" + username, function(response) {
if (response)
// otherwise, do Y
}, function() {
// Handle 404 or other failures here
})
}
EDIT: This no longer works