0

I just started on PHP OOP and currently using Code Igniter framework. I am having some problems sending data over to the controller using AJAX so I've came up with the most simplest way I could to test whether AJAX is working or not, which is not working.

External JS file:

function confirm_add_user()
{
    var name1 = $("#name").val();
    var page = base_url+'User/test/';

    $.ajax({
        url: page,
        type: 'POST',
        data:{ nameA : name1},
        success:function(data) {
            alert("Pass");
        },
        error: function(){
            alert("Fail");
        }
    });
}

Controller:

public function test()
{
    $name = $this->input->post('nameA');

    echo "Name: $name";
}

View:

<button type="submit" class="btn btn-primary" id="submit" onclick="confirm_add_user()">Submit</button>

Checks I've done:

1. JQuery file is linked.
2. name1 or $("#name").val() gets the correct data from it's text input field.
3. Base_url is the correct url.

So correct me if I'm wrong here, when the submit button is clicked by right it should alert/pop up a Pass dialog. However, what I'm getting is Fail whereby I indicated the alert if the ajax should fail. Been trying to solve for quite a while but I've yet to reach to any conclusion for the problem so I've come to stackoverflow for guidance and assistance. Any help on what might or could be the problem?

My main goal is to be able to load a view on the current page(not sure if it's the right way to put it) but I have yet to progress because I can't send any data over from my form input fields to the controller function.

Edit:

After some time of trying out I found out that when I code the js directly in the view, specifically using these codes, it works:

$(document).ready(function(){
    $('#add_user_form').on('submit', function(form){
        form.preventDefault();
        $.post('<?php echo base_url();?>/index.php/User/add_this_user', $("#add_user_form").serialize(), function(data){
            $('div.test').html('gaefwef');
        });
    });
});

However when I use it in an external js file it doesn't. I've tried a test function just to see whether the js file is properly linked by using an alert and it did so the problem still lies somewhere in the ajax. Is it because of the prevent default for the form? I'm not too sure. Still experimenting for now.

kross
  • 475
  • 1
  • 11
  • 31

6 Answers6

0

Please check you have enabled csrf protection or not. If you have enabled csrf verification then you have to pass CSRF Token in post field.

Vishal Rambhiya
  • 741
  • 6
  • 10
0

remove type='submit' in button. it actually submits ur form in default way, so update ur button tag with type='button' and it will work

<button type="button" class="btn btn-primary" id="submit" onclick="confirm_add_user()">Submit</button>

and in ur javascript ajax function

update this line

data:{"nameA":name1},
Nagesh Sanika
  • 1,090
  • 1
  • 8
  • 16
  • Hmmm I ticked your answer just now because it works, but now I can't submit my form. Is there a workaround? – kross Sep 06 '15 at 23:36
  • It's alright I realized this is the part where I have to post the data over. Thanks – kross Sep 06 '15 at 23:54
0

Try that:

function confirm_add_user()
        {
            var nameA = $("#name").val();

            $.ajax({
                url: "<?php echo base_url() ?>User/test/" +nameA,
                type: 'POST',
                data:{},
                success:function() {
                    alert("Pass");
                },
                error: function(){
                    alert("Fail");
                }
            });
        }
davidev
  • 314
  • 9
  • 22
0

i think your mistake in creating data json use below code, json key must be in double quote then you able to receive the post key

function confirm_add_user(){
var name1 = $("#name").val();
var page = base_url+'User/test/';

$.ajax({
    url: page,
    type: 'POST',
    data:{ "nameA" : name1},
    success:function(data) {
        alert("Pass");
    },
    error: function(){
        alert("Fail");
    }
});    }
Murtuza Zabuawala
  • 318
  • 11
  • 17
0

Try something like this if you have enable CSRF protection.

function confirm_add_user(){

        $.ajax({
            url: '<?php echo base_url() ?>User/test',
            type: 'post',
            data: {
                nameA: $('#name').val(),
                <?php echo $this->security->get_csrf_token_name();?>: '<?php echo $this->security->get_csrf_hash();?>'
            },
            success: function (data) {
                console.log(data);
            },
            error: function(xhr, desc, err){
                console.log(err);
            }
       });
    }
Aditya Lepcha
  • 194
  • 1
  • 1
  • 11
  • Nope, sorry I'd have to research more on CSRF protection first before trying this out because I've no clue what that is. – kross Sep 04 '15 at 17:14
0

I am guessing that you want to send data as json. CodeIgniter doesn't know how to do that so you need to fetch the request data differently.

jQuery does some under the hood tricks and transforms your data into form-data-x, that's why it worked in your second trial.

The solution is to use $this->input->raw_input_stream to fetch your JSON and decode it using php's json_decode. Check the full answer and code below:

Retrieve JSON POST data in CodeIgniter

Community
  • 1
  • 1
jimasun
  • 604
  • 9
  • 12