xhr status 0 ajax

0

I have a script where I use ajax that does not go into success

$.ajax({

    data: parametros,
    url: '../gestionUsuario/insertUsuario.php',
    type: 'post',

    success: function(response) {
        alert("hola success");
        if (response == 1) {
            alert("insertado");
            //$('#success_message').html('<h3>USUARIOS INSERTADO</h3>');
        } else {
            alert("no insertado");
            //$('#success_message').html('<h3>ERROS INSERCCION</h3>');
        }
    },
    error: function(xhr, ajaxOptions, thrownError) {
        alert("estatus " + xhr.status);
        alert("estatus " + xhr.responseText);
        alert("error " + thrownError)
    } 

The route is fine since the php inserts me into the database but the answer enters error and the status shows 0.

    
asked by aitorlv 12.02.2018 в 18:44
source

1 answer

0

I recommend you check what the PHP code is returning, in the case of the example I have tried creating a php file with content 1 and it works correctly, I also tested it with 0 and it works well on my localhost.

I recommend using console.log (response) in order to find out what php is returning

var parametros = {
                "id" : 1,
                "nombre" : "Manuel",
        };
$.ajax({

    data: parametros,
    url: 'insertUsuario.php',
    type: 'post',
    beforeSend: function () {
                    console.log('Se inicia la petición');
    },
    success: function(response) {
        console.log(response);
        alert("hola success");
        if (response == 1) {
            alert("insertado");
            //$('#success_message').html('<h3>USUARIOS INSERTADO</h3>');
            }else{
            alert("no insertado");
            //$('#success_message').html('<h3>ERROS INSERCCION</h3>');
        }
    },
    error: function(xhr, ajaxOptions, thrownError) {
        alert("estatus " + xhr.status);
        alert("estatus " + xhr.responseText);
        alert("error " + thrownError);
    }   
});

the answer must be done with print or echo since javascript what you read is the generated flat text, in the previous comment it shows a way to find out if the query was done correctly with affected_rows

if (mysqli_affected_rows($con)>0) { return 1; } else { return 0; } 

However for an ajax request it is recommended to do the following

if (mysqli_affected_rows($con)>0) { echo 1; } else { echo 0; } 
    
answered by 12.02.2018 / 22:58
source