Upgrade Your Drupal Skills

We trained 1,000+ Drupal Developers over the last decade.

See Advanced Courses NAH, I know Enough

Creating nodes with services module

Parent Feed: 

So, today i decided to have a go at the services module, to make an app post nodes to my site. With services module enabled you can do a number of things from non-drupal sites, for example you can post nodes through your phonegap app by javascript. And that is exactly what i wanted to do today.

Ok here is the javascript code, the services part of it is pretty straight forward to set up anyway, but finding how to create nodes with json and javascript was not that easy. You can probably figure out how to log in based on this, and this snippet posts to a content type with a geofield, and posts the users location onto my server, along with some other values.

function getLocationAndPost() {
  'use strict';
  navigator.geolocation.getCurrentPosition(function (position) {
    var url = 'http://example.com/enpoint' + '/node.json'; //endpoint URL
    var lat = position.coords.latitude;
    var lon = position.coords.longitude;
    var date = new Date();
    var timestamp = Math.round(date.getTime() / 1000);
    var node_object = {
      "type": "some_type", //set this to your content type
      "uid": 1,  
      "field_geo": { "und": { 0 : { //my geofield is called field_geo
        "wkt": "POINT (" + lon + " " + lat + ")",
        "geo_type": "point",
        "lat": lon,
        "lon": lat,
        "top": lon,
        "bottom": lon,
        "left": lat,
        "right": lat } }
      },
      "title": "Big brother sees you",
      "body": { "und": { 0 : { "value": "Put some body value here if you want" } } },
      "created": timestamp, 
      "status": 1 // Set to 1 for Published. O for unpublished.
    };
    $.ajax({
      url: url,
      type: "POST",
      data: node_object,
      success: function() {
        alert('Success!');
      }
    });
  });
}
Remember, in phonegap, this should be fired when phonegap has loaded! Also, this entire thing is wrapped in the geolocation success function, just for shorter code. You probably want to have this as a named function, as well as an error function
Original Post: 

About Drupal Sun

Drupal Sun is an Evolving Web project. It allows you to:

  • Do full-text search on all the articles in Drupal Planet (thanks to Apache Solr)
  • Facet based on tags, author, or feed
  • Flip through articles quickly (with j/k or arrow keys) to find what you're interested in
  • View the entire article text inline, or in the context of the site where it was created

See the blog post at Evolving Web

Evolving Web