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.