Reputation: 3484
I hate using libraries unless I absolutely need them. I prefer working with vanilla JavaScript as I think it will do what I want and I will know better what I'm doing. So, there is a simple add-record operation I want to do via AJAX:
function addToBlacklist() {
var xhr = new XMLHttpRequest();
xhr.open('POST', 'api.php?action=addToBlackList');
var jsonObj;
xhr.onreadystatechange = function () {
try {
jsonObj = JSON.parse(xhr.responseText);
} catch (e) {
alert(e.toString());
}
if (jsonObj.status_code === 200) {
alert('Added');
//Add the new word to the end of the list in the grid view
} else {
alert('Add failed');
}
}
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send('blackword=' + encodeURIComponent(document.getElementById('blackword')));
}
On server side, I process the request this way (Already set header at the top of the page with header('Content-Type: application/json') :
if(isset($_GET['action'])){
$action = filter_input(INPUT_GET, 'action', FILTER_SANITIZE_URL);
switch('action'){
case 'addToBlacklist':
error_log('Action: ' . 'addToBlackList');
$blackword = filter_input(INPUT_POST, 'blackword', FILTER_SANITIZE_URL);
if(file_put_contents(BLACKLIST_FILE, $blackword . PHP_EOL, FILE_APPEND)){
echo json_encode(['status_code'=>200, 'description'=>Translate::get('Adding to blacklist successful')]);
}
else {
echo json_encode(['status_code'=>500, 'description'=> Translate::get('Adding to blacklist failed')]);
}
break;
}
}
The problem is I always get this error in my browser:
SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data
Upvotes: 3
Views: 1925
Reputation: 240
Make sure you always send valid JSON string from the server. On the client side, check, whether the response status is valid (HTTP status code 200) and only then proceed to parse the XHR response. The value, you get from server is empty, that is the problem.
At first, JSON.parse()
expects JSON string as a parameter, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse.
Second, the switch statement in your php code is incorrect for multiple reasons:
$action
var as paramdefalut
clause - this results in returning nothing, which can not be parsed as JSON by javascript - I suggest you to use some fallback JSON string to make sure, that there is always a JSON-type string response from the server in case of successful response. (Should switch statements always contain a default clause?)Upvotes: 1