开发者

How do I perform a jQuery ajax request in CakePHP?

I'm trying to use Ajax in CakePHP, and not really getting anywhere!

I have a page with a series of buttons - clicking one of these should show specific content on the current page. It's important that the page doesn't reload, because it'll be displaying a movie, and I don't want the movie to reset.

There are a few different buttons with different content for each; this content is potentially quite large, so I don't want to have to load it in until it's needed.

Normally I would do this via jQuery, but I can't get it to work in CakePHP.

So far I have:

In the view, the button control is like this:

$this->Html->link($this->Html->image('FilmViewer/notes_link.png', array('alt' =>  __('LinkNotes', true), 'onclick' => 'showNotebook("filmNotebook");')), array(), array('escape' => false));

Below this there is a div called "filmNotebook" which is where I'd like the new content to show.

In my functions.js file (in webroot/scripts) I have this function:

function showNotebook(divId) {
 // Find div to load content to
 var bookDiv = document.getElementById(divId);
 if(!bookDiv) return false;
 $.ajax({ 
   url: "ajax/getgrammar",
   type: "POST",
   success: function(data) {
    bookDiv.innerHTML = data;
   }
  });
 return true;
}

In order to generate plain content which would get shown in the div, I set the following in routes.php:

 Router::connect('/ajax/getgrammar', array('controller' => 'films', 'action' => 'getgrammar'));

In films_controller.php, the function getgrammar is:

  function getgrammar() {
   $this->layout = 'ajax';
   $this->render('ajax');
  }

The layout file just has:

and currently the view ajax.ctp is just:

<div id="grammarBook"开发者_如何学Go>
 Here's the result
</div>

The problem is that when I click the button, I get the default layout (so it's like a page appears within my page), with the films index page in it. It's as if it's not finding the correct action in films_controller.php

I've done everything suggested in the CakePHP manual (http://book.cakephp.org/view/1594/Using-a-specific-Javascript-engine).

What am I doing wrong? I'm open to suggestions of better ways to do this, but I'd also like to know how the Ajax should work, for future reference.


everything you show seems fine. Double check that the ajax layout is there, because if it's not there, the default layout will be used. Use firebug and log function in cake to check if things go as you plan.

A few more suggestions: why do you need to POST to 'ajax/getgrammar' then redirect it to 'films/getgrammar'? And then render ajax.ctp view? It seems redundant to me. You can make the ajax call to 'films/getgrammar', and you don't need the Router rule. You can change ajax.ctp to getgrammar.ctp, and you won't need $this->render('ajax');


this is ajax call

$(function() {
    $( "#element", this ).keyup(function( event ) {
        if( $(this).val().length >= 4 ) {
            $.ajax({                   
                url: '/clients/index/' + escape( $(this).val() ),
                cache: false,
                type: 'GET',
                dataType: 'HTML',
                success: function (clients) {
                    $('#clients').html(clients);
                }
            });
        }
    });
});

This the action called by ajax

public function index($searchterm=NULL) {

if ( $this->RequestHandler->isAjax() ) {

        $clients=$this->Client->find('list', array(
            'conditions'=>array('LOWER(Client.lname) LIKE \''.$searchterm.'%\''),
            'limit'=>500
        ));

        $this->set('clients', $clients);
}

}


This is a function I use to submit forms in cakephp 3.x it uses sweet alerts but that can be changed to a normal alert. It's very variable simply put an action in your controller to catch the form submission. Also the location reload will reload the data to give the user immediate feedback. That can be taken out.

$('#myForm').submit(function(e) {
    // Catch form submit
    e.preventDefault();

    $form = $(this);
    // console.log($form);
    // Get form data
    $form_data = $form.serialize();
    $form_action = $form.attr('action') + '.json';
    // Do ajax post to cake add function instead
    $.ajax({
        type   : "PUT",
        url    : $form_action,
        data   : $form_data,
        success: function(data) {
            swal({
                title: "Updated!", 
                text: "Your entity was updated successfully", 
                type: "success"
            },
            function(){
                    location.reload(true);
            });
        }
    });
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜