UPDATE (12/15/2011): Connecting to StackMob with JavaScript (PhoneGap and other cross-domain ajax capable clients)

464 views
Skip to first unread message

Erick Tai

unread,
Dec 15, 2011, 8:13:19 PM12/15/11
to stac...@googlegroups.com
**UPDATE ** This is a new update to connecting to StackMob via JS.  We've updated our request format with new domains and request headers.  Here's the "deprecated" connect-to-stackmob-with-JS writeup.

This example is for applications like PhoneGap whose browsers allow cross-domain ajax calls.  Though, of course, this javascript would run anywhere where you can make cross domain ajax calls. 

StackMob doesn't have an official JS SDK at the moment, but with a bit of JS know-how and some trust StackMob REST API Format docs, you can create objects, fetch, and filter them through StackMob.  I assume that you've already created a StackMob app.

1.  Get the Javascript jsOAuth Library

We start by making sure you've downloaded jsOAuth, a handy JS library that let's us make secure OAuth calls.  OAuth is a security protocol that we use to secure your requests to our servers so that we know that it's you making the calls.  It's like when you show up at the bank and you have to enter your own PIN number to identify it's you.  You're making a URL call to StackMob, but you also need to pass up your OAuth key in order to have your request authorized.  Show up at the bank (URL) without a pin number (OAuth key), and you get no service. :)  So, keep your keys secret please!

Here's a download to the latest version: https://github.com/downloads/bytespider/jsOAuth/jsOAuth-1.3.3.min.js (download me!)

You may find the most up to date version on the jsOAuth github page: https://github.com/bytespider/jsOAuth (optional)

2.  Create a user, then retrieve that user: John Smith

Make sure this page is in the same folder as jsOAuth.

Hint* Chrome doesn't normally allow cross-domain ajax requests, but Rob Griffiths, the author of jsOAuth, had this handy tip so that you can run this on your desktop to test!

You can test in Chrome using the following commandline on OSX /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --disable-web-security --allow-file-access-from-files --allow-file-access --user-data-dir=~/chrome-test/ spec/runner.html

On Ubuntu try /opt/google/chrome/google-chrome --disable-web-security --allow-file-access-from-files --allow-file-access --user-data-dir=~/chrome-test/ spec/runner.html"

<html>
<head>
<script type="text/javascript" src="jsOAuth-1.3.3.min.js"></script>
</head>
<body>

<script type="text/javascript">
/* <![CDATA[ */


var stackmob, keys;

//Find your keys at https://www.stackmob.com/platform/account/apps/reset
//Set your OAuth keys (Use Development Keys)
keys = {
    consumerKey: 'my StackMob public key', //Public Key
    consumerSecret: 'my StackMob private key' //Private Key
};

oauth = OAuth(keys);

/*
    Let's create a user instance. 
    Simple schemas (strings, ints, arrays, etc) are automatically generated on StackMob's end when you POST this.
    Automatic Schema Generation: http://www.stackmob.com/devcenter/docs/Automatic-Schema-Generation
 */
var newUser = { 'username': 'John Smith', 'password': 'opensesame', 'age': 25 };

//Make the REST API POST call to create the user
oauth.request( {
    method : 'POST',
    headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/vnd.stackmob+json; version=0' //If this was an app in production, change version=1 or version=2 as appropriate. 0 is Development
        },
    url : "http://api.mob1.stackmob.com/user",
    data: JSON.stringify(newUser),
    success: function(data) { console.debug(newUser); },
    failure: function(data) { console.error('fail'); console.debug(newUser); }
});



//Now let's fetch that user we just saved
//Let's see a list of ALL users
oauth.request({
    method : 'GET',
    headers: {
        'Accept': 'application/vnd.stackmob+json; version=0' 
    },
    url : "http://api.mob1.stackmob.com/user/John%20Smith",
    success: function(response) { console.debug(JSON.parse(response.text)); },
    failure: function(response) { console.debug(JSON.parse(response.text)); },
});




//Let's see a list of ALL users
oauth.request({
    method : 'GET',
    headers: {
        'Accept': 'application/vnd.stackmob+json; version=0' 
    },
    url : "http://api.mob1.stackmob.com/user",
    success: function(response) { console.debug(JSON.parse(response.text)); },
    failure: function(returnedError) { console.debug(JSON.parse(response.text)); },
});

 
   
/* ]]> */
</script>
</body>
</html>

3.  More REST API Calls

To make your own REST API Calls to filter, paginate, order, look through our docs and check out the REST API Format tabs.  Replicate them in your AJAX and you're good to go!

adam16ster

unread,
Dec 22, 2011, 11:44:37 PM12/22/11
to stac...@googlegroups.com
how to test if on windows?

is the cdata wrap necessary?

javascript sdk on the roadmap? soon?


Erick

unread,
Dec 23, 2011, 12:20:56 AM12/23/11
to stac...@googlegroups.com
Hi Adam, no I don't believe the CDATA wrap is necessary.  It's just a form of habit for me.  

I saw this for Windows when googling your question.  This oughta work I hope?


I'm writing a JS SDK over the holidays, but I wouldn't recommend it for web use since your OAuth keys will be in the open.  It's more for use in Phonegap where the keys are hidden - and as a springboard for me to dive into Titanium.  

May I ask where you were going to use the SDK?

adam16ster

unread,
Dec 23, 2011, 12:35:37 AM12/23/11
to stac...@googlegroups.com
thanks for the link, i'll give it a shot soon.  

i'm trying to integrate with gotiggr.  inspired by this post, http://mkblog.exadel.com/2011/12/truly-rapid-mobile-apps-prototyping-with-stackmob-and-tiggr/

the problem may lie with gotiggr however and not stackmob or the jsoauth script.

Erick

unread,
Dec 23, 2011, 1:08:15 AM12/23/11
to stac...@googlegroups.com
Cool - I gave them a tweet to see if they could give you a hand.  Lemme know how it goes!  They just tweeted this too, coincidentally:

"Need help building your mobile app in Tiggr?http://gotiggr.com/forum or email us at support @ gotiggr.com"

maxim...@gmail.com

unread,
Dec 23, 2011, 1:49:23 AM12/23/11
to stac...@googlegroups.com
We'll try out the script in Tiggr...and report back

Max

Erick

unread,
Dec 23, 2011, 2:29:59 AM12/23/11
to stac...@googlegroups.com
You rock, Max!  

adam16ster

unread,
Dec 23, 2011, 5:33:03 PM12/23/11
to stac...@googlegroups.com
using the script in tiggr, this is the first error in the console:
Failed to load resource: the server responded with a status of 404 (Not Found)
http://api.mob1.stackmob.com/user


is that the url i should be using to access the stackmob api?  i've seen examples where the url includes other things like app name.

i'm working with max simultaneously on this.  thanks for your help thus far.  both of you have been extremely helpful and responsive.

Erick

unread,
Dec 23, 2011, 5:56:01 PM12/23/11
to stac...@googlegroups.com
Of course Adam, we're happy to help. 

Have you set your keys properly?  That would look like something failing on our request.  But since you get a 404 at least you're hitting the server.

//Find your keys at https://www.stackmob.com/platform/account/apps/reset
//Set your OAuth keys (Use Development Keys)
keys = {
    consumerKey: 'my StackMob public key', //Public Key 
    consumerSecret: 'my StackMob private key' //Private Key
};

The URL is ok.  We modified the URL format to be the one you see above.  We route your calls given your OAuth keys, which you may find at:


Would you be willing to email me your code and I can double check your code?  You can always change/reset your keys later if you'd like to be the only one who knows how to access your API.

Erick

unread,
Dec 23, 2011, 5:57:05 PM12/23/11
to stac...@googlegroups.com
To clarify, yes, there used to be a URL that had the app name included in it (which still works by the way), but this simplified URl is the one we're moving to, and we're aware of your app name via your OAuth keys.

adam16ster

unread,
Dec 23, 2011, 6:09:29 PM12/23/11
to stac...@googlegroups.com
pretty much a copy/paste from your script, except i injected my development keys.

CODE:

var stackmob, keys;

//Set your OAuth keys (Use Development Keys)
keys = {
    consumerKey: '####################################', //Public Key 
    consumerSecret: '###################################' //Private Key

adam16ster

unread,
Dec 23, 2011, 6:14:32 PM12/23/11
to stac...@googlegroups.com
not sure if you or max have changed anything but the first error message has changed slightly without any change in code:

  1. OPTIONS http://api.mob1.stackmob.com/user 404 (Not Found)
    1. g.init.requestasset-1266329:2
    2. (anonymous function)

Taylor Leese

unread,
Dec 23, 2011, 6:19:01 PM12/23/11
to stac...@googlegroups.com
Adam - Are you including the StackMob accept header in your request? That could potentially cause the 404 if omitted.

Accept: application/vnd.stackmob+json; version=X (where X is your API version number)

- Taylor

--
You received this message because you are subscribed to the Google Groups "StackMob" group.
To view this discussion on the web visit https://groups.google.com/d/msg/stackmob/-/z46blR2i5IMJ.

To post to this group, send email to stac...@googlegroups.com.
To unsubscribe from this group, send email to stackmob+u...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/stackmob?hl=en.

Erick Tai

unread,
Dec 23, 2011, 6:19:55 PM12/23/11
to Taylor Leese, stac...@googlegroups.com
For development, version=0

adam16ster

unread,
Dec 23, 2011, 6:25:28 PM12/23/11
to stac...@googlegroups.com, Taylor Leese
in the code i pasted above:

 'Accept': 'application/vnd.stackmob+json; version=0' 

Erick Tai

unread,
Dec 23, 2011, 6:33:05 PM12/23/11
to stac...@googlegroups.com, Taylor Leese
oh haha, Google conveniently collapsed your code so that we didn't see anything beyond the keys (facepalm)

k lemme see what's going on


On Fri, Dec 23, 2011 at 3:25 PM, adam16ster <adamacos...@gmail.com> wrote:
in the code i pasted above:

 'Accept': 'application/vnd.stackmob+json; version=0' 

--
You received this message because you are subscribed to the Google Groups "StackMob" group.
To view this discussion on the web visit https://groups.google.com/d/msg/stackmob/-/sMS6MOK2tD8J.

Erick

unread,
Dec 23, 2011, 6:49:25 PM12/23/11
to stac...@googlegroups.com, Taylor Leese
I took your code and copy pasted it back into mine.  I put in my development keys and it worked.  If I pass the incorrect OAuth keys, I get 404s.  I tried 2 apps and got it to connect.  

I'm sure you're as good at copy and pasting as I am (I have years of intense training in copy/paste), so I'm wondering what else is going on.

What browser are you using?  IE?  Wish I had my Windows machine so I could test it here at work.  

adam16ster

unread,
Dec 23, 2011, 11:05:01 PM12/23/11
to stac...@googlegroups.com, Taylor Leese
Chrome on Windows 7.  I've also tried IE and FF.  I've also tried to test on my phone through tiggr and appmobi but no luck. 

Erick Tai

unread,
Dec 24, 2011, 5:01:08 AM12/24/11
to stac...@googlegroups.com, Taylor Leese
k, I'm going to email you directly so that we can dive in deeper Adam!

Erick Tai

unread,
Dec 24, 2011, 5:38:25 AM12/24/11
to stac...@googlegroups.com
I just discovered after trying the above on my Windows machine at home that you need to do the following to allow cross domain on Chrome in windows.

1.  Close all Chrome browsers
2.  Find where your Chrome is and go to that folder in the command line (I found my path by right clicking on the Chrome shortcut and clicking properties.
3.  Run this:  chrome.exe --args --allow-file-access-from-files --disable-web-security 
4.  Load your HTML/JS file that makes the ajax calls.  
5.  Things should work!

Key step is to close all your Chrome browsers before you start.  If you leave any open before you start an instance of Chrome with the disabled web security in step 3, it apparently won't work.  Instead, you will get 404s and get some Origin: null errors telling you you can't make cross domain calls, etc.

This was run on my now old school Windows XP Professional laptop with Chrome 16.0.912.63

adam16ster

unread,
Dec 24, 2011, 3:27:40 PM12/24/11
to stac...@googlegroups.com
its glorious! ok so closing all chrome browsers did the trick BUT i had to take it half a step further and end all chrome processes in the task manager that they stealth-ily leave running!  sheesh that was rough lol. it fixed all issues.  i got it to work with gotiggr, appmobi, standalone, etc... 

thank you so much for your help. this is one of the best christmas gifts i've received so far :)

Erick Tai

unread,
Dec 24, 2011, 8:41:13 PM12/24/11
to stac...@googlegroups.com
Sweet!

I'm guessing that doing this in Chrome will only be for development purposes?  I'm assuming goTiggr/appmobi will eventually get your code deployed onto devices that allow cross domain calls automatically without special restarts, quitings, hoop jumping etc?  


adam16ster

unread,
Dec 24, 2011, 10:53:07 PM12/24/11
to stac...@googlegroups.com
correct and correct. i've tested my tiggr app on my evo with no hiccups.

things will get easier as tiggr will officially support oauth soon and appmobi has its own oauth api already.

Erick Tai

unread,
Dec 25, 2011, 12:25:39 AM12/25/11
to stac...@googlegroups.com
Great to hear!  Adam, thanks for spending your holiday time with us :)  if you have any other questions, feel free to open a new Google Group thread, and we'll be on it.

Happy holidays! 

Erick


On Sat, Dec 24, 2011 at 7:53 PM, adam16ster <adamacos...@gmail.com> wrote:
correct and correct. i've tested my tiggr app on my evo with no hiccups.

things will get easier as tiggr will officially support oauth soon and appmobi has its own oauth api already.

--
You received this message because you are subscribed to the Google Groups "StackMob" group.
To view this discussion on the web visit https://groups.google.com/d/msg/stackmob/-/dQx_6sWdQsMJ.

CJ

unread,
Oct 5, 2012, 11:48:19 PM10/5/12
to stac...@googlegroups.com
I'm having the same issue with appmobi, I'm getting error: "Not Found" with the normal test code:

Erick

unread,
Oct 12, 2012, 11:26:14 AM10/12/12
to stac...@googlegroups.com
Hi CJ!  This is probably because you're using AppMobi.  My suspicion is that the JS SDK doesn't realize it's on AppMobi and is hence making AJAX calls to a relative URL ( "/user") rather than a full path ("https://api.stackmob.com/user")  

May you try this?

StackMob.init({
  ...
  ...
})

Also if AppMobi needs to whitelist external domains, please add that.  Let me know how that goes.

Erick
Reply all
Reply to author
Forward
0 new messages