Komarzer Komarzer - 6 months ago 16
PHP Question

PHP update database field without redirecting

I'm using PHP Codeigniter. I have a sidebar in my website that displays every task I have in my database. In the Task table, I have a text column, that I want to be able to update when pressing enter.

The textarea that I want to use to update

What I did at the moment was to create a javascript function that gets called when pressing Enter :

function CursorKeyDown(e, id){
if(e.keyCode === 13){
var text = document.getElementById('area').value;
window.location.href = "<?php echo site_url('task/Task/validSuivi/')?>" + '/' + id + '/' + text;
//window.history.pushState('', '', "<?php echo site_url('task/Task/validSuivi/')?>" + '/' + id + '/' + text);
//alert("Enter was pressed was presses");
}

return false;
}


At the moment if I use window.location.href, it redirects to the link or where my controller wants it. What I want is to call the method, update the database, but no redirection or whatever. Is that possible ? With Ajax ? I tried something with pushstate but it just modifies the URL without triggering the method.

My method in the controller :

public function validSuivi($id_tache, $text)
{
$arr['suivi'] = $text;

$this->task_model->update(array('id_tache'=>$id_tache),$arr);

//redirect('task/task');
}

Answer

Check this code :-

<script>
function CursorKeyDown(e, id){
    if(e.keyCode === 13){
        var text = document.getElementById('area').value;
        var ajax_url = "<?php echo site_url('task/Task/validSuivi/');?>" + '/' + id + '/' + text
        $.ajax({
            url: ajax_url,
            type: "POST",
            dataType: "json",
            data: {},
            success: function (result) {
                console.log('get your response..');
                console.log(result);
            },
            error: function(a,b,c) {
                console.log('error');
            },
            beforeSend:function(jqXHR, plain_jqXHR) {
                console.log('show some loading..');
                console.log('disable button..');
            },
            complete: function() {
                console.log('hide loading..');
                console.log('enable button..');
            }
        }); 
    }
    return false;
}

</script>

if your response not of json comment dataType: "json" in ajax request.

Comments