syuji-higa
6/6/2018 - 7:52 AM

PHP - get data with Ajax

PHP - get data with Ajax

<?php
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) ||
  $_SERVER['HTTP_X_REQUESTED_WITH'] !== 'XMLHttpRequest') {
  die(json_encode(array('status' => "Invalid call.")));
}
setlocale(LC_ALL, 'ja_JP.UTF-8');
if($_SERVER['REQUEST_METHOD'] !== 'POST') {
  die(json_encode(array('status' => 'Not POST.')));
}
if(!isset($_POST['name'])) {
  die(json_encode(array('status' => "Not 'name' data.")));
}
$url  = 'http://api.xxx/xxx';
$body = array(
  'key'  => '01234567890123456789',
  'name' => $name,
);
$res = file_get_contents($url . '?' . http_build_query($body));
preg_match('/HTTP\/1\.[0|1|x] ([0-9]{3})/', $http_response_header[0], $matches);
$status_code = $matches[1];
if($status_code !== '200') {
  die(json_encode(array('status' => "Request error.")));
}
$res = json_decode($data, true);
header('Content-Type: application/json; charset=UTF-8');
header('X-Content-Type-Options: nosniff');
echo json_encode($res, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP);