Embed Post not showing with FB.api Call Facebook Javascript Api - javascript

I'm using Facebook Javascript SDK and FB.api. I read public pages' posts and wanted to show it on my website. So I made the call with FB.api and got the response. But while I try to show them by Facebook Embed System it just didn't show up.
Here is my code
FB.api("/" + PageId + "/posts",
{
access_token: getCookie("access_token"),
since: From,
until: To,
fields: "id,likes.summary(true).limit(0),comments.summary(true).limit(0),shares,link",
limit: LoadLimit,
date_format: "U",
},
function (res) {
$("#load_post").attr("disabled", false).attr("value", "Load Posts");
if (typeof res.error === 'undefined') {
if (res.data.length > 0) {
for (var i = 1; i <= res.data.length; i++) {
var NewData = res.data[i - 1];
var Id = NewData.id.split("_")[1];
var CreatedTime = NewData.created_time;
var Likes = NewData.likes.summary.total_count;
var Comment = NewData.comments.summary.total_count;
var Share = 0;
var Link = NewData.link;
if (typeof NewData.shares !== 'undefined') {
Share = NewData.shares.count;
}
var Data = "";
Data += "<tr>";
Data += "<td>" + i + "</td>";
Data += "<td><div id='" + Id + "' class='fb-post' data-href='" + Link + "' data-width='350'></div></td>";
Data += "<td>" + CreatedTime + "</td>";
Data += "<td>" + Likes + "</td>";
Data += "<td>" + Comment + "</td>";
Data += "<td>" + Share + "</td>";
Data += "<td></td>";
Data += "<td></td>";
Data += "<td></td>";
Data += "</tr>";
$("#data_area").append(Data);
FB.XFBML.parse(document.getElementById(Id));
}
} else {
alert("No data found.");
}
} else {
alert("Error occured.\n" + res.error.message);
}
});
Even I tried "FB.XFBML.parse" but lately checking the documentation I found that it has no effect on Embed Post.
I checked the console and found no error or something.
Please help me out.

Related

Get return true values using if else statements in jquery

I want to get true values from the if/else statement using jQuery. I apply this code but I can't get the required output. It displays both true and false values.
$.each(response, function(index, value) {
var user = (user_id == value.User_id);
if (user_roll == 'Customer' && user) {
if (user === true) {
//alert(user === true);
html += "<tr data-id='" + value.ticket_id + "'>";
html += "<td>" + value.ticket_id + "</td>";
html += "<td>" + value.User_id + "</td>";
html += "<td>" + value.User_name + "</td>";
html += "<td>" + value.Customer_name + "</td>";
html += "<td>" + value.subject + "</td>";
html += "<td>" + value.priority + "</td>";
}
}
The response is this : [The response I got][1]
[1]: https://i.stack.imgur.com/oePac.png . I want to get only User_id = 1 records
try comparing the string values together. Sometimes what happens is one of the id that you pass is read as String.
So ,
user_id.toString() == value.User_id.toString()
this is what I do in Javascript to compare id, please check how to convert into String in jquery.

Display JSON data in tablular format of predefined format

I am working on a small project's interface. Basically, an API sends the following JSON data:
{
"wallet_transactions": [
{
"total_cost": "80.000",
"expense_type__name": "Gas",
"total_quantity": "5.000",
"trans_type": "Purchased"
},
{
"total_cost": "250.000",
"expense_type__name": "Gas",
"total_quantity": "35.000",
"trans_type": "Rent"
}
]}
The data basically shows how much of GAS was given, its cost and its means (on credit or it was bought).
I tried to build a table out of it directly, but it was dimmed unfriendly since GAS was written twice.
What I tried was:
$.each(response.wallet_transactions, function(index) {
var exp_name=response.wallet_transactions[index].expense_type__name;
var quantity=response.wallet_transactions[index].total_quantity;
var price=response.wallet_transactions[index].total_cost;
var trans_type=response.wallet_transactions[index].trans_type;
rows=rows+'<tr><td>' + exp_name + '</td>';
rows=rows + '<td>' + price + '</td>';
rows=rows + '<td>' + quantity + '</td>';
rows=rows + '</tr>';
});
The output that is needed now looks like the image below:
Group the data for each name together in another object, then build the table from that.
var table_data = {};
$.each(response.wallet_transactions, function(i, trans) {
var exp_name = trans.expense_type__name;
var quantity = trans.total_quantity;
var price = trans.total_cost;
var trans_type = trans.trans_type;
if (!table_data[exp_name]) {
table_data[exp_name] = {}
}
table_data[exp_name][trans_type] = {
quantity: quantity,
cost: price
};
}
$.each(table_data, function(name, data) {
rows += "<tr><td>" + name + "</td>";
rows += "<td>" + data.Rent.cost + "</td>";
rows += "<td>" + data.Rent.quantity + "</td>";
rows += "<td>" + data.Purchased.cost + "</td>";
rows += "<td>" + data.Purchased.quantity + "</td>";
rows += "</tr>";
}
Notice that $.each passes the array element as the second argument to the callback function, so you don't have to repeat response.wallet_transactions[index] on every line.

Trying to store the response of ajax to a global variable but that value is not assigned outside the ajax code

One more thing is here that if I use the alert() at end of the ajax code the code is working fine. here whatever the ajax response comes has to be appended to the existing table.
for (var i = 1; i < rows.length; i++) {
var cells = splitCSVtoCells(rows[i], ",");
var obj = {};
for (var j = 0; j < cells.length; j++) {
obj[first_Row_Cells[j]] = cells[j];
}
jsonArray.push(obj);
}
console.log(jsonArray);for (var i = 0; i < jsonArray.length-1; i++) {
html += "<tr id=\"rowitem" + i + "\"><td id=\"rownum"+i+ "\" style=\"display:none;\">" + i + "</td><td> " + jsonArray[i].Clientgroup + " </td>";
html += "<td>" + jsonArray[i].hostgroup + "</td>";
html += "<td>" + jsonArray[i].server + "</td>";
html += "<td>" + jsonArray[i].Group + "</td>";
html += "<td>" + jsonArray[i].user + "</td>";
html += "<td>" + jsonArray[i].ticket + "</td>";
html += "<td>" + jsonArray[i].requesttype + "</td>";
$.ajax({
url : "BulkValidateServlet",
type : "POST",
data : {clientgroup: jsonArray[i].Clientgroup, hostgroup: jsonArray[i].hostgroup, server: jsonArray[i].server
},success : function(response){
//alert("i in of ajax:"+i);
status = response;
if (status) {
//alert("outside if: " + status);
//$('<img src=\'images/check_mark.png\' height=\'20\' width=\'20\'/></td>').appendTo(tr);
html += "<td id=\"result"+ i + "\"><img src='images/check_mark.png' height='20' width='20'/></td>";
} else {
//alert("outside else: " + status);
//$('<img src=\'images/cross_mark.png\' height=\'20\' width=\'20\'/></td>').appendTo(tr);
html += "<td id=\"result"+ i + "\"><img src='images/cross_mark.png' height='20' width='20'/></td>";
}
console.log("Data: " + status);
// alert("Data: " + status );
//return status;
}
});
console.log("outside: " + status);
alert();
}
document.getElementById('tbodyLeads').innerHTML = html;
}
You can try adding
async: false
to your ajax attributes.
Refer to this link.

Change position of data in tables

I have written JavaScript which retrieves data and sets it into a series of tables as shown below.
$(function()
{
$.ajax(
{
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists(guid'9BBF789F-E5BA-449D-A595-BAA326E2C8FF')/Items?$expand=Category&$select=Id,Related_x0020_Working_x0020_PracId,Title,Reference,Policy_x0020_Type,Category/Title&$orderby=Category/Title asc",
type:"get",
headers: { "accept": "application/json;odata=verbose" },
success: function(dataObj)
{
//to uniquely identifiy the accordion.
var intCat = 0;
var arrPolicies = [];
var arrCategories = [];
//Get the policies and seperate out the categories from the returned REST call
for(var i =0; i < dataObj.d.results.length; i++)
{
var strCategory = dataObj.d.results[i].Category.Title;
arrPolicies.push({
"Id" : dataObj.d.results[i].Id,
"Title" : dataObj.d.results[i].Title,
"Category" : strCategory,
"Ref" : dataObj.d.results[i].Reference,
"PolicyType" : dataObj.d.results[i].Policy_x0020_Type,
"WorkingPracticeId" : dataObj.d.results[i].Related_x0020_Working_x0020_PracId
});
//setting category if not found
//in array
if(arrCategories.indexOf(strCategory) == -1)
{
//Add the category to the list...
arrCategories.push(strCategory);
}
}
//Output the menu to the screen for each category - one by one
arrCategories.forEach(function(varCategory)
{
var strCatIdentifier = "tblCategory_" + intCat;
var strCatImgIdentifier = "tblCategory_image_" + intCat;
var strCategoryInfo = "<table>"+
"<tbody>" +
"<tr>"+
"<td class='category'>"+
"<a href='javascript:ExpandCollapseRow(" + strCatIdentifier + ","+strCatImgIdentifier+")'>"+
"<img id='"+strCatImgIdentifier+"' src='" + _spPageContextInfo.webAbsoluteUrl + "/SiteAssets/Images/expand-16.png' alt='expand category'/>"+
"</a> "+
varCategory +
"</td>"+
"</tr>"+
"<tr><td>"+
"<table id='" + strCatIdentifier + "' class='indent hidden'>";
//looping through policies - add the details into the category table's cell
arrPolicies.forEach(function(varPolicy)
{
//checking the category attached to the policy is the same as what
//category it is on
if(varPolicy.Category == varCategory)
{
//checking to see if the
if(varPolicy.PolicyType == "Policy and Responsibility")
{
strCategoryInfo += "<tr>"+
"<td class='policy'>" +
"<a href='#'>"+
"<img src='"+_spPageContextInfo.webAbsoluteUrl+"/SiteAssets/Images/arrowicon.png' alt='View Document'/>"+
"</a>"
+ varPolicy.PolicyType + ": "+varPolicy.Ref +" - " + varPolicy.Title +
"</td>"+
"</tr>";
}
//If Working Practice - add in the sub-table (3rd level table) for attachments
if(varPolicy.PolicyType == "Working Practices")
{
var strCatWPIdentifier = "tblWorkingPractice" + varPolicy.Id;
var strCatWPImgIdentifier = "sub_level_image" + varPolicy.Id;
strCategoryInfo += "<tr>"+
"<td class='working_practice'>"+
"<a href='javascript:ExpandCollapseRow(" + strCatWPIdentifier + ","+strCatWPImgIdentifier+")'>"+
"<img id='"+strCatWPImgIdentifier+"' src='" + _spPageContextInfo.webAbsoluteUrl + "/SiteAssets/Images/expand-16.png' alt='expand working practice'/>"+
"</a> "+
varPolicy.PolicyType + " - " + varPolicy.Title+
"</td>"+
"</tr>";
var intAttachmentCount = 0;
//Build a table by looping through the policies array AGAIN and only use the policies where the Policy Type is 'Attachment' AND the 'WorkingPracticeID' is the same as the pilocy ID
arrPolicies.forEach(function(varWPAttachment)
{
if(varWPAttachment.WorkingPracticeId == varPolicy.Id && varWPAttachment.PolicyType == "Working Practice Attachment")
{
intAttachmentCount++;
strCategoryInfo += "<tr>"+
"<td>"+
"<table id='"+strCatWPIdentifier+"' class='indent hidden'>"+
"<tr>"+
"<td>"+
varWPAttachment.PolicyType +" - "+ varWPAttachment.Title+ " - " + varPolicy.Title+
"</td>"+
"</tr>"+
"</table>"+
"</td>"+
"</tr>";
}
});
if(intAttachmentCount == 0)
{
strCategoryInfo += "<tr>"+
"<td>"+
"<table id='"+strCatWPIdentifier+"' class='indent hidden'>"+
"<tr>"+
"<td>"+
"Sorry, no attachments found for this practice."+
"</td>"+
"</tr>"+
"</table>"+
"</td>"+
"</tr>";
}
}
}
});
//Close the 'Category details' table
strCategoryInfo += "</table>";
//Close the table for the category...
strCategoryInfo += "</td></tr>" +
"</tbody>"+
"</table>";
intCat++;
$('#divQualityFrameworkMenu').append(strCategoryInfo + "<br />");
});
},
error: function(error)
{
alert("Error");
}
});
});
I want to be able to organise them so that related data is grouped together ie Policies are above working practices.
How would I go about doing this
This seems pretty easy. After the first for (var d = 0; [...] ) loop, but before the arrCategories.forEach([...]), just sort arrPolicies to your choosing:
arrPolicies.sort(function(policy1, policy2) {
//Policies BEFORE Working Practicies:
if (policy1.PolicyType === "Policies and Responsibilities" && policy2.PolicyType === "Working Practices") {
return -1;
}
//Working Practicies AFTER Policies:
if (policy1.PolicyType === "Working Practices" && policy2.PolicyType === "Policies and Responsibilities") {
return 1;
}
//[Include any other orderings you might have...]
//If you've reached the end here, then you must not care about the ordering of these policies, so just make them "equal":
return 0;
});

Working with JSON input

I'm trying to get a JSON input with AJAX and load it in a select control.
but when I run it :\ It stuck on "Downloading the recipes....".
anyone see the problem maybe? (I tried couple of changes but nothing work so far)
1 more issue can anyone think on a shorter way to do the
ConvertToTable(targetNode)
cuse it's way to long and complex, I think :\
<script type="text/javascript">
function loadXMLDoc() {
var xmlhttp;
document.getElementById("span").style.visibility = "visible";
document.getElementById("span1").style.visibility = "hidden";
document.getElementById("button").style.visibility = "hidden";
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
result = xmlhttp.responseText;
result = eval('(' + result + ')');
txt = "<select onchange='ShowRecipeDetails(this)'>";
for (i = 0; i < result.length; i++) {
txt = txt + "<option VALUE=" + result[i].recipe + ">" + result[i].recipe + "</option>";
}
txt = txt + "</select >";
document.getElementById("span").style.visibility = "hidden";
document.getElementById("span1").style.visibility = "visible";
document.getElementById("myDiv").innerHTML = txt;
}
}
xmlhttp.open("POST", "http://food.cs50.net/api/1.3/menus?meal=BREAKFAST&sdt=2011-03-21&output=json", true);
xmlhttp.setRequestHeader("Content-Type", "application/json; charset=utf-8");
xmlhttp.send();
}
function ShowRecipeDetails(event) {
// get the index of the selected option
var idx = event.selectedIndex;
// get the value of the selected option
var field = event.options[idx].value;
$.ajax({
type: "GET",
url: "http://food.cs50.net/api/1.3/recipes?&output=json&id=" + field,
success: function (data) {
$("#TableDiv").html(ConvertToTable(data[0]));
}
});
}
function ConvertToTable(targetNode) {
var table = "<table border = 1 borderColor =green>";
table += "<tr>";
table += "<td>" + "ID" + "</td>";
table += "<td>" + targetNode.id + "</td>";
table += "</tr>";
table += "<td>" + "Ingredients:" + "</td>";
table += "<td>" + targetNode.ingredients + "</td>";
table += "</tr>";
table += "<td>" + "Name:" + "</td>";
table += "<td>" + targetNode.name + "</td>";
table += "</tr>";
table += "<td>" + "Size:" + "</td>";
table += "<td>" + targetNode.size + "</td>";
table += "</tr>";
table += "<td>" + "Unit" + "</td>";
table += "<td>" + targetNode.unit + "</td>";
table += "</tr>";
table += "<td>" + "VEGETARIAN:" + "</td>";
table += "<td>" + targetNode.VEGETARIAN + "</td>";
table += "</tr>";
table += "</tr>";
table += "</table>"
return table;
}
</script>
and the HTML:
<button id="button" type="button" onclick="loadXMLDoc()" >Get all recipes</button>
<br />
<span id="span" style="visibility:hidden">Downloading the recipes....</span>
<span id="span1" style="visibility:hidden">Please choose a recipe ID to view</span>
<div id="jsonDiv"></div>
<div id="myDiv"></div>
<div id="TableDiv"></div>
The HarvardFood API also supplies a JSONP version. So if you change your URL to this:
http://food.cs50.net/api/1.3/menus?meal=BREAKFAST&sdt=2011-03-21&output=jsonp&callback=parseResponse
you can create a parseResponse function to handle the data that comes back, and you can do the AJAX by inserting a script tag.
The problem is that you're running afoul the Same Origin Policy.
I see that you've updated the question to use jQuery AJAX. That offers a jsonp data type, which might be easier than adding a script tag.

Categories