3

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
Mehdi Haghgoo
  • 3,144
  • 7
  • 46
  • 91

1 Answers1

1

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:

  1. It uses hardcoded string 'action' as parameter - I suppose there should be $action var as param
  2. It is missing a defalut 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?)
James Wrcsti
  • 220
  • 1
  • 8
  • Fixed those, but the code still fails. Just new lines are added to the file. – Mehdi Haghgoo Nov 17 '18 at 13:29
  • What is the server response now (after code fixes)? I suppose, the `file_put_contents` condition is evaluated as true, since new lines are added, but there seems to be some other error/warning/notice, which results in non-valid JSON server response. – James Wrcsti Nov 19 '18 at 13:04
  • Thanks for checking. In addition to those fixes i found that i also needed to check xhr.status and xhr.readyState before processing response. – Mehdi Haghgoo Nov 21 '18 at 21:58