I have only been working with ajax for under a week now trying to use it with codeigniter to create a pretty complex ajax menu system. The user can add new sections to the menu system as they work on it. I have ajax code posting to the database and on success adding it to the menu system. The problem I am having is that the code is running before the update is made to the database. So instead of getting the new menu section I just get a copy of the latest menu before making the addition. If I wait a moment and make the call manually with a button I attached with the ajax call instead of using .done this works fine.
This is my ajax call
// this is attached to my form to add a menu section
$(function(){
$('#add_category_form').submit(function(evnt){
evnt.preventDefault();
var posting = $.post(base_url+"/menu/add_category", $("#add_category_form").serialize());
posting.done(newCategory());
});
//calls view to generate menu section
function newCategory(){
$.ajax({
'url' : base_url + '/' + controller + '/new_category',
'type' : 'POST', //
'success' : function(data){
var container = $('#testcontainer');
if(data){
container.html(data);
}
}
});
}
// view
<?php
$count = count($menu)+1;
$counter=0;
foreach ($menu as $category) {
$counter++;
if ($count == $counter) {
echo "menu html goes here of last menu created";
}
}
?>