Simple Ajax/Codeigniter request

2019-03-02 02:20发布

I'm having some issues with ajax and codeigniter. I've already posted another question (link to question) and I thought I solved it, but I did not so I`m asking someone to write simple code with ajax/codeigniter that will increase number inside div/span on click.

I`m trying last few days to do this, but constantly getting errors..My CI setting are :
base_url : localhost/test/
index:index.php
autoload:url
default controller:welcome (I left it so just for this test)

I would be more than happy to have simple example to do this. I tried also, again, but without any luck. Here's what I tried this time :

Controller (welcome.php)

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Welcome extends CI_Controller {


function __construct()
    {
        parent::__construct();
    }

public function index()
{
    $this->load->view('welcome_message');
}

function increase(){
    $increase = $this->input->post('increase');
    echo increase++;
}
}

JS (Ajax)

function increase(){
var number = parseInt($('#number').html()) + 1;
$.ajax({
        type: 'POST',
        url: 'localhost/test/welcome/increase',
        data: { increase:number },
        success:function(response){
            $('#number').html(response);
        }
});

}

View (HTML/CSS)

<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript"></script>
<script type="text/javascript" src="<?php echo base_url();?>assets/js/jquery_v1.9.1.js"> </script>
<script type="text/javascript" src="<?php echo base_url();?>assets/js/script.js">            </script>
<style type="text/css">
#number {
display: block;
text-align: center;
width: 100px;
height: 30px;
margin: auto auto;
line-height: 30px;
border: 1px solid #999999;
border-radius: 5px;
}

</style>
</head>
<body>
    <span id="number" onclick="increase()">0</span>
</body>
</html>

I'm using latest xampp on windows 7. Error that I get when I click on span - POST http://localhost/test/localhost/test/welcome/increase 404 (Not Found)

8条回答
萌系小妹纸
2楼-- · 2019-03-02 02:27

First You should define your site base_url in application/config file then use this base_url with your ajax page call from where your call goes. Suppose your base_url is http://localhost/test/

function increase(){
   var number = parseInt($('#number').html()) + 1;
   $.post('<?php echo base_url()?>welcome/increase',{number :number},function(response){
          $('#number').html(response);
   });    
}

then change your increase function in controller like this

function increase(){
   $increase = $_POST['number'];
echo increase++;

}

查看更多
疯言疯语
3楼-- · 2019-03-02 02:30

try this :

function increase(){
        var number = parseInt($('#number').html()) + 1;
        $.ajax({
            type: 'POST',
            url: 'localhost/test/Welcome/increase/',
            data: "increase=" + number,
            dataType: "text",
            success:function(response){
                $('#number').html(response);
            }
        });

 }
查看更多
Animai°情兽
4楼-- · 2019-03-02 02:36

use site_url() of codeigniter

 function increase(){
   var number = parseInt($('#number').html()) + 1;  
   $.ajax({
     type: 'POST',
     url: '<?php echo site_url("welcome/increase")?>',
     data: { increse:number }, //<--- here should be increase
     success:function(response){
        $('#number').html(response);
     }
  });

}

however, adding http:// in front of localhost should work

 url: 'http://localhost/test/welcome/increase',

but it is always better and recommended to use site_url() if you are calling a controller in CI...so that this won't give you errors while when you upload it to live server.

查看更多
祖国的老花朵
5楼-- · 2019-03-02 02:37
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript"></script>
<script type="text/javascript" src="<?php echo base_url();?>assets/js/jquery_v1.9.1.js"> </script>
<script type="text/javascript" src="<?php echo base_url();?>assets/js/script.js">            </script>
<style type="text/css">
  #number {
    display: block;
    text-align: center;
    width: 100px;
    height: 30px;
    margin: auto auto;
    line-height: 30px;
    border: 1px solid #999999;
    border-radius: 5px;
  }

</style>
</head>
<script>
function increase(){
  var number = parseInt($('#number').html()) + 1;
  $.ajax({
      type: 'POST',
      url: '<?php echo base_url()?>welcome/increase',
      data: { increase:number },
      success:function(response){
         $('#number').html(response);
      }
  });

}
</script>
<body>
<span id="number" onclick="increase()">0</span>
</body>
</html>
查看更多
欢心
6楼-- · 2019-03-02 02:42

If you are using this ajax in a .php file than you should do something like this to your url:

function increase(){
var number = parseInt($('#number').html()) + 1;
var base_url = "<?php echo base_url();?>";
$.ajax({
    type: 'POST',
    url: base_url+'welcome/increase',
    data: { increase:number },
    success:function(response){
        $('#number').html(response);
    }
  });
}

OR if you are doing this in a .js file than you need to add this line inside your head tag

<script> var base_url = "<?php echo base_url();?>";</script>

And than use this :

function increase(){
var number = parseInt($('#number').html()) + 1;
$.ajax({
    type: 'POST',
    url: base_url+'welcome/increase',
    data: { increase:number },
    success:function(response){
        $('#number').html(response);
    }
  });
}

Hope that it resolves the problem. However, its always a good idea when developing in the local environment to set the base_url in config.php like this :

$root = "http://".$_SERVER['HTTP_HOST'];
$root .= str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']);
$config['base_url']    = $root;
查看更多
Melony?
7楼-- · 2019-03-02 02:44

You must submit the CSRF token from cookies otherwise the request will be invalid, if you have CSRF enabled in config.php.

You can use this plugin to retrieve cookies in javascript. And simply pass it to CI.

ci_token

and

ci_cookie

keys may be different and can be found in config.php

I would also suggest setting up a route for the request and using

site_url()

over

base_url()

var SITE = "<?php echo site_url();?>" // GLOBAL variable so your javascripts can be external

-

var data = { 'ci_token' : $.cookies.get('ci_cookie'), 'increase' : parseInt(number)}
$.ajax({
    url : SITE + "/link/to/controller/method",
    data : data,
});
查看更多
登录 后发表回答