Luis Liz
Luis Liz

Reputation: 1959

jQuery is not sending data to codeigniter

I am trying to get ajax working with a codeigniter installation.

This is my PHP function:

    function test() {
            return print_r("hey");
    }

This is the JS:

    $.ajax({
          type: "POST",
            url: "http://localhost/code/test",
            success: function(data) {
                    alert(data);    
            }
    });

This works perfectly but, as soon as I add data it doesn't work.

    $.ajax({
          type: "POST",
            url: "http://localhost/code/test",
            data: {bar:"foo"}, 
            success: function(data) {
                    alert(data);    
            }
    });

Thanks in advance!

Upvotes: 0

Views: 193

Answers (3)

Haso Keric
Haso Keric

Reputation: 271

Try the following:

$.ajax({
    type: "POST",
    url: "http://localhost/code/test",
    data: "bar=foo&name=cyberbob", 
    success: function(data) {
            alert(data);    
    }
});

Upvotes: 1

Code Prank
Code Prank

Reputation: 4250

Use following:

$.ajax({
          type: "POST",
          url: "http://localhost/code/test",
          dataType: 'json',
          data: {'bar':'foo'},
          success: function(data) {
                  alert(data);    
          }
    });

Or you can use shorthand version:

$.post("http://localhost/code/test", {'bar':'foo'}, function(data) {
    alert(data);
});

And your php code should be:

function test() {
    echo "hey";
}

Upvotes: 2

Hasib Tarafder
Hasib Tarafder

Reputation: 5813

please check the following

$.ajax({
          type: "POST",
            url: "http://localhost/code/test",
            data: "&bar=foo&isAjax="+true, 
            success: function(data) {
                    alert(data);    
            }
    });

And controller...

function test() {
            if($this->input->post('isAjax')){
                  return print_r("hey");
            }
            else{
                  //do another thing
            }

    }

And another thing if you want to add data in json format then you have to add another property in your $.ajax object that is datatype: "json"

Upvotes: 4

Related Questions