简体   繁体   中英

Ajax Query using CodeIgniter?

I am currently developing a website and was using strictly PHP, after a few hours of development I am noticing I really need to perform AJAX queries. However I am using CI and slightly confused on how I call Ajax queries - especially to a controllers method. I am looking to post data using the query,I have found the following using Jquery:

$.ajax({
  type: "POST",
  url: url,
  data: data,
  success: success,
  dataType: dataType
});

but if I had a controller called main and method called postBack() - how would I pass postback() the data?

Could anyone point me in the right direction it would be much appreciated - apologies if this is extremely simple to say I am a newbie is an understatement.

Here is a Codeingiter/Jquery function pair that I wrote not long ago:

Javascript:

var BASE_URL = <?php echo base_url(); ?>
var stuff = "";

 $('div.get_this').each(function(){
    if(stuff ){
        stuff = stuff + '-';
    }
    stuff = stuff + $(this).html();
});

$.ajax({
  type: "POST",
  url: BASE_URL+"gate",
  data: {'data':stuff},
  success: function(data){
    ...
  });
});

Codeigniter Controller:

class Gate extends CI_Controller {

    public function index(){

        if(isset($_POST['data'])){

            $data = explode('-', $_POST['data']);

In Ci u will use Ajax the for the URL part u will add the controller function name example var URL="HOME SITE URL"+"main/post Back"; //here main is controller and post Back is function that u want to call like below. $Ajax({ type: "POST",URL: URL,data: {star: 3},success: success,data Type: data Type }); and after that in post Back function in controller we used function post Back() { $variable1 = $_POST["star"]; //or $_GET["star"] or $this->input->post('star'); }

class MyClass extends MyController {

    function postBack(){
        //dosomething with post data
        $postdata = $this->input->post();
        $somearray = filter_something($postdata);
        //this is where you return the output to jQuery. you output a string in JSON format 
        echo json_encode($some_array);
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM