API FAIL
Aletvia

Hi, I'm try to send a json with the score of my game to an API made with PHP but ever can`t success. I tested my API in Postman and It's correct. Someone has do it lately? I did 2 years ago but now not work. First i had problems with CORS but now i only get the code 500. Equal I try with others API but is the same. I let you my code. Help :(

==========================GAME==========================

$.ajax({
    data: {
                    'juego':'juego',
                    'jugador':'nombre',
                    'nivel':'1',
                    'tiempo':'00:00:00',
                    'fecha':'00/00/0000'
                },
    dataType: 'application/json',
    url: 'https://jugandoyaprendiendo.000webhostapp.com/_crear_registro.php',
    type: 'POST',
    success: function (result) {
        alert(result);
    },
    failure: function (errMsg) {
        alert(errMsg);
    }
});

==========================API==========================

<?php
/**
 * Insertar una nueva meta en la base de datos
 */
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
header("Allow: GET, POST, OPTIONS, PUT, DELETE");
header("Content-Type: application/json; charset=utf-8");

require '_registro.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Decodificando formato Json
    $JSONData = file_get_contents("php://input");
    $body = json_decode($JSONData);
    $retorno = Registro::insert(
        $body->juego,
        $body->jugador,
        $body->nivel,
        $body->tiempo,
        $body->fecha);

    echo $retorno;
    if ($retorno) {
        echo 'exito';
        // Código de éxito
        print json_encode(
            array(
                'estado' => '1',
                'mensaje' => 'Creación exitosa')
        );
    } else {
        echo 'error';
        // Código de falla
        print json_encode(
            array(
                'estado' => '2',
                'mensaje' => 'Creación fallida')
        );
    }
}

All 2 Comments
krumza

Hi, 500 error mean server error, not Wade error.

I think reason is a somewhere there:

$retorno = Registro::insert(

Because you try insert data somewhere into database(?) without validation.

Aletvia

Well, I couldn't solve it that way, but I was able to save the data to a text file with ajax and php. Maybe isn´t be the best option but it works. If anyone has any better option post it please.
Here my code:

$.ajax({
                url: '/guardar.php',
                type: 'POST',
                data:{data},
                success: function(result) {
                    console.log('the data was successfully sent to the server');
                }
            });

<?php

$data=$_POST["data"];
if ( file_exists("file.txt")) {
        $fp = fopen ("file.txt", "a");
        fwrite($fp, $data);
        fclose($fp);
        echo "Success";

    } 
    else {
       echo'<script type="text/javascript">alert("file does not exist")</script>';
    }

?>

Post a reply
Add Attachment
Submit Reply
Login to Reply