CodeIgniter Forums

Full Version: jQuery Ajax and getting the data
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
So I'm building game with HTML5 Canvas and I want to use CodeIgniter for my high score server.  Basically when the game has ended, you're prompted for your name and the game sends your score and name via ajax where it's updated in the db.

this is my controller:

PHP Code:
       public function addScore()
           $score $this->input->post('score');
//$resp['name'] = $name;
           //$resp['score'] = $score;
           if ($this->form_validation->run() !== FALSE
               $resp['success'] = true;

           } else
               $resp['success'] = false;
['name'] = $name;
           $resp['score'] = $score;
            echo json_encode

and this is my ajax call:
function addScore() {
 newScore = {
   name: '"' + $('#name').val() + '"',
   score: '"' + Player.worldPos[1] + '"'
     url: "myGame/addScore/",
     type: 'post',
     contentType: 'application/json',
     data: newScore,
     success: function(data, status, xhr) {
       console.log("connection success"); // for debug, remove for release
     error: function(xhr, desc, err) {
       console.log(xhr); // for debug, remove for release
       console.log("Details: " + desc + "\nError:" + err); // for debug, remove for release
   }); //end ajax

My problem is that I can't get the ajax data from my controller.  $this->input->post('name') is null.  The data is there when I send it out (I console.log'd to make sure I wasn't sending null values).

this is the log:

connection success

So how am I supposed to get the post data in my controller?  I've been pulling my hair out all night... Thanks in advance for any help
Did you make sure you have CSRF disabled? Or at least disable it on that particular url? If you still want to have it enabled I guess you can pass it manually in the ajax code. (

I had the same problem but with angular. So i think that's not a jQuery problem.

oddly, every ajax post was null in CI for me (angular or jQuery). But i found a solution

try to add a Content-Type

(in angular, i do $['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';)

it's solved my problems
keulu, Thank you so much. After 4 hours of changing things back and forth last night I was about ready to give up. It was the content type, I had contentType: 'application/json'; set in the ajax call, changing it to x-www-form-urlencoded fixed this. Thank you!

Avenirer, the game is currently hosted on the same domain, so there's no cross-origin going on at the moment. But thank you for the reply, I need to bookmark that because eventually the game will run from mobile devices with PhoneGap and will have to do some cross-origin requests.