I have written a code following the documentation on phone gap website`
// Wait for Cordova to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// Cordova is ready
//
function onDeviceReady() {
// find all contacts
var options = new ContactFindOptions();
var fields = ["displayName", "name"];
navigator.contacts.find(fields, onSuccess, onError, options);
}
// onSuccess: Get a snapshot of the current contacts
//
function onSuccess(contacts) {
for (var i=0; i<contacts.length; i++)
{
console.log("Display Name = " + contacts[i].displayName);
var element = document.getElementById('cont');
element.innerHTML='<li>' + contacts[i].displayName + '</li>';
}
}
// onError: Failed to get the contacts
//
function onError(contactError) {
alert('onError!');
}
</script>`
It is working fine in andriod emulator but when i install the application samsung galaxy phone it return a "null". Kindly Help.
Strange... I also got null... (using Phonegap version 2.0)
I suggest you use something like contacts[i].name.formatted instead of contacts[i].displayName.
So, for example, by using contacts[i].name.formatted, your code should look like something like this:
// Wait for Cordova to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// Cordova is ready
//
function onDeviceReady() {
// find all contacts
var options = new ContactFindOptions();
var fields = ["displayName", "name"];
navigator.contacts.find(fields, onSuccess, onError, options);
}
// onSuccess: Get a snapshot of the current contacts
//
function onSuccess(contacts) {
var element = document.getElementById('cont');
for (var i=0; i<contacts.length; i++)
{
console.log("Display Name = " + contacts[i].name.formatted);
element.innerHTML='<li>' + contacts[i].name.formatted + '</li>';
}
}
// onError: Failed to get the contacts
//
function onError(contactError) {
alert('onError!');
}
Here are the different information that you can obtain with contacts[i].name:
contacts[i].name.givenName : provides the given name
contacts[i].name.formatted : provides a formatted name (first name + last name)
contacts[i].name.middleName : provides the middle name
contacts[i].name.familyName : provides the family name (first name + last name)
contacts[i].name.honorificPrefix : provides the honorific prefix
contacts[i].name.honorificSuffix : provides the honorific suffix
Hope this helps.
It is a complex problem with simple solution. just added only one line of code
options.filter="";
options.multiple=true;
var filter = ["*"];
That is complete code is
<script type="text/javascript" charset="utf-8">
// Wait for Cordova to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// Cordova is ready
//
function onDeviceReady() {
// find all contacts
var options = new ContactFindOptions();
options.filter="";
options.multiple=true;
var filter = ["*"];
navigator.contacts.find(filter, onSuccess, onError, options);
}
// onSuccess: Get a snapshot of the current contacts
//
function onSuccess(contacts) {
var ele = document.getElementById("cont");
var str = '<ul data-role="listview" >';
for (var i=0; i<contacts.length; i++) {
str=str + '<li>' + contacts[i].displayName + '</li>';
}
str = str + '</ul>';
// ele.innerHTML = str;
}
// onError: Failed to get the contacts
//
function onError(contactError) {
alert('onError!');
}
And it is working, by the way it also shows some null values as per the contact entries but it is working fine.
It may be iOS - http://docs.phonegap.com/en/2.1.0/cordova_contacts_contacts.md.html#Contacts. The docs say displayName isn't supported there. I'd follow Littm's advice, and also check the doc I linked to here as it talks about what properties don't work across different platforms.
Related
I really really need your help pls. I have been battling with these for days and my project is stucked. Your help will really be appreciated.
I have 3 pages.
Page one receives my data, and html formatted version is created. it is a loop and it returns 10 posts.
===
page 2 is the html page that displays the 10 post
====
page 3. the posts at page 2 are just featured image and excerpt and title with url... to read full, click it and go to page 3 ...
Page 3 uses the unique id of each posts to display the full post:
my question: how do i pass each post id to page 3 for full content view.
i tried to store the id generated in page 1 to localstorage, but bcos its a loop ... ONLY THE LAST ONE IS STORED..
my code..
Page 1 - script page receives data
document.addEventListener("deviceready", onDeviceReady, false);
var portfolioPostsContainer = document.getElementById("portfolio-posts-container");
function onDeviceReady(){
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'http://myurl/wp-json/wp/v2/posts?_embed');
ourRequest.onload = function() {
if (ourRequest.status >= 200 && ourRequest.status < 400) {
var data = JSON.parse(ourRequest.responseText);
createHTML(data);
console.log(data);
} else {
console.log("We connected to the server, but it returned an error.");
}
};
ourRequest.onerror = function() {
console.log("Connection error");
};
ourRequest.send();
}
Page 1 still: CreateHTMl create thru a loop
function createHTML(postsData) {
var ourHTMLString = '';
for (i = 0; i < 1; i++)
{
var posturl = postsData.link
ourHTMLString +='<tr>';
ourHTMLString += '<td>' + '' + postsData[i].title.rendered + ''+'</td>';
ourHTMLString += '<td>' + '<img width="100%" src ="' + postsData[i]._embedded['wp:featuredmedia']['0'].source_url + '" />' + ''+'</td>';
ourHTMLString += '<td>' + postsData[i].excerpt.rendered + localStorage.setItem("postid",postsData[i].id)+'</td>';
//i tried to store each id in a localstorage but only the last one remains
ourHTMLString+= '</tr>';
} portfolioPostsContainer.innerHTML = ourHTMLString;
}
page two uses this to display ourHTMLString
<div id="portfolio-posts-container"></div>
page 3 Need each post id.
function onDeviceReady(){
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'http://myurl/wp-json/wp/v2/posts/'+mypostid+'?_embed=true')
ourRequest.onload = function() {
if (ourRequest.status >= 200 && ourRequest.status < 400) {
var data = JSON.parse(ourRequest.responseText);
// createHTML(data); '+mypostid)
console.log(data);
var ourHTMLString = '';
Each post has its generated id from the api, how do i pass it to page 3 for displaying individual post
Although I'm a little confused as re the overall structure of this system, you could pass the id as a query string parameter.
View post 123
This can be parsed using location.search within JavaScript:
var postMatch = /id=(\d+)/.exec(location.search);
if(postMatch) {
var postId = postMatch[1];
// Load post postId...
} else {
// No post was passed
}
I'm trying to use youtube api to be able to search for videos through my site however, when ever I click on the search button nothing pop up.It does log what I have searched but no videos pop up. Help Please. I am currently running it on Cloud9. I did get the error that I am missing "}" but where it is tell me I am missing it, there is a bracket already there.
Here is the Java-script code :
// JavaScript File
$(function(){
console.log(part1)
var searchField = $('#query');
var icon = $('#search-btn');
console.log(data);
//Focus Event Handler
$(searchField).on('focus',function(){
console.log(part2)
$(this).animate({
width:'100%'
}, 400);
$(icon).animate({
right:'10px'
}, 400);
console.log(part3)
});
// Blur Event Handler
$(searchField).on('blur',function(){
console.log(part4)
$("#searchfield").val('');{
$(searchField).animate({
width:'45%'
},400, function(){});
console.log(part5)
$(searchField).animate({
right:'360px'
},400, function(){});
console.log(part6)
}
});
('#search-form').submit(function(e){
console.log(part7)
e.preventDefault();
});
})
function search(){
//Clear Results
console.log(part8)
$('#results').html('');
$('#buttons').html('');
// Get Form Input
q = $('#query').val();
// Run GET Request on API
$.get(
"https://www.googleapis.com/youtube/v3/search",{
part:'snippet, id',
q: q,
type:'video'
key:" AIzaSyDjByBmG4PJdONQf2DZE_SBQHuhhoZGiHg "}
function(data){
console.log(part8)
var nextPageToken = data.nextPageToken;
var previousPageToken = data.previousPageToken;
/
/ Get OutPut
console.log(part9);
$.each(data.items, function(i, items){
console.log(part10)
// Get Output
var ouput =getOutput(item);
//Display Results
$('#results').append(output);
console.log(part11)
});
}
);
}
// Build OutPut
function getOutput(item){
console.log(data);
var videoID = item.id.videoID
var title = item.snippet.title;
var description = item.snippet.description;
var thumb = item.snippet.thumbnails.high.url;
var channelTitle = item.snippet.channelTitle;
var videoDate = item.snippet.publishedAt;
console.log(part12)
// Built Output String
var output ='<li>'+
'<div class="list-left">'+
'<img src="'+thumb+'">'+
'</div>'+
'<div class="list-right">'+
'<h3>'+title+'</h3>'+
'<small>By<span class="cTitle">'+channelTitle+'</span>on '+videoDate+'</small>'+
'<p>'+description+'</p>'+
'</div>'+
'</li>'+
'div class="clearfix"></div>'+
'';
return output;
}
I have one requirement to start the SP workflow through JavaScript. For this, i have wrote some lines of code to start the workflow.But I am getting a Subscription failed error due to undefined object. This is occuring at ExcecuteasyncQuery method. So i didn't get which object returns the undefined value. My code is shown below.
<script type="text/javascript" src="/_layouts/15/sp.js"></script>
<script type="text/javascript" src="/_layouts/15/sp.core.js"></script>
<script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>
<script type="text/javascript" src="/_layouts/15/sp.workflowservices.js"> </script>
<script type="text/javascript">
var subID = "3debdbad-db52-4586-87e1-40e4db581da5";
function GetCurrentItemID()
{
var ctx = SP.ClientContext.get_current();
var selectedItems = SP.ListOperation.Selection.getSelectedItems(ctx);
for (item in selectedItems)
{
var itemId = selectedItems[item].id;
startWorkflow(itemId, subID);
}
}
function startWorkflow(itemID, subID) {
var context = SP.ClientContext.get_current();
var web = context.get_web();
var wfServiceManager = SP.WorkflowServices.WorkflowServicesManager.newObject(context, web);
var subscription = wfServiceManager.getWorkflowSubscriptionService().getSubscription(subID);
context.load(subscription);
context.executeQueryAsync(
function(sender, args){
alert("Subscription load success. Attempting to start workflow.");
var inputParameters = {};
wfServiceManager.getWorkflowInstanceService().startWorkflowOnListItem
(subscription, itemID, inputParameters);
context.executeQueryAsync(
function(sender, args){ alert("Successfully starting workflow."); },
function(sender, args){
alert("Failed to start workflow.");
alert("Error: " + args.get_message() + "\n" + args.get_stackTrace());
}
);
},
function(sender,args){
alert("Failed to load subscription.");
alert("Error: " + args.get_message() + "\n" + args.get_stackTrace());
}
);
}
</script>
I am calling the GetCurrentItemID() function at the button click. But at that time, i am getting the following error.
Failed to load subscription
Invalid Request
Undefined
Could any one please help me to sort out this issue. Thanks in advance.
According to the script and the error message,
I suggest you check whether the “subscription” and “itemId” objects hold the proper values.
What’s more, you can take a look at the two links below about how to start workflow using JavaScript Client Object Model:
http://usamawahabkhan.blogspot.com/2013/07/start-workflow-sharepoint-2010.html
https://sharepoint.stackexchange.com/questions/87015/solved-start-a-workflow-of-the-host-web-via-sharepoint-app-and-jsom
Feel free to reply with the test result or if there are any progress.
Building on the solutions provided by others, here's the code I was able to use. NOTE: You need to have your workflow set to "Allow this workflow to be started manually."
/**
* Starts a SharePoint 2013 Workflow on a particular list item.
* Params:
* workflowName: The name of the Workflow
* listGUID: the GUID of the list
* itemId: the ID of the list item
*/
function startListWorkflow(workflowName, listGUID, itemId){
SP.SOD.executeFunc("sp.js", "SP.ClientContext" , function(){
SP.SOD.registerSod('sp.workflowservices.js', SP.Utilities.Utility.getLayoutsPageUrl('sp.workflowservices.js'));
SP.SOD.executeFunc('sp.workflowservices.js', "SP.WorkflowServices.WorkflowServicesManager",
function(){
var ctx = new SP.ClientContext.get_current(),
wfsManager = SP.WorkflowServices.WorkflowServicesManager.newObject(ctx, ctx.get_web()),
wfSubs = wfsManager.getWorkflowSubscriptionService().enumerateSubscriptionsByList(listGUID);
ctx.load(wfSubs);
ctx.executeQueryAsync(function () {
wfsEnum = wfSubs.getEnumerator();
while (wfsEnum.moveNext()) {
var wfSub = wfsEnum.get_current();
if (wfSub.get_name() === workflowName) {
var initiationParams = {};
wfsManager.getWorkflowInstanceService().startWorkflowOnListItem(wfSub, itemId, initiationParams);
ctx.executeQueryAsync(
function (sender, args) {
console.log("Successfully started workflow.");
},
function (sender, args) {
console.log("Failed to start the workflow.");
console.log("Error: " + args.get_message() + "\n" + args.get_stackTrace());
}
);
}
}
},function(e){
console.error(e)
});
}
);
});
}
to check if page is published using server side code i should use this snippet:
PublishingPageCollection pages = PublishingWeb.GetPublishingWeb(web).GetPublishingPages();
foreach (PublishingPage page in pages)
{
if(!page.ListItem.File.Level == SPFileLevel.Published)
return;
// logic
}
How could i do the same but using Javascript in SharePoint?
According to SP.Publishing.PublishingWeb Methods the method GetPublishingPages is not supported in JSOM API.
But you could consider the following example to determine whether page is published or not using JSOM API
function getPublishingPages(success,error)
{
var ctx = SP.ClientContext.get_current();
var list = ctx.get_web().get_lists().getByTitle('Pages');
var items = list.getItems(SP.CamlQuery.createAllItemsQuery());
ctx.load(items,'Include(File)');
ctx.executeQueryAsync(function() {
success(items);
},
error);
}
SP.SOD.executeFunc('SP.js', 'SP.ClientContext', function() {
getPublishingPages(printPagesInfo,logError);
});
function printPagesInfo(pages)
{
pages.get_data().forEach(function(item){
var file = item.get_file();
var pageStatus = file.get_level() === SP.FileLevel.published ? 'published' : 'not published';
console.log(String.format('Page {0} is {1}', file.get_name(),pageStatus));
});
}
function logError(sender,args){
console.log('An error occured: ' + args.get_message());
}
I'm currently implementing a web smartphone application with Phonegap. On this application, users can post images they take with the phone camera on Facebook. This feature has been succesfully implemented only using javascript, by sending a base 64 encoded image. Now, I want to implement the same feature using Twitter.
I found some very interesting blog posts about this and I'm already be able to update the user status only using javascript... but I can't post images too using the update_with_media Twitter web service.
According too this post, someone says it's impossible to implement this operation without using a server side code (like a php script for example).
So my question is : is it possible to use the update_with_media Twitter web service only with javascript ?
I send you my code to have an overview of the current solution. I've taken this article as working base : http://oodlestechnologies.com/blogs/Twitter-integration-on-PhoneGap-using-ChildBrowser-and-OAuth-for-iOS-and-Android-Platforms
Here is my HTML code.
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script type="text/javascript" src="../js/jquery/jquery.min.js"></script>
<script type="text/javascript" src="../cordova-2.5.0.js"></script>
<script type="text/javascript" src="../js/childBrowser/childbrowser.js"></script>
<script type="text/javascript" src="../js/helpers/jsOAuth-1.3.6.js"></script>
<script type="text/javascript" src="../js/helpers/twitter.js"></script>
</head>
<body>
<h4>Oodles Twitter App</h4>
<table border="1">
<tr>
<th>Login using Twitter</th>
<th>
<button id="loginBtn" onclick="Twitter.init();">Login</button>
<button id="logoutBtn" onclick="logOut();">Logout</button>
</th>
</tr>
<tr id="tweetText">
<td colspan="2"><textarea id="tweet"></textarea></td>
</tr>
<tr id="tweetBtn">
<td colspan="2" align="right">
<button id="tweeter" onclick="Twitter.tweet();">Tweet</button>
</td>
</tr>
<tr><td colspan="2"><div id="welcome">Please Login to use this app</div></td></tr>
</table>
<br/>
<br/>
<button onclick="javascript:location.reload();">Recharger la page</button>
</body>
</html>
Here is my twitter.js code : (The point is in the post method)
$(document).ready(function() {
document.addEventListener("deviceready", onDeviceReady, false);
});
function onDeviceReady() {
var root = this;
cb = window.plugins.childBrowser;
if (!localStorage.getItem(twitterKey)) {
$("#loginBtn").show();
$("#logoutBtn").hide();
$("tweetBtn").hide();
$("tweetText").hide();
}
else {
$("#loginBtn").hide();
$("#logoutBtn").show();
$("tweetBtn").show();
$("tweetText").show();
}
if (cb != null) {
cb.onLocationChange = function(loc) {
root.locChanged(loc);
};
cb.onClose = function() {
root.onCloseBrowser()
};
cb.onOpenExternal = function() {
root.onOpenExternal();
};
}
}
function onCloseBrowser() {
console.log("onCloseBrowser!");
}
function locChanged(loc) {
console.log("locChanged!");
}
function onOpenExternal() {
console.log("onOpenExternal!");
}
// Consumer key : ...
// Consumer secret : ...
// GLOBAL VARS
var oauth; // It Holds the oAuth data request
var requestParams; // Specific param related to request
var options = {consumerKey: '...', consumerSecret: '...', callbackUrl: "http://www.google.fr"};
var twitterKey = "twtrKey"; // This key is used for storing Information related
var Twitter = {
init: function() {
// Apps storedAccessData , Apps Data in Raw format
var storedAccessData, rawData = localStorage.getItem(twitterKey);
// here we are going to check whether the data about user is already with us.
if (localStorage.getItem(twitterKey) !== null) {
// when App already knows data
storedAccessData = JSON.parse(rawData); //JSON parsing
//options.accessTokenKey = storedAccessData.accessTokenKey; // data will be saved when user first time signin
options.accessTokenSecret = storedAccessData.accessTokenSecret; // data will be saved when user first first signin
// javascript OAuth take care of everything for app we need to provide just the options
oauth = OAuth(options);
oauth.get('https://api.twitter.com/1/account/verify_credentials.json?skip_status=true',
function(data) {
var entry = JSON.parse(data.text);
console.log("USERNAME: " + entry.screen_name);
}
);
}
else {
// we have no data for save user
oauth = OAuth(options);
oauth.get('https://api.twitter.com/oauth/request_token',
function(data) {
requestParams = data.text;
cb.showWebPage('https://api.twitter.com/oauth/authorize?' + data.text); // This opens the Twitter authorization / sign in page
cb.onLocationChange = function(loc) {
Twitter.success(loc);
}; // Here will will track the change in URL of ChildBrowser
},
function(data) {
console.log("ERROR: " + JSON.stringify(data));
}
);
}
},
/*
When ChildBrowser's URL changes we will track it here.
We will also be acknowledged was the request is a successful or unsuccessful
*/
success: function(loc) {
// Here the URL of supplied callback will Load
/*
Here Plugin will check whether the callback Url matches with the given Url
*/
if (loc.indexOf("http://www.google.fr") >= 0) {
// Parse the returned URL
var index, verifier = '';
var params = loc.substr(loc.indexOf('?') + 1);
params = params.split('&');
for (var i = 0; i < params.length; i++) {
var y = params[i].split('=');
if (y[0] === 'oauth_verifier') {
verifier = y[1];
}
}
// Here we are going to change token for request with token for access
/*
Once user has authorised us then we have to change the token for request with token of access
here we will give data to localStorage.
*/
oauth.get('https://api.twitter.com/oauth/access_token?oauth_verifier=' + verifier + '&' + requestParams,
function(data) {
var accessParams = {};
var qvars_tmp = data.text.split('&');
for (var i = 0; i < qvars_tmp.length; i++) {
var y = qvars_tmp[i].split('=');
accessParams[y[0]] = decodeURIComponent(y[1]);
}
$('#oauthStatus').html('<span style="color:green;">Success!</span>');
$('#stage-auth').hide();
$('#stage-data').show();
oauth.setAccessToken([accessParams.oauth_token, accessParams.oauth_token_secret]);
// Saving token of access in Local_Storage
var accessData = {};
accessData.accessTokenKey = accessParams.oauth_token;
accessData.accessTokenSecret = accessParams.oauth_token_secret;
// Configuring Apps LOCAL_STORAGE
console.log("TWITTER: Storing token key/secret in localStorage");
localStorage.setItem(twitterKey, JSON.stringify(accessData));
oauth.get('https://api.twitter.com/1/account/verify_credentials.json?skip_status=true',
function(data) {
var entry = JSON.parse(data.text);
console.log("TWITTER USER: " + entry.screen_name);
$("#welcome").show();
document.getElementById("welcome").innerHTML = "welcome " + entry.screen_name;
successfulLogin();
// Just for eg.
app.init();
},
function(data) {
console.log("ERROR: " + data);
}
);
// Now we have to close the child browser because everthing goes on track.
window.plugins.childBrowser.close();
},
function(data) {
console.log(data);
}
);
}
else {
// Just Empty
}
},
tweet: function() {
var storedAccessData, rawData = localStorage.getItem(twitterKey);
storedAccessData = JSON.parse(rawData); // Paring Json
options.accessTokenKey = storedAccessData.accessTokenKey; // it will be saved on first signin
options.accessTokenSecret = storedAccessData.accessTokenSecret; // it will be save on first login
// javascript OAuth will care of else for app we need to send only the options
oauth = OAuth(options);
oauth.get('https://api.twitter.com/1/account/verify_credentials.json?skip_status=true',
function(data) {
var entry = JSON.parse(data.text);
Twitter.post();
}
);
},
/*
We now have the data to tweet
*/
post: function() {
alert('Post !');
var theTweet = $("#tweet").val(); // You can change it with what else you likes.
oauth.post('https://upload.twitter.com/1/statuses/update_with_media.json',
{
'status': theTweet,
'media': //HERE IS THE PROBLEM, WHAT TO DO HERE ?
}, "multipart/form-data",
function(data)
{
alert('Data 1 !');
console.log('------Data1 : ' + data);
var entry = JSON.parse(data.text);
console.log(entry);
done();
},
function(data) {
//var json_result = JSON.parse(data);
//alert(json_result.text.error);
var entry = JSON.stringify(data);
console.log('------Data2 : ' + entry);
}
);
}
}
function done() {
alert("OKKK !");
$("#tweet").val('');
}
function successfulLogin() {
$("#loginBtn").hide();
$("#logoutBtn,#tweet,#tweeter,#tweetBtn,#tweetText").show();
}
function logOut() {
//localStorage.clear();
window.localStorage.removeItem(twitterKey);
document.getElementById("welcome").innerHTML = "Please Login to use this app";
$("#loginBtn").show();
$("#logoutBtn,#tweet,#tweeter,#tweetText,#tweetBtn").hide();
}
After many tests (sending a base64 image, sending a blob, sending a binary file, ...) here is the return message from Twitter I have :
{\"errors\":[{\"message\":\"Internal
error\",\"code\":131}]}","xml":"","requestHeaders":{"Content-Type":"multipart/form-data"},"responseHeaders":{"date":"Fri,
19 Apr 2013 15:45:28
GMT","content-encoding":"deflate","strict-transport-security":"max-age=631138519","status":"500
Internal Server
Error","server":"tfe","content-type":"application/json;
charset=utf-8","version":"HTTP/1.1"}}
A "solution" (by send a blob) have been posted on the Twitter dev forum but not working for me : dev.twitter.com/discussions/6969
Does anyone want to implement the same feature or have a solution ? Thank you !
------ EDITED :
I just want to use Javascript and I don't want to implement any server-side solution (no PHP, C#, Java...).
According to the docs, Twitter requires the multipart/form-data enctype, which means a base64 string isn't going to work.
Unlike POST statuses/update, this method expects raw multipart data. Your POST request's Content-Type should be set to multipart/form-data with the media[] parameter ~ https://dev.twitter.com/docs/api/1/post/statuses/update_with_media
However, you could host an endpoint that takes base64, converts it to a real file, and forwards the request to Twitter. For example (untested):
<?php
$base64 = $_POST['image'];
$data = base64_decode( $base64 );
// Make name unique to avoid conflicts.
$temp_file = uniqid() . $_POST['name'];
// Save the file to a temp location.
file_put_contents( $temp_file, $data );
$temp_info = pathinfo( $temp_file );
$temp_type = $temp_info['extension'];
$temp_name = basename( $temp_file, '.' . $temp_type );
// OAuth library recommended by Twitter: https://github.com/themattharris/tmhOAuth
// See original: https://github.com/themattharris/tmhOAuth-examples/blob/master/images.php
require 'tmhOAuth.php';
require 'tmhUtilities.php';
$tmhOAuth = new tmhOAuth( array(
'consumer_key' => $_POST['consumer_key'],
'consumer_secret' => $_POST['consumer_secret'],
'user_token' => $_POST['user_token'],
'user_secret' => $_POST['user_secret'],
));
// note the type and filename are set here as well
// Edit: Not sure if the `type` and `filename` params are necessary.
$params = array( 'media[]' => "#{$temp_file};type={$temp_type};filename={$temp_name}" );
$code = $tmhOAuth->request( 'POST', $tmhOAuth->url( '1/status/update_with_media' ),
$params,
true, // use auth
true // multipart
);
// Remove temp file.
unlink( $temp_file );
if ( $code == 200 ) {
tmhUtilities::pr( json_decode( $tmhOAuth->response['response'] ) );
}
tmhUtilities::pr( htmlentities( $tmhOAuth->response['response'] ) );
?>
And you might call it like:
$.ajax({
// You'll want to use https to protect the oauth info.
url: "https://mysite.com/proxy.php",
type: "POST",
data: {
image: "base64 data...",
name: "foo.png",
consumer_key: options.consumerKey,
consumer_secret: options.consumerSecret,
user_token: options.accessTokenKey,
user_secret: options.accessTokenSecret
},
success: function( data ) {
console.log( data );
}
});
For anyone trying to post images to Twitter using client JS, I was able to post to twitter using the solution by gary-buynary-co-za (https://github.com/bytespider/jsOAuth/pull/11) at the end of this forum. Pretty much ended up using Phonegap FileTransfer and FileTransferOptions objects for transferring image to twitter api, but used jsOAuth for preparing FileTransferOptions headers and signatures. The solution could definitely be cleaned up though.