Rodrigo Souza
Rodrigo Souza

Reputation: 7332

How to handle form render and ajax response in the same action?

I have the create() method in my ProjectsController which renders a form and save its data using AJAX:

class ProjectsController extends AppController
{    
    public function create()
    {
        if ($this->request->is('post'))
        {
            $this->Project->create();
            $this->request->data['Project']['created_by'] = $this->Auth->user('id');
            if ($this->Project->save($this->request->data))
            {
                ...
            } else {
                ...
            }
        }

    }

How can i just pass a success message if the data is saved and also render my form if it's not an ajax request? I can't set autoRender false 'cause it has to render the form yet

Is it the most correct way for handling jax request? What should I do if not?

Upvotes: 1

Views: 122

Answers (1)

Dave
Dave

Reputation: 29121

Detecting AJAX:

You can use:

if($this->request->is('ajax')) {

to do whatever you'd like w/ ajax, and the obvious 'else' to do the rest.

Dealing with it:

Probably something like this:

if ($this->request->is('ajax')) {
    //process the ajax response
    $this->render('/Ajax/json');

} else {
    if($this->request->is('post')) {
        //process the post
    }
    //set variables for the view...etc etc

}

Another option - separate functions:

Or, it's also fairly common just to have two different actions - one for ajax and one for anything else you want. This is the way I like it because I'd rather not have if() blocks all over. But - to each their own, and I've seen both used regularly.

public function create_ajax() { ... }

public function create() { ... }

Upvotes: 1

Related Questions