hzq hzq - 7 months ago 30
PHP Question

Posting data to controller using AJAX not working, Code Igniter

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/';

url: page,
type: 'POST',
data:{ nameA : name1},
success:function(data) {
error: function(){


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

echo "Name: $name";


<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
dialog. However, what I'm getting is
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.


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:

$('#add_user_form').on('submit', function(form){
$.post('<?php echo base_url();?>/index.php/User/add_this_user', $("#add_user_form").serialize(), function(data){

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.


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