I am trying to make a form that consumes an API to store information in my Database.
But the file app.php it's not returning anything. There is where I handle to communicate the API with the DB.
I am getting this error in the Developer Extension in my frontend form:
SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data
Just for testing I tried to do var_dump($response); die; in app.php and it shows me the text correctly.
My app.php
<?php
namespace App;
require 'autoload.php';
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_REQUEST['action'])) {
switch ($_REQUEST['action']) {
case 'set':
$data = new Data;
$data->name = $_REQUEST['name'];
$data->email = $_REQUEST['email'];
$data->phone = $_REQUEST['phone'];
header('Content-Type: application/json');
$response['id'] = $data->save();
return json_encode($response);
break;
default:
header("HTTP/1.0 404 Not Found");
break;
}
} else {
header("HTTP/1.0 404 Not Found");
}
My app.js file:
var data = {
name: name,
email: email,
phone: phone,
action: 'set'
};
var sentData = sendData(data);
if(sentData) {
alert("OK");
resetFields();
} else {
alert("NOT OK");
}
function sendData(data) {
$.ajax({
url: 'app/app.php',
method: 'POST',
data: data,
dataType: 'json',
success: function(response) {
return response;
},
error: function(xhr, status, error) {
return xhr.responseText
}
})
}
So, where is the error?
header('Content-Type: application/json);exit(json_encode($response));notreturn json_encode($response);