Search code examples
phpjsonajaxslim

Trying to remove value from a JSON file


I'm trying to remove value from a json file with AJAX request, it don't show any error but it don't delete the value, someone can check it? Thanks you!

Before the AJAX function (for insert the ID on the "erase"). (the function deletee(item) click the button that activate the dlt function)

JS:

function deletee(item) {
    var el = document.getElementById('erase');
    el.value = Checker[item].id;
    var r= confirm("Do you want delete it?")
    if (r==true) {
        document.getElementById('rmv').click()
    }

    }

JS AJAX:

        function dlt(item) {
    var iddlt = document.getElementById('erase').value;
    $.ajax({
        type: 'GET',
        url: 'api/delete/'+ iddlt,
        dataType: 'json'
    });

}

php:

$app->get('/delete/{id}', function (array $args) {
$jsonContents = file_get_contents('data/data.json');
$id = $args['id'];
$data_array = json_decode($jsonContents, true);
foreach ($data_array as $key => $value) {
    if ($value['id'] == $id) {
        unset($data_array[$key]);
    }
}
$data_array = array_values($data_array);
file_put_contents('data/data.json', json_encode($data_array));

});


Solution

  • Pass ID to your function and Ajax URL :

    function dlt(item_id) {
        $.ajax({
            type: 'GET',
            url: 'api/delete' + item_id,
            dataType: 'json'
        });
    }