0

Im using cakePHP 2.2.1

I have a GoalsController that has an add action in it. This action saves posted data to Goals table.

Inside the add.ctp im using jQuery ajax method to post the form data to above said add action.

What i want is,

  1. ajax method posts form data to goals/add
  2. goals/add action saves data to goals table
  3. Obtain the id of newly inserted row using $this->Goal->id
  4. Return this id back to the onSuccess function of ajax method

Steps 1,2,3 are working fine. But i dont know how to implement step4.

I know php is server side and js is client side and all. Is there anyway i can achieve this?

1 Answer 1

2

Be sure to read the book entry on Json views and implement something like this:

// Routes.php
Router::parseExtensions('json');

// Controller
$this->set('id', $this->Goal->id);
$this->set('_serialize', array('id'));

// AppController.php
public $components = array('RequestHandler'); // Or add 'RequestHandler' to the existing list.

Then you need to make your ajax post to /goals/add.json, Cake will then recognise the .json extension in combination with the $this->set('_serialize') and return a json string along the lines of { id: 1 }.

Then in your $.ajax function, have a success call like this:

$.ajax({
    url: '/goals/add.json',
    dataType: 'json'
    // other settings
    success: function(response) {
        alert(response.id); // response contains the returned data
    }
});
Sign up to request clarification or add additional context in comments.

7 Comments

Your answer is fine, but don't forget you need to add RequestHandler to your components list
@Dunhamzzz Thanks for the reply. I tried what you advised. But im getting 500 Internal error in Firebug console. This is the resonse:
Ah you'll need to make a view file for your action, just an add.ctp in the normal location. Not ideal as you'll never use it (could use it as a non-javascript fallback)
@José Lorenzo do i need to create an extra file named add.json for this method to work? I currently have put the form elements and ajax code in the add.ctp file.
Sorry you are right, the strange thing is it's looking for a json view file which I thought it would skip doing as you're using $this->set('_serialize', array('id'));. Try making a View/Goals/json/add.ctp and echo json_encode(compact('id')); inside it
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.