FB ui feed get message after posting on wall - javascript

I'm using this function to initiate a UI feed to post on my wall a content from my website. :
FB.ui({
method: 'feed',
name: myname,
link: window.location.href,
picture: mypic,
caption: '',
description: desc
},function(response){}
});
I need to execute a callback inside the callback in which I can retrieve the message that the I inserted in the Facebook Dialog, I'm searching but not finding a way to get it, I also tried to delegate a keydown event to the dialog's textarea , but It does not work.
How can I solve this?

In order to extract data from the post that was created from the dialog you can retrieve the post_id from within the callback function that the dialog provides. Within the callback you'll be able to inspect the response object. It will contain the post_id provided that the post was successfully created.
With this post_id you can execute an additional call to the API and provide the post_id` as the endpoint:
https://graph.facebook.com/POST_ID
Or with the JavaScript SDK:
FB.api( '/POST_ID', function( response ) {
console.log( response );
} );
Take a look at the response object from the second call, it'll look something like this :
{
"id": "POST_ID",
"from": {
"name": "Lix",
"id": "XXXYYY"
},
"message": "Checkout this awesome link!",
"picture": "https://fbexternal-a.akamaihd.net/...",
...
}
As you can see, the message is contained in the response, so to enhance my previous example:
FB.api( '/POST_ID', function( response ) {
if ( response ){
console.log( response.message );
}
} );
And now we can put it all together with the FB.ui call:
FB.ui({
method: 'feed',
...
},function( response ){
if ( response && response.post_id ){
FB.api( '/' + response.post_id, function( response ) {
console.log( response );
} );
}
}
});

Related

Meteor HTTP call is different from jquery ajax?

I have the same call in Meteor HTTP and in jQuery ajax. But the response from server is different.
Meteor:
HTTP.call("POST", url, {
params: data
}, function (error, result) {
//My works....
})
jQuery:
$.ajax({
"url": url,
"method": "POST",
"data": data,
success: function(data_res) {
//My works...
}
})
I would expect the same result, but jquery is executed correctly, while meteor returns an error.
Are calls not identical?
In Meteor method call, Use 'data' field instead of 'params' as it's a POST request.
Try this in Meteor :
HTTP.post( URL, {data:dataToBePosted,headers:{key:value}}//if headers needed use headers field
,function( error, response ) {
if ( error ) {
console.log( error );
} else {
console.log( response);
}
});

Vue js Ready function is not triggered

I have this vue function where there are basically two methods. The first one postStatus is used to save a post just after the user clicks on the save button, and the other one getPosts is used to retrieve all previous posts of that user from the database.
Here is the vue.js, where there is an ajax call to a controller (in Laravel 5.3)
$(document).ready(function () {
var csrf_token = $('meta[name="csrf-token"]').attr('content');
/*Event handling within vue*/
//when we actually submit the form, we want to catch the action
new Vue({
el : '#timeline',
data : {
post : '',
posts : [],
token : csrf_token,
limit : 20,
},
methods : {
postStatus : function (e) {
e.preventDefault();
//console.log('Posted: '+this.post+ '. Token: '+this.token);
var request = $.ajax({
url : '/posts',
method : "POST",
dataType : 'json',
data : {
'body' : this.post,
'_token': this.token,
}
}).done(function (data) {
//console.log('Data saved successfully. Response: '+data);
this.post = '';
this.posts.unshift(data); //Push it to the top of the array and pass the data that we get back
}.bind(this));/*http://stackoverflow.com/a/26479602/1883256 and http://stackoverflow.com/a/39945594/1883256 */
/*request.done(function( msg ) {
console.log('The tweet has been saved: '+msg+'. Outside ...');
//$( "#log" ).html( msg );
});*/
request.fail(function( jqXHR, textStatus ) {
console.log( "Request failed: " + textStatus );
});
},
getPosts : function () {
//Ajax request to retrieve all posts
$.ajax({
url : '/posts',
method : "GET",
dataType : 'json',
data : {
limit : this.limit,
}
}).done(function (data) {
this.posts = data.posts;
}.bind(this));
}
},
//the following will be run when everything is booted up
ready : function () {
console.log('Attempting to get the previous posts ...');
this.getPosts();
}
});
});
So far the, first method postStatus is working fine.
The second one is supposed to be called or fired right at the ready function, however, nothing happens. I don't even get the console.log message Attempting to get the previous posts .... It seems it's never fired.
What is the issue? How do I fix it?
Notes: I am using jQuery 3.1.1, Vue.js 2.0.1
I see that you are using Vue 2.0.1. There is no ready method in Vue 2.0 and above.
Here is the link to list of all Vue 2.0 changes: https://github.com/vuejs/vue/issues/2873
As mentioned in the page above, you can use mounted instead of ready.
Not an issue, but just a note: You are mixing jQuery and Vue extensively. If you need jQuery only for http related functions, you may instead use vue-resource - https://github.com/vuejs/vue-resource
EDIT: Update on vue-resource
As pointed out by #EmileBergeron in the comments, vue-resource was retired way back in November 2016 itself (few weeks after I provided this answer with that last paragraph on vue-resource). Here is more info on the same:
https://medium.com/the-vue-point/retiring-vue-resource-871a82880af4
#Mani's suggestion of using mounted(){} works on the component that's not hidden. If you like to run a function in the component when visible and the elements which are hidden using conditions like v-if="" or v-show="" then use updated(){}.

WordPress REST API - Allow anyone to POST

I am building an application on WordPress that requires a simple front end form where anyone can submit information that needs to be saved in the database. I am attempting to handle this through the REST API. (Due to the nature of the application, there can not be any redirection of the page when this information is submitted.)
I have no problem setting up the REST API (v2) so that I can submit a post. It works great when I am logged into WordPress. When I try to fill out the form when I am not logged in to WordPress, I receive an error.
Failed to load resource: the server responded with a status of 403 (Forbidden)
How can I set the API to receive a POST from anyone without authentication?
Here is my javascript:
$( '#post-submission-form' ).on( 'submit', function(e) {
e.preventDefault();
var title = $( '#post-submission-title' ).val();
var excerpt = $( '#post-submission-excerpt' ).val();
var content = $( '#post-submission-content' ).val();
var status = 'draft';
var data = {
title: title,
excerpt: excerpt,
content: content
};
$.ajax({
method: "POST",
url: POST_SUBMITTER.root + 'wp/v2/posts',
data: data,
beforeSend: function ( xhr ) {
//xhr.setRequestHeader( 'X-WP-Nonce', POST_SUBMITTER.nonce );
},
success : function( response ) {
console.log( response );
alert( POST_SUBMITTER.success );
},
fail : function( response ) {
console.log( response );
alert( POST_SUBMITTER.failure );
}
});
});
Here is how I am initializing my javascript:
function holiday_scripts() {
// Onload JS
wp_enqueue_script( 'holiday-js', get_template_directory_uri() . '/js/holiday.js', array(), false, true );
//localize data for script
wp_localize_script( 'holiday-js', 'POST_SUBMITTER', array(
'root' => esc_url_raw( rest_url() ),
'nonce' => wp_create_nonce( 'wp_rest' ),
'success' => __( 'Thanks for your submission!', 'your-text-domain' ),
'failure' => __( 'Your submission could not be processed.', 'your-text-domain' ),
'current_user_id' => 9
)
);
}
add_action( 'wp_enqueue_scripts', 'holiday_scripts' );
Does anyone have any idea on how to accomplish this?
Thanks!
There are three different options to authenticate to the REST API:
Cookie - this is what you are using now
OAuth - requires the OAuth plugin and embedding key on the front end
Basic - requires embedding the username/password on the front end
See the documentation on using these methods here: http://v2.wp-api.org/guide/authentication/.
There are obvious security risks when embedding the auth info on the front end, which is required by OAuth and Basic as anyone will be able to authenticate as the user the key is associated with. I'm not familiar enough with the WP OAuth plugin to know how granularly you can control access, but I don't think you really can.
The easiest solution is to write your own method outside the REST API to handle these updates (or contribute to the project to make unauthenticated requests possible). I wrote up a guide for Creating AJAX Functions on my website, but basically you want to attach a function to the wp_ajax_nopriv_* hook, where the * is the "action" parameter of your request. In your hooked PHP function you handle the post insertion and respond with JSON (you could even match the WP REST API format).
PHP
// insert new post
function create_post_33741541() {
// use the $_POST to create your post
$args = array(
'post_title' => isset( $_POST['title'] )? $_POST['title'] : 'Empty Title',
// more parameters....
);
$post_id = wp_insert_post( $args );
// make a response
$response = array( 'post_id' => $post_id, 'message' => 'post created!' );
// set the content type and return json encode response, then exit
header( 'Content-type: application/json' );
die( json_encode( $response ) );
}
// use wp_ajax_nopriv to access from front end
add_action( 'wp_ajax_nopriv_create_post_33741541', 'create_post_33741541' );
add_action( 'wp_ajax_create_post_33741541', 'create_post_33741541' );
JavaScript
function createThePost(){
var data = {
// use the part after "wp_ajax_nopriv" as the action
action: 'create_post_33741541',
title: 'Your title',
// other params
};
$.ajax({
method: "POST",
url: ajaxurl,
data: data,
// your handlers
});
}

Jquery ajax fail when calling rest webservice

I have a set of REST URIs that i can access after authenticating on the server. This service takes a JSON input with the login information and retrieve a JSON output with the session ID.
When using a Rest client, like a chrome extension, everything works.
Now I want to implement it using JS but despite of the failure return, I can not see any details of what is wrong (error messages are blank) and neither could found what I am missing in my code.
$.ajax({
// the URL for the request
url: "https://host002:50000/b1s/v1/Login",
// the data to send (will be converted to a query string)
data: {
UserName: "manager",
Password: "1234",
CompanyDB: "CUS_001"
},
// whether this is a POST or GET request
type: "POST",
// the type of data we expect back
dataType : "json",
// code to run if the request succeeds;
// the response is passed to the function
success: function( json ) {
$( "<h1/>" ).text( json.title ).appendTo( "body" );
$( "<div class=\"content\"/>").html( json.html ).appendTo( "body" );
},
// code to run if the request fails; the raw request and
// status codes are passed to the function
error: function( xhr, status, errorThrown ) {
alert( "Sorry, there was a problem! " + xhr.responseText);
console.log( "Error: " + errorThrown );
console.log( "Status: " + status );
console.dir( xhr );
},
// code to run regardless of success or failure
complete: function( xhr, status ) {
alert( "The request is complete!" );
}
});
xhr.responseText is always blank. Status is always error. errorThrown is always blank as well.
I tried also the $post method but got the same behavior.
Your JSON is incorrect. Try using this
data: JSON.stringify({UserName: "manager", Password: "1234", CompanyDB: "CUS_001"});
While navigating from one url to other there is a cross-domain error thing which pops up.
Try doing this.
Call to a function on your same url using ajax and from there use CURL request to your web service url.

Posting to facebook wall using graph api

I'm trying to post a text with image to facebook wall using graph api.
I'm using following code snippet for this.
var body = {
message : 'this is a test message',
image : 'http://someurltoimage.png'
};
FB.api(
"/me/feed",
"POST",
{
"object": {
"message": body.message,
"picture": body.image
}
},
function (response) {
if (response && !response.error) {
//process when success
}
}
);
But I'm getting following error code.
error: Object
code: 100
error_subcode: 1349125
message: "Invalid parameter"
type: "FacebookApiException"
There's no document for this error.
Any advise will be appreciated.
"I'm trying to post a text with image to facebook wall using graph api."
You are using /feed, to upload a photo you have to use /photos call
You are sending an invalid parameter object which contains your parameters, to Facebook, the API doesn't know that your parameter Object is an object (I know, too many objects here, in another way, you're sending an object within an object
To solve all this, replace me/feed with me/photos and the 3rd argument (your object) with the body
var body = {
message : 'this is a test message',
url: 'http://someurltoimage.png'
};
FB.api("/me/photos",
"POST",
body,
function (response) {
if (response && !response.error) {
//process when success
}
}
);

Categories

Resources