CI_Guy
CI_Guy

Reputation: 1039

phonegap with codeigniter backend

So I am getting better at using phonegap but am still trying to fully add codeigniter as the backend. I have been able to .load in jquery something from a controller of my CI to my phonegap android app but can't seem to submit anything TO the server properly. Do you need a rest server to communicate with CI from phonegap? I was planning on using ajax post to info to CI but so far unable to get it to work. I'd really appreciate it someone can help me over this hurdle. Thanks

link to relative answer

Controller:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Welcome extends CI_Controller {


    public function index()
    {
        //$this->load->view('welcome_message');
    $data['query']=$this->site_model->get_last_ten_articles();
$this->load->view('partial1',$data);

    }

    public function addarticle(){
    $headline=$this->input->post('headline');
    $article=$this->input->post('article');
    $this->site_model->insert_entry($headline,$article);    

    }
}

Javascript(on phonegap device)

function add_article(){



$.ajax({
  type: 'POST',
  url: 'http://testlab.site40.net/droiddev/welcome/addarticle/',
  data: {"headline": "test headline","article": "test article"} 
  error: function(){alert('fail');},
  success: function(data){
   alert('article added');
  },
  dataType: "json"
});

}

Upvotes: 4

Views: 3782

Answers (1)

lsl
lsl

Reputation: 4419

First of all, lets get your example running, your post data is json, and the datatype is json but your CI implementation is accessing post variables.

The quick and dirty fix is to submit a uri string in the post data such as:

&headline=test%20headline&article=test%20article

This can be generated from a form with the jquery serialize function:

var myData = $('#form-id').serialize();

This post data will be set in the $_POST var on submission and then later accessible through the CI post function:

$this->input->post()

*Note: remeber to remove the dataType setting in the ajax call for this to work.

For a more politically correct way to solve this problem, you're going to want to leave your javascript alone (thats all good) but you need to set the CI backend up as a RESTful service, the default installed controller and input classes won't handle it. You need to use something like Phil Sturgeon's REST implementation:

  • There is a github project for the code,
  • A blog post (read this first - its a good short primer on REST servers for CI concerned usage),
  • And the tutorial you already know about.
  • Oh and a video on setting it up.

Upvotes: 6

Related Questions