I'm trying to put a button on my website to allow our customers to place reviews on our Facebook page. I need this button to open up a dialog similar to the FB.ui feed dialog but with the possibility to rate the comment with that 5 stars style used on Facebook reviews? Can I do that with php o javascript?
My code for feed:
<script type="text/javascript">
x$.ready(function () {
x$('#share_button').click(function (e) {
e.preventDefault();
FB.ui(
{
method: 'feed',
name: '<?php echo $linkname;?>',
link: '<?php echo $link;?>',
<?php if (isset($campaign->facebook_image) && $campaign->facebook_image != '' && $campaign->facebook_image != null) { ?>
picture: '<?php echo 'bo.opinat.com' . DIRECTORY_SEPARATOR . 'facebookimages' . DIRECTORY_SEPARATOR . $campaign->id . DIRECTORY_SEPARATOR .$campaign->facebook_image; ?>',
<? } ?>
caption: '<?php echo $linkcaption;?>',
description: '<?php echo $linkdescription;?>'
},
function (response) {
if (response && !response.error_message) {
FB.api('/' + response.post_id, function (response) {
x$().xhr('<?php echo Yii::app()->createUrl('survey/saveSocialMediaPost', array('answer_id' => $answer->id, 'social_network' => 1, 'state' => 'P', 'user_id' => $campaignCenter->social_media_user)); ?>', {
method: 'POST',
async: true,
data: 'message=' + response.message + '&post_id=' + response.id,
});
console.log(response.message);
});
}
else {
x$().xhr('<?php echo Yii::app()->createUrl('survey/saveSocialMediaPost', array('answer_id' => $answer->id, 'social_network' => 1, 'state' => 'E', 'user_id' => $campaignCenter->social_media_user)); ?>', {
method: 'POST',
async: true,
data: 'message=' + response.error_message + '&post_id=' + response.error_code,
});
}
}
);
});
});
</script>
As you can read in the docs, you can´t post reviews/ratings with the API: https://developers.facebook.com/docs/graph-api/reference/page/ratings#Creating
You can't perform this operation on this endpoint.
Related
I'm using Quill editor on Livewire and trying to upload inserted images on editor with Livewire JavaScript Upload API. The problem is,
I can't insert temporary url to editor. If I use $image->temporaryUrl() or $url outside of editor, image shows. I can get image temporary url. But $image->temporaryUrl() and $url not working inside the editor. And images are still uploading to livewire-tmp directory. Just can't insert temporary url to editor.
My blade file:
<script>
var quill = null;
function selectLocalImage() {
const input = document.createElement('input');
input.setAttribute('type', 'file');
input.click();
// Listen upload local image and save to server
input.onchange = () => {
const file = input.files[0];
// file type is only image.
if (/^image\//.test(file.type)) {
imageHandler(file);
} else {
console.warn('You could only upload images.');
}
};
}
function imageHandler(image) {
var formData = new FormData();
var url = '{{ $url }}';
formData.append('image', image);
formData.append('_token', '{{ csrf_token() }}');
formData.append('pageId', '{{ $page->id }}');
//let file = document.querySelector('image').files[0];
#this.upload('image', image, (uploadedFilename) => {
insertToEditor(url, quill);
})
}
function insertToEditor(url, editor) {
// push image url to rich editor.
const range = editor.getSelection();
editor.insertEmbed(range.index, 'image', url);
}
$(document).ready(function() {
var options = {
modules: {
syntax: true,
toolbar: [
[{
'font': []
}, {
'size': []
}],
['bold', 'italic', 'underline', 'strike'],
[{
'color': []
}, {
'background': []
}],
[{
'script': 'super'
}, {
'script': 'sub'
}],
[{
'header': '1'
}, {
'header': '2'
}, 'blockquote', 'code-block'],
[{
'list': 'ordered'
}, {
'list': 'bullet'
}, {
'indent': '-1'
}, {
'indent': '+1'
}],
['direction', {
'align': []
}],
['link', 'image', 'video', 'formula'],
['clean']
]
},
placeholder: 'Content...',
theme: 'snow'
};
quill = new Quill('#editor', options);
quill.getModule('toolbar').addHandler('image', () => {
selectLocalImage();
});
quill.on('text-change', function() {
#this.set('pageBody', quill.root.innerHTML);
});
});
</script>
My component:
public $image;
public $url;
public function updatedImage()
{
if ($this->image) {
$this->url = $this->image->temporaryUrl();
// dd($this->url); <---- Showing temporary url
}
}
How can I solve this problem?
After some research I've changed my code like below.
After upload, fired an event called imageAdded with image parameter. And listen this event on Livewire component.
With imageAdded function I've defined image's temporary url. And dispatched a browser event called getUrl. With array_push I added new images to $images array. Because there could be multiple images to upload.
Finally, listened dispatched browser event getUrl on Java Script and then added to editor with insertToEditor function.
function imageHandler(image) {
var formData = new FormData();
formData.append('image', image);
formData.append('_token', '{{ csrf_token() }}');
formData.append('pageId', '{{ $page->id }}');
#this.upload('image', image, (uploadedFilename) => {
window.livewire.emit('imageAdded', image);
});
}
window.addEventListener('getUrl', e => {
e.detail.imageUrl;
console.log(e.detail.imageUrl);
insertToEditor(e.detail.imageUrl, quill);
});
function insertToEditor(url, editor) {
// push image url to rich editor.
const range = editor.getSelection();
editor.insertEmbed(range.index, 'image', url);
}
Component:
public $images = [];
public $image;
public $url;
protected $listeners = ['imageAdded'];
public function imageAdded()
{
$this->url = $this->image->temporaryUrl();
$this->dispatchBrowserEvent('getUrl', ['imageUrl' => $this->url]);
array_push($this->images, $this->image);
}
public function store()
{
foreach ($this->images as $key => $image) {
$image->store('images/page_images/'.$this->page->id);
}
}
Now I can upload images with Quill editor on Livewire. Suggestions would be pleased.
I've developed this part based in your code. With that you can replace the temporary url by stored images. If you want, you can save regex in variable.
public function store()
{
$this->validate();
foreach ( $this->images as $key => $image ) {
$temporaryUrl = $image->temporaryUrl();
preg_match('/(https?:\/\/.*\.(?:png|jpg|gif))/', $temporaryUrl, $tmp);
if ( $tmp[0] ) {
$temporaryUrl = $tmp[0];
$url = $image->store('imgs/help-center');
$url = config('app.url') . '/' . $url;
preg_match('/(https?:\/\/.*\.(?:png|jpg|gif))/', $url, $match);
if ( $match[0] ) {
$url = $match[0];
$this->article['content'] = str_replace($temporaryUrl, $url, $this->article['content']);
}
}
}
$this->images = [];
$article = HelpCenter::updateOrCreate([
'id' => $this->article['id']
], $this->article);
}
i hope it help you
I am using typeahead library, it's fetching the data successfully. But not loading the data into the suggestions list, instead its showing the unable to find any company that match current query every time.
Here is my code:
$('#js-typeahead').typeahead({
highlight: true,
minLength: 1
}, {
displayKey: ['title'],
source: function(keywords, result) {
ajaxRequest({
url: '{{ route("admin.companies.auto-complete") }}',
dateType: 'json',
data: {
keywords: keywords,
_token: '{{ csrf_token() }}'
},
success: function(response) {
result($.map(response, function(data) {
return {
'title': data.title,
'token': data.token,
};
}));
}
});
},
templates: {
empty: [
'<div class="empty-message">',
'unable to find any company that match current query',
'</div>'
].join('\n'),
suggestion: function(data) {
return '' + data.title + '';
}
}
});
Here is the fetched data
Please tell me what am I doing wrong here.
[SOLVED]: Here is my final code...
$('.js-typeahead').typeahead({
hint: false,
highlight: true,
minLength: 1
}, {
displayKey: 'title',
source: (new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('title'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: '{{ route("admin.{$parent['route']}.auto-complete") }}',
prepare: function (keywords, settings) {
return $.extend({}, settings, {
type: "POST",
contentType: "application/json; charset=UTF-8",
data: JSON.stringify({
keywords: keywords,
_token: '{{ csrf_token() }}'
})
});
}
}
})),
templates: {
empty: '<div class="empty">No result found</div>',
suggestion: function (data) {
return '<div>' + data.title + '</div>';
}
},
}).on('typeahead:asyncrequest', function(event) {
$('.js-typeahead').before('<i class="fas fa-spinner fa-spin loading"></i>');
}).on('typeahead:asyncreceive', function(event) {
$('.js-typeahead').prev('.loading').remove();
}).on('typeahead:selected', function(event, selection) {
// window.location.href = selection.token;
});
I hope this may come in handy for someone...
You're code is practically correct. And the best thing is that you can also get the result without using bloodhound.
from the initial code you state, you are calling it synchronously. thats why it does not yield any result.from typeahead docs. here is the highlight
Expected to be a function with the signature (query, syncResults, asyncResults). syncResults should be called with suggestions computed synchronously and asyncResults should be called with suggestions computed asynchronously (e.g. suggestions that come for an AJAX request)
so your initial code part
source: function(keywords, result) {
ajaxRequest({
url: '{{ route("admin.companies.auto-complete") }}',
dateType: 'json',
data: {
keywords: keywords,
_token: '{{ csrf_token() }}'
},
success: function(response) {
result($.map(response, function(data) {
return {
'title': data.title,
'token': data.token,
};
}));
}
});
},
are running synchronously, and because you are fetching data from ajax, you should make it asynchronously like this (i added asyncresult)
source: function(keywords, result, asyncresult) {
ajaxRequest({
url: '{{ route("admin.companies.auto-complete") }}',
dateType: 'json',
data: {
keywords: keywords,
_token: '{{ csrf_token() }}'
},
success: function(response) {
asyncresult($.map(response, function(data) {
return {
'title': data.title,
'token': data.token,
};
}));
}
});
},
hope it helps!
Orignal code from opencart:-
var cart = {
'add': function(product_id, quantity) {
$.ajax({
url: 'index.php?route=checkout/cart/add',
type: 'post',
data: 'product_id=' + product_id + '&quantity=' + (typeof(quantity) != 'undefined' ? quantity : 1),
dataType: 'json',
beforeSend: function() {
$('#cart > button').button('loading');
},
complete: function() {
$('#cart > button').button('reset');
},
success: function(json) {
$('.alert, .text-danger').remove();
if (json['redirect']) {
location = json['redirect'];
}
if (json['success']) {
$('#content').parent().before('<div class="alert alert-success"><i class="fa fa-check-circle"></i> ' + json['success'] + ' <button type="button" class="close" data-dismiss="alert">×</button></div>');
// Need to set timeout otherwise it wont update the total
setTimeout(function () {
$('#cart > button').html('<span id="cart-total"><i class="fa fa-shopping-cart"></i> ' + json['total'] + '</span>');
}, 100);
$('html, body').animate({ scrollTop: 0 }, 'slow');
$('#cart > ul').load('index.php?route=common/cart/info ul li');
}
},
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
},
I tried to edit these way but it had no effect on the front end everything was same
check below i tried replacing the code here:-
var cart = {
'add': function(product_id, quantity) {
$.ajax({
url: 'index.php?route=checkout/cart/add',
type: 'post',
data: 'product_id=' + product_id + '&quantity=' + (typeof(quantity) != 'undefined' ? quantity : 1),
dataType: 'json',
beforeSend: function() {
$('#cart > button').button('loading');
},
complete: function() {
$('#cart > button').button('reset');
},
success: function(json) {
$('.alert, .text-danger').remove();
if (json['redirect']) {
location = json['redirect'];
}
//here i replaced the code
if (json['success']) {
window.location='index.php?route=checkout/checkout';
}
},
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
},
can anyone kindly help me out with these opencart 2.3.0.2 problem..??
This should work, I'm on 2.3.0.2 and have multiple stores using this in the Success statement to redirect to the cart page after clicking add to cart.
window.location.href = "index.php?route=checkout/cart";
Obviously you'd want to change it to:
window.location.href = "index.php?route=checkout/checkout";
Good luck!
replace the redirect function where you already changed with the code below
window.location='index.php?route=checkout/checkout';
with this code, this will redirect to your checkout.
location.href='index.php?route=checkout/checkout';
Am working on facebook graph API for posting on facebook page.I have a webpage where each users can login and share contents on a facebook page.Consider certain organizations,each organization has there own facebook page.From my website any user having facebook account can come and share their feedbacks about that organization and that feedback should be posted in the facebook page of the particular organization.
I need to implement this using facebook javascript api,but am getting an error
The user hasn't authorized the application to perform this action","type":"OAuthException","code":200
Here is my code:
FB.api('/page_id/feed', 'post',
{
message : "It's awesome ...",
name : 'Feedback',
to: '',
from: '',
description : 'Your description'
},
function(response) {
if (!response || response.error) {
//alert(JSON.stringify(response.error));
console.log(JSON.stringify(response.error));
} else {
alert('Post ID: ' + response.id);
}
});
}
Please help
Thanks
Try this:
function login() {
FB.login(function (response) {
if (response.authResponse) {
// connected
postFeedBack();
} else {
// cancelled
}
}, { scope: 'publish_stream' });
}
function postFeedBack() {
FB.api('/page_id/feed', 'post', {
message: "My Feedback"
}, function (response) {
if (!response || response.error) {
alert('Error occured');
} else {
alert('Post ID: ' + response.id);
}
});
}
I've seen this example at facebook, but doesn't seem to be working.
<?php
define('YOUR_APP_ID', 'your app id ');
define('YOUR_APP_SECRET', 'your app secret');
function get_facebook_cookie($app_id, $app_secret) {
$args = array();
parse_str(trim($_COOKIE['fbs_' . $app_id], '\\"'), $args);
ksort($args);
$payload = '';
foreach ($args as $key => $value) {
if ($key != 'sig') {
$payload .= $key . '=' . $value;
}
}
if (md5($payload . $app_secret) != $args['sig']) {
return null;
}
return $args;
}
$cookie = get_facebook_cookie(YOUR_APP_ID, YOUR_APP_SECRET);
$user = json_decode(file_get_contents(
'https://graph.facebook.com/me?access_token=' .
$cookie['access_token']));
?>
All this documentation I found it on facebook so I just asumed that replacing some things would be enough.
I find an error/bug when it comes to this line
<?php if ($cookie) { ?>
Welcome <?= $user->name ?>
<?php } else { ?>
<fb:login-button></fb:login-button>
<?php } ?>
The login doesn't return the name of the person who's logged in.
I've tried this
FB.Event.subscribe('auth.login', function(response) {
alert('session:' response.session + ' connection:' response.status);
window.location.reload();
});
This return session: undefined and connection: connected, so I don't understand where is the problem.
I don't know if it is because some bug (which I already heard about with this plugin) or not