开发者

How to call a php controller method using jquery?

I am developing a web application and i am integrating jquery in it... Now looking for ajax calls with jquery to my controller function....

jquery.ajax() would be useful i think so... But how to call my controller method....

$.ajax({
        type: "POST",
        url: "http://localhost/codeigniter_cup_myth_new/index.php/libraryController/loadbookdetails",
        data: "",
        contentType: "application/json; charset=utf-8",
        async: false,
        dataType: "开发者_StackOverflow中文版json",
        success: function(jsonObj) {

function loadbookdetails()
{
    //Paging 
        $college=$_SESSION['college'];
        $this->load->library('pagination');
        $data['bookdetails'] = $this->librarymodel->selectbook($college);
        //$data['rackOptionData'] = $this->librarymodel->selectrack();
         if(empty($data['bookdetails']))
          {
             $data['comment'] = 'no record found!';
          }

        $this->load->view('bookdetials',$data);
}

I am fetching this records here how to use it with jquery.ajax() function and how to convert $data to json and use it with jquery and iterate with a table...


You can't directly interface jQuery to PHP functions, because they don't run at the same time: PHP is executed on the server side (and usually generates the HTML page), jQuery is run on the client side.

You would have jQuery make an Ajax call to a PHP page's URL. That PHP page would the desired controller, and perform the requested action(s).

Whether there is a pre-defined way to do that depends on what PHP Framework you are using (if any).


For PHP >= 5.2.0, you can use json_encode(). Your code would look like this:

$this->load->view('bookdetails', json_encode($data));

A good collection of references on CodeIgniter + AJAX can be found here.


if you already have your view/bookdetials.php Then everything you need is (instead of your javscript code):

Add div somewhere on the page like this:

<div id="ajax-palaceholder"></div>

and then add this javascript code:

<script type="text/javascript">
$(document).ready({
  $('#ajax-palaceholder').load('http://localhost/codeigniter_cup_myth_new/index.php/libraryController/loadbookdetails');
});
</script>

This will do ajax request on page load and then put loaded content into div#ajax-palaceholder


Ajax request have to contact with php script. That script have to return data. You are using json as response format:

dataType: "json",

So for your example only output form script have to be json. And it cannot be anything more than json.

Your serwer script (bookdetials view) will look like:

  //Initialise data
  $bookdetails = ...
  // json encode data
  echo json_encode( $bookdetails );
  // make sure nothing else go to the output
  ???

??? - depends on system. Usually you will have to block pagelayout here.

json as response is nice but for most cases HTML is enought...

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜