Post with Ajax always gives an error but it still works

2

SOLUTION: One of the given solutions (which was the one that worked for me was to eliminate dataType : 'json', then if the route remains as in my case /search/search/undefined that I solved changing window.location.href = response.redirect; per window.location.href = ''; .

I have the following code in which I first obtain in an array the selected checkboxes to then make a Post of said data that all it does is change the state in the database, that is, the default fields are found in the database with the value "Active" and the idea is that after having selected several of them in the form and clicking on the "Archive" button the status of the fields in the database change to "Archived" what I do not know is why the function never enters Success, always gives an error and triggers the "Does not work" alert but if I reload the page or go to the bd the value of the fields changed successfully, does anyone know what can be owed that? thanks in advance.

CODE OF FORM FOR THE PART OF THE CHECKBOX:

<ul id='listResult'>
    <?php for($i=0;$i<count(1);$i++)
    {
        ?>
        <li><input id ='opt'type='checkbox' name='opt' value='<?= $dato['id']?>'><?= $dato['desc'].' - '.$dato['date'].' - '.$dato['status']?></li>
        <?php
    }
    ?>
</ul>

CODE PART OF THE AJAX:

function archivar()
{
    var busquedas = [];
    $('#listResult input[type=checkbox]:checked').each(function()
    {
        busquedas.push($(this).attr('value'));
    });
    if(busquedas.length>0)
    {
        $.ajax({
            url : 'search/search',
            data : {opt:busquedas},
            type : 'POST',
            dataType : 'json',

            success : function(response){
                window.location.href = response.redirect;
                alert("funciona");
            },
            error: function(error){
                alert("No funciona");
            }
        });
    }
}
    
asked by Ccccccccc 12.09.2017 в 13:52
source

1 answer

2

The problem is that when you put dataType : 'json' you are telling jQuery that a valid JSON should be expected as a response, otherwise it will be taken as if it were an error response

What you should check is the response that the server gives you. And you must validate that this response is a valid JSON. To try it in a simple way, remove the dataType : 'json' and you have a console.log of the answer, like this:

$.ajax({
    url : 'search/search',
    data : {opt:busquedas},
    type : 'POST',

    success : function(response){
        console.log(response);
        //window.location.href = response.redirect;
        alert("funciona");
    },
    error: function(error){
        alert("No funciona");
    }
});
    
answered by 15.09.2017 / 19:08
source