Skip to main content

PHP JSON Response Pattern

Ένα δομημένο response σε JSON μορφή από PHP προς JavaScript:


<?php

header('Content-Type: application/json');

$response=[
'error' => false,
'msg' => '',
'data' => ''
];



// MY LOGIC
// e.g. connection to db
// Αν αποτύχει η διαδικασία κάνουμε
// if(){
// $response['error'] = true;
// $response['msg'] = "Error message";
// echo json_encode($response);
// exit;
// }
//


$response['error'] = false;

// json encode the response to decode it from javascript and use it there as // object. Μπορούμε να χρησιμοποιήσουμε στη javascript console.log(response.data) για να δούμε τα data ή να χρησιμοποιήσουμε response.error για να δουμε αν είναι true ή false και να κάνουμε πχ alert to response.msg αλλιως συνεχίζουμε επιτυχως τη διαδικασία μας π.χ. να σβήσουμε το row που θέλουμε δυναμικά με javasript
echo json_encode($response);
exit;
?>