-1

I am doing something i don't understand how. written a php code in O.O.P and the value gotten from it are objects. but i want to convert this O.O.P object to JSON data to be used in by javascript. so I converted my converted my objects to array on the php end. the try to use the json_encode function on it the script just keep returning errors. so i tried using a function i scope out, it worked but the js keeps on rejecting the data. Below is the JS file

var ajax = new XMLHttpRequest();
ajax.open('GET','user.php',true);
ajax.setRequestHeader("Content-type","application/json");
ajax.onreadystatechange = function(){
  if(ajax.readyState == 4 && ajax.status ==200){
    var data = JSON.parse(ajax.responseText.trim());
    console.log(data);
    console.log(data[username]);
  }
} 
ajax.send();

it will return this error "SyntaxError: JSON.parse: bad control character in string literal at line 1 column 129 of the JSON data" without the JSON.parse it return undefind fro the data.username console log. Below is the PHP SCRIPT

    //header("Content-type: application/json");
require_once 'core/init.php';

function array2json($arr) {
    /*if (function_exists('json_encode')) {
    echo "string";
    return json_encode($arr);
    }*/

    $pars = array();
    $is_list = false;

    $keys = array_keys($arr);
    $max_length = count($arr) - 1;
    if (($keys[0] == 0) and($keys[$max_length] == $max_length)) {
        $is_list = true;
        for ($i = 0; $i < count($keys); $i++) {
            if ($i != $keys[$i]) {
                $is_list = false;
                break;
            }
        }
    }
    foreach($arr as $key => $value) {
        if (is_array($value)) {
            if ($is_list) $parts[] = array2json($value);

            else $part[] = '"'.$key.
            ':'.array2json($value);
        } else {
            $str = '';
            if (!$is_list) $str = '"'.$key.
            '"'.
            ':';
            if (is_numeric($value)) $str. = $value;
            elseif($value === false) $str. = 'false';
            elseif($value === true) $str. = 'true';
            else $str. = '"'.addslashes($value).
            '"';

            $parts[] = $str;
        }
    }
    $json = implode(',', $parts);
    if ($is_list) return '['.$json.
    ']';
    return '{'.$json.
    '}';

}


$user = new User();
$json = array();
if (!$user - > is_LOggedIn()) {
    echo "false";
} else {
    foreach($user - > data() as $key => $value) {
            $json[$key] = $value;
            //$json =json_encode($json,JSON_FORCE_OBJECT);
            //echo $json;
        }
        /*$details	= '{"'.implode('", "', array_keys($json)).'"';
        $data 		= '"'.implode('" "', $json).'"}';
        die($details.' / '.$data);*/

    $json = array2json($json);
    print $json;

}

PLEASE HELP ME OUT TO SORT THIS ERROR THANK YOU.

7
  • 6
    Why not using the build in php method json_encode()? Commented Oct 22, 2015 at 16:32
  • Yes, the "right way" to generate JSON from PHP is json_encode(). If both that function and yours are not working, let's solve the problem with the "right way" rather than turning this into an XY Problem. You say "the json_encode function on it the script just keep returning errors". What errors? Commented Oct 22, 2015 at 16:41
  • simple as it is your JSON is not valid. maybe you have some linebreaks or something in a part of it. use a online json validator to see where the error is. log your json in js via console.log and go to jsonlint.com Commented Oct 22, 2015 at 16:44
  • Warning: Illegal string offset 'username' in C:\Users\Ilamini\Desktop\xampp\htdocs\church-app\user.php on line 54 after using JSONLINT i got this error Commented Oct 22, 2015 at 16:44
  • without your entire code we dont have a chance Commented Oct 22, 2015 at 16:48

2 Answers 2

1

You need to set the response headers, and ensure you are not violating CORS:

    /*
     * Construct Data Structure
     */
    $response =
    [
        'value1',
        'value2'
    ];

    /*
     * Format Data
     */
    $jsonResponse = json_encode ( $response, JSON_PRETTY_PRINT );

    /*
     * Prepare Response
     */
    header('content-type: application/json; charset=UTF-8');

    /*
     * ONLY if you want/need any domain to be able to access it.
     */
    header('Access-Control-Allow-Origin: *');

    /*
     * Send Response
     */
    print_r ( $jsonResponse );

    /*
     * Return with intended destruction
     */
    die;
0
1

Just use the json functions json_encode and json_decode to convert arrays into json string or vice versa:

$myArray = array("value1", "value2");
echo json_encode($myArray);

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.