0

I'm trying to send a JQuery request to an API I'm making (first time, learning!) but my php code reports the JSON is malformed.

if I make a JSON array in PHP and pass that through it works fine but if I try to request via JQuery it always says malformed.

Im stuck!

the Javascript side looks like this...

jsonrequest = "{request: 'getJobs', token : 'eb024fab2bf6a1bfb5863dcaabcfd63fcaea50e429237df3f1cbcbfcf9b2'}";
    $.ajax({
    url: 'api.php',
    async: true,
    dataType: 'json',
    contentType: "application/json; charset=utf-8",
    data: jsonrequest,


       success: function ( result ) {
            console.log(result);
        }
});

and the PHP looks like this

$data       = file_get_contents("php://input");

if(isJson($data)) {

        // never passes the isJSON validation.

        $json       = json_decode($data,true);
        $request    = sanitize($json['request']);
        }


function isJSON($string)
{
    // decode the JSON data
    $result = json_decode($string);

    // switch and check possible JSON errors
    switch (json_last_error()) {
        case JSON_ERROR_NONE:
            $error = ''; // JSON is valid // No error has occurred
            break;
        case JSON_ERROR_DEPTH:
            $error = 'The maximum stack depth has been exceeded.';
            break;
        case JSON_ERROR_STATE_MISMATCH:
            $error = 'Invalid or malformed JSON.';
            break;
        case JSON_ERROR_CTRL_CHAR:
            $error = 'Control character error, possibly incorrectly encoded.';
            break;
        case JSON_ERROR_SYNTAX:
            $error = 'Syntax error, malformed JSON.';
            break;
        // PHP >= 5.3.3
        case JSON_ERROR_UTF8:
            $error = 'Malformed UTF-8 characters, possibly incorrectly encoded.';
            break;
        // PHP >= 5.5.0
        case JSON_ERROR_RECURSION:
            $error = 'One or more recursive references in the value to be encoded.';
            break;
        // PHP >= 5.5.0
        case JSON_ERROR_INF_OR_NAN:
            $error = 'One or more NAN or INF values in the value to be encoded.';
            break;
        case JSON_ERROR_UNSUPPORTED_TYPE:
            $error = 'A value of a type that cannot be encoded was given.';
            break;
        default:
            $error = 'Unknown JSON error occured.';
            break;
    }

    if ($error !== '') {
        // throw the Exception or exit // or whatever :)
        $output = array('status' => "error",'message' => $error);
        echo json_encode($output);
        exit;
    }

    // everything is OK
    return $result;
}
1
  • JSON also needs quotes on object keys. Commented Jul 7, 2016 at 17:34

2 Answers 2

2

Try

data: {request: 'getJobs', token: 'eb024fab2bf6a1bfb5863dcaabcfd63fcaea50e429237df3f1cbcbfcf9b2'}

without the quotes around it. jQuery should handle that for you.

If it still fails, maybe open this up in the developer tools and look at the ajax request and see what the data actually looks like going out to get an idea.

Sign up to request clarification or add additional context in comments.

3 Comments

This mirrors what I was gonna respond with, exactly. It's probably html-encoding that input string.
i've put the quotes on but didn't make a difference, I didn't realise that developer tools would tell me the outgoing request. Cool feature... in the network section was this api.php?request=getJobs&token=eb024fab2bf6a1bfb5863dcaabcfd63fcaea50e429237df3f1cbcbfcf9b2 Does this mean its going out as a standard GET type request instead of encoded JSON?
@CraigArmitage Yes, that's a GET request, You either want to use $.post() or include method: "POST" as a property in $.ajax(). api.jquery.com/jquery.ajax
1

Your code

jsonrequest = "{request: 'getJobs', token : 'eb024fab2bf6a1bfb5863dcaabcfd63fcaea50e429237df3f1cbcbfcf9b2'}";

you are defining jsonrequest as a string not an object.

Try one of two things (note the key name has to be wrapped in quotes too)

 jsonrequest = {'request': 'getJobs', 'token' : 'eb024fab2bf6a1bfb5863dcaabcfd63fcaea50e429237df3f1cbcbfcf9b2'};

or if the jsonrequest has to built as a string you can use jQuery.parseJSON()

jsonrequest = '{"request": "getJobs", "token" : "eb024fab2bf6a1bfb5863dcaabcfd63fcaea50e429237df3f1cbcbfcf9b2"}';
jsonrequest = $.parseJSON(jsonrequest);

2 Comments

Thanks for the input, sadly still getting malformed on the PHP side.
Even with the added quotes around the keys? Can you log the string that gets passed to the PHP side? That would be the first place to check what part of it isn't valid JSON.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.