The variable x is getting the current url. I need to then put this url into the spot where the xxxx is. How would I go about doing this?
<script type='text/javascript'>
function postListen()
{
var x = ( document.URL );
FB.api(
'/me/beatmushroom:listen',
'post',
{ song: xxxx},
function(response) {
if (!response || response.error) {
alert('Error occured');
} else {
alert('Listen was successful! Action ID: ' + response.id);
}
});
}
Simply use the variable in the object literal. While the key is always a string (even without quotes), the value can be any JavaScript epxression:
{ recipe: x },
Just replace 'xxxx' with the variable x
function postCook() {
var x = ( document.URL );
FB.api(
'/me/[YOUR_APP_NAMESPACE]:cook',
'post',
{ recipe: x },
function(response) {
if (!response || response.error) {
alert('Error occured');
} else {
alert('Cook was successful! Action ID: ' + response.id);
}
}
);
}
Related
I have created a jQuery function extending its own object $. This function translate those elements attached to the element this:
$.fn.extend({
translate: function(sourceLang, targetLang) {
if($(this).text().trim().length < 1 || !isNaN(parseInt($(this).text().trim())) || sourceLang == targetLang)
return;
let $function = this;
$($function).each(function() {
let $each = this;
$.ajax({
url: 'https://translate.yandex.net/api/v1.5/tr.json/translate',
method: 'GET',
dataType: 'JSONP',
crossDomain: true,
data: {
key: /* my-secret-key */,
text: $($each).text(),
lang: sourceLang + '-' + targetLang
},
success: function(response) {
try {
if(response.code !== 200)
throw "Response: " + response.code;
$($each).text(response.text[0])
} catch(error) {
console.error('Translation error on element: ', $($function).text());
console.error('Message returned by the server:', error);
}
},
error: function(xhr, status, error) {
console.error('Translation error on element: ', $($function).text());
console.error('Message returned by the server:', xhr.responseText);
}
});
});
}
});
After loading the code I do this:
$(document).ready(function() {
let lang = $('html').attr('lang').split('-')[0];
$('td td:visible').translate(lang, "en");
});
Note: the HTML tag looks like this <html lang="es-ES"> depending on the logged user language.
The issue I have is the table loads after a couple of seconds (since we are not in Production environment they could be more than 30). Therefore the previous code block is not useful.
Note: the <tbody> tag is created when the data is added.
What I have tried is:
1. Create a setInterval() and clearInterval() when the $('td:visible').length is greater than 0:
let iv = setInterval(function() {
let lang = $('html').attr('lang').split('-')[0];
let rows = $('tbody td:visible');
if(rows.length > 0) {
rows.translate(lang, "en");
clearInterval(iv);
}
}, 1000);
2. Set a .delay() before the translation:
let isTranslated = false;
while(!isTranslated) {
let lang = $('html').attr('lang').split('-')[0];
let rows = $('tbody td:visible');
if(rows.length > 0) {
rows.delay(1000).translate(lang, "en");
isTranslated = true;
}
}
The memory consumed by the browser is greater than 200MB. I also tried with $('table').on('DOMSubstreeModified', 'tbody', function() {}) but it didn't work.
So, what approach would you recommend to use this translation plugin on this table after it loads its tbody?
Edit 1:
I have changed my code so I perform less API requests, thanks to the recommendation of #lucifer63:
let $function = this;
let collection = [];
let translation = '';
$(this).each(function() {
collection.push($(this).text());
});
let text = collection.join('::');
$.ajax({
url: 'https://translate.yandex.net/api/v1.5/tr.json/translate',
method: 'GET',
dataType: 'JSONP',
crossDomain: true,
data: {
key: /* my-secret-key */,
text: text,
lang: sourceLang + '-' + targetLang
},
success: function(response) {
try {
if(response.code !== 200) {
throw "Response: " + response.code;
}
translation = response.text[0].split('::');
$($function).each(function() {
$(this).text(translation.shift());
});
} catch(error) {
console.error('Message returned by the server:', error);
}
},
error: function(xhr, status, error) {
console.error('Message returned by the server:', xhr.responseText);
}
});
But still, I need to figure out how to print after data has loaded.
Well... I think I found the answer I was seeking:
$('body').on('DOMNodeInserted', 'table', function() {
$('td:visible').translate('es', 'en');
});
It seems it is working correctly.
I know this question was asked already often, but I have been trying to fix this problem for like more than 6 hours now and I could use a little help. Error Message: Insufficient permssion to post to target on behalf of the viewer.
I'm trying to post as page, my code so far:
var pageID = "myPage";
FB.init({
appId: "myId",
secret: "mySecret",
status: true,
cookie: true,
});
function postToFeed() {
FB.login(function(response) {
FB.api('/me/accounts', function(response) {
var accessToken = "";
var data = response.data;
for (var i=0; i<data.length; i++) {
if (data[i].id == pageID) {
accessToken = data[i].access_token;
}
}
if (accessToken == "") {
alert("You are not allowed to post.");
}
else {
console.log(accessToken);
FB.api('/' + pageID + '/feed', 'post', {
message : "test",
link : 'Link',
picture : 'Imageurl',
name : 'test',
to : pageID,
from : pageID,
description : 'test'
}, function(response) {
if (!response || response.error) {
alert(JSON.stringify(response.error));
} else {
alert('Post ID: ' + response.id);
}
});
}
});
}, {scope: 'publish_actions,manage_pages,public_profile'});
}
When I echo my accessToken via console and copy the accessToken inside this code, it works perfectly. But that's not an solution because I want it to be dynamic:
function postToFeed() {
FB.login(function(response) {
FB.api('/' + pageID + '/feed', 'post', {
access_token: 'theAcccessToken',
message: "I'm a Page!",
}, function(response) {
console.log(response);
}
);
}, {scope: 'publish_actions,manage_pages,public_profile'});
}
And this does not work? (not sure what you want to do with the "to" and "from" parameters, so i removed them)
FB.api('/' + pageID + '/feed', 'post', {
message : 'test',
link : 'Link',
picture : 'Imageurl',
name : 'test',
description : 'test',
access_token: accessToken
}
The most important thing: You need publish_pages to post "as Page", not publish_actions.
Btw, a small optimization:
for (var i = 0; i < data.length; i++) {
if (data[i].id === pageID) {
accessToken = data[i].access_token;
break;
}
}
if (accessToken === "") {
alert("You are not allowed to post.");
}
...always use typesafe comparison :)
I can't seem to check if a logged in user likes a specific Facebook Business page(URL). This keeps coming back as undefined. Notice anything wrong here?
function postLike() {
FB.api(
'https://graph.facebook.com/me/og.likes',
'get',
{ id: objectToLike,
privacy: {'value': 'SELF'} },
function(response) {
if (!response) {
alert('Error occurred.');
} else if (response.error) {
document.getElementById('result').innerHTML =
'Error: ' + response.error.message;
} else {
document.getElementById('result').innerHTML =
'Business page is ' +
response.object + '</a>';
}
}
);
}
im trying to send values in a form via POST in ajax, how do i capture them in send them, this is wat i have now while in GET
function test(ans_field_uuid){
var result = "";
var url="ajax_pages/remove_answer_field_ajax.php"
url += '?uuid=' + ans_field_uuid;
$.get(
url,
function (data) {
result = data;
}
)
.success(function () {
if (result != "") {
addTableRow('tb_add_field', result);
$('#ajaaxDiv').html(result);
}
})
.complete(function () {
$('#img_create_subcat').hide();
$('#dialog').dialog('close');
})
.error(function () {
alert('An error has occurred.');
});
return false;
}
since you already use jQuery
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
data: name and location are your POST variable.
You can fetch the POST variable in this example in some.php with
$_POST["name"]
which equals "John"
If you want to receive something then like "Hello".
Inside your some.php
echo "Hello";
and it will be send to your ajax function as response in your done function as variable msg
Documentation for jQuery post
// ...
var url = "ajax_pages/remove_answer_field_ajax.php";
$.post( url, "uuid=" + ans_field_uuid, function (data) {
result = data;
}
// ...
I am using following code to post actions on timeline
<script type="text/javascript">
function read()
{
FB.api('/me/app_namespace:read' +
'?article=http://example.com/test.php&access_token=','post',
function(response) {
var msg = 'Error occured';
if (!response || response.error) {
if (response.error) {
msg += "\n\nType: "+response.error.type+"\n\nMessage: "+response.error.message;
}
alert(msg);
}
else {
alert('Post was successful! Action ID: ' + response.id);
}
});
}
</script>
Now i want to use the following code to delete action but the problem is dont know how to save the "action id" from above code so that it can be used in following code.
<script type="text/javascript">
function deleteAction()
{
FB.api(
'/actionid',
'delete',
function(response) {
alert('action deleted')
});
}
</script>
Thanks!
It depends, are you looking to delete the action in a later session or current? In the current session itself, you can probably simply store it in a variable. For eg:
function read()
{
FB.api('/me/app_namespace:read' +
'?article=http://example.com/test.php&access_token=','post',
function(response) {
var msg = 'Error occured';
if (!response || response.error) {
if (response.error) {
msg += "\n\nType: "+response.error.type+"\n\nMessage: "+response.error.message;
}
alert(msg);
}
else {
alert('Post was successful! Action ID: ' + response.id);
var idToDeleteLater = response.id;
}
});
}
function deleteAction()
{
FB.api(
'/'+idToDeleteLater,
'delete',
function(response) {
alert('action deleted')
});
}
As you can see, that's pretty straightforward, all you've done is stored the actionID in a variable. You can potentially store multiple IDs in an array or something.
On the other hand, if you want to delete the actions in a later session (unlikely for a "read" action), then you need to store these action IDs in a database or something, and pull the action from there prior to deleting.