0

I am trying to run an ajax request in CakePHP 2.3. I am working off of this post: simple ajax example with cakephp 2.3.0

I cant get it to work, here is my code:

$("#node-form-save").click(function(){
        event.preventDefault();
        var firstName = $("#node-form-first-name").val();
        var lastName = $("#node-form-last-name").val();
        var dob = $("#node-form-dob").val();
        $.ajax({
            url:'/persons/create',
            type: 'GET',
            datatype: 'json',
            data: {firstName: firstName, lastname: lastName, dob:dob},
            success: function(data){
                alert("succes");
                }
        });
        $('#modal-pop').jqmHide();

    })

I started with a simple test, to see if the sucess function is reached, but I get no alert. What is wrong with my code? The url is correct. The url /persons works, and when I type in /persons/create I get a CakePHP screen saying that I have no view (but I don't want one, I am doing ajax. I list my controller (PersonsController.php) below

class PersonsController extends AppController
{
public $helpers = array('html', 'form');

public function index()
{

}

public function create()
{

}
}

I left the functions blank for now, just so I can get the basic functionality working.

4

3 回答 3

1

第一:为什么“得到”?创建功能似乎超级不安全。改为通过 POST 进行 ajax 调用。

你说你不想要一个视图,但你的代码没有指定。对于 ajax,为了避免渲染视图和布局,请执行此操作

public function create() {
    $this->autoRender = false;
}

此外,如果您这样做,您将不会得到任何回报,因此在操作中,您需要回显这些值,以便 ajax 可以接收它。

还有一个提示,您可以通过简单的检查将您想要使用 ajax 执行的功能和正常方式分开

public function create() {
    if( $this->request->is('ajax') ) {
        $this->autoRender = false;
        echo 'hello result';
        return;
    }

    //else, handle this action as a normal one and render a view and whatever
}
于 2013-06-13T20:00:28.513 回答
0

您需要将“事件”传递给函数:

$("#node-form-save").click(function(event){
        event.preventDefault();
        ...
}
于 2013-06-13T20:14:55.260 回答
0

这就是我这样做的方式。希望它有所帮助

$(document).ready(function() {
    $(".submit").click(function(event){//my submit button has class name 'submit'
        event.preventDefault();

        $.ajax({
            type:"POST",
            url:"/cakephp/messages/create/",
            success : function(data) {
                alert('success');

            }
        });
    });
});

控制器

public function create(){
    if( $this->request->is('ajax') ) {
        $this->autoRender = false;
        echo 'hello result';
        return;
    }
  }
于 2013-06-16T09:45:17.347 回答