ron tornambe ron tornambe - 6 months ago 12
jQuery Question

Why is json_encode returning arrays instead of objects?

If you are inclined to downvote this question, please indicate the reason so I can learn from my mistakes.

PHP - EDIT

<?php

require_once "dbconnect.php";

function isEmpty($str) {
return strlen(trim($str)) == 0;
}

function getWritersData() {
try {
if (!isset($_REQUEST["userid"]) || isEmpty($_REQUEST["userid"])) {
throw new Exception('A user-id must be supplied.');
}
$userid = $_REQUEST["userid"];
$dbh = connect2DB();
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->prepare("SELECT Title, WorkType, FormType, Genre, NumberOfPages, Filename, OriginalFilename FROM Writers WHERE fkAccounts = :userid");
$stmt->bindParam(':userid', $userid, PDO::PARAM_INT);
$stmt->execute();
$rows = $stmt->fetchAll();
echo json_encode($rows, JSON_FORCE_OBJECT);
} catch (PDOException $e) {
echo 'Database error: ' . $e->getMessage();
} catch (Exception $e) {
echo 'General error: ' . $e->getMessage();
}
}
/** Update writers data **/
function saveWritersData()
{
try {
include_once "commonWritersPostElements";
$dbh = connect2DB();
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->prepare("UPDATE Writers SET fkAccounts=:userid, Title=:title, WorkType=:worktype, FormType=:formtype, Genre=:genre, NumberOfPages=:pages, Filename=:filename, OriginalFilename=:origonal WHERE fkAccounts=:userid");
$worktype = "1";
$stmt->bindParam(':userid', $userid, PDO::PARAM_INT, 10);
$stmt->bindParam(':title', $title, PDO::PARAM_STR, 255);
$stmt->bindParam(':worktype', $worktype, PDO::PARAM_STR, 30);
$stmt->bindParam(':formtype', $formtype, PDO::PARAM_STR, 30);
$stmt->bindParam(':genre', $genre, PDO::PARAM_STR, 100);
$stmt->bindParam(':pages', $nbrPages, PDO::PARAM_STR, 100);
$stmt->bindParam(':filename', $NewFileName, PDO::PARAM_STR, 30);
$stmt->bindParam(':original', $File_Name, PDO::PARAM_STR, 30);
$stmt->execute();

} catch (PDOException $e) {
echo 'Database error: ' . $e->getMessage();
} catch (Exception $e) {
echo 'General error: ' . $e->getMessage();
}
}
function deleteWritersData()
{
try {
if (!isset($_REQUEST["userid"]) || isEmpty($_REQUEST["userid"]))
throw new Exception('user-id is missing.');
else {
$userid = filter_var(trim($_REQUEST["user-id"]), FILTER_SANITIZE_STRING);
$userid = htmlspecialchars_decode($userid, ENT_QUOTES);
}
$dbh = connect2DB();
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->prepare("DELETE Writers WHERE fkAccounts=:userid");
$stmt->bindParam(':userid', $userid, PDO::PARAM_INT, 10);
$stmt->execute();

} catch (PDOException $e) {
echo 'Database error: ' . $e->getMessage();
} catch (Exception $e) {
echo 'General error: ' . $e->getMessage();
}
}


if (!isset($_REQUEST['action']) || isEmpty($_REQUEST['action']))
throw new Exception('Programmer error: action not posted.');
else {
$action = $_REQUEST['action'];
switch($action) {
case 'get-writer-data':
getWritersData();
break;
case 'update-writers':
select();
break;
default:
throw new Exception("Unknown action: " . $action);
break;
}
}

if (!isset($_REQUEST['action']) || isEmpty($_REQUEST['action']))
throw new Exception('Programmer error: action not posted.');
else {
$action = $_REQUEST['action'];
switch($action) {
case 'get-writer-data':
getWritersData();
break;
case 'delete-writers':
deleteWritersData();
break;
case 'update-writers':
saveWritersData();
break;
default:
throw new Exception("Unknown action: " . $action);
break;
}
}

?>


JS

$(function () {
populateWritersDropdowns();

data = {};
data.action = 'get-writer-data';
data.userid = sessionStorage.getItem("user-id");
console.log("user-id-manage-uploads=" + sessionStorage.getItem("user-id"))
ajax('post', 'php/manage-uploads.php', data, getSuccess, "Error retrieving writer's data: ");
$(".tr-clone");
function getSuccess(data) {
console.log("data=" + data);
var trClone = $(".tr-clone");
var jsonData = $.parseJSON(data);
var count = 0;
for (var key in jsonData) count++
$.each(jsonData, function (key, value) {
trClone.find(".title").val(value.Title);
trClone.find(".work-type").val(value.WorkType);
trClone.find(".form-type").val(value.FormType);
trClone.find(".genre").val(value.Genre);
console.log("value.FormType=" + value.FormType + ", form-type.val()=" + trClone.find(".form-type").val());
console.log("value.Genre=" + value.Genre + ", genre.val()=" + trClone.find(".genre").val());
trClone.find(".form-type").val(value.FormType);
trClone.find(".nbr-pages").val(value.NumberOfPages);
trClone.find(".synopsis a[href='" + value.Filename + "']");
if (key === count - 1) return false;
trClone = trClone.clone().insertAfter($(".tr-clone:last"));
});
}


console.log

In the JS code, the JSON.parse(...) throws the error show below.


data=[{"Title":"Mozart, Wunderkind","0":"Mozart,
Wunderkind","WorkType":"1","1":"1","FormType":"4","2":"4","Genre":"12","3":"12","NumberOfPages":"250","4":"250","Filename":"6532744220.pdf","5":"6532744220.pdf","OriginalFilename":"MozartWunderkindQueryLetter.pd","6":"MozartWunderkindQueryLetter.pd"},{"Title":"Mozart,
Wunderkind Query-Letter","0":"Mozart, Wunderkind
Query-Letter","WorkType":"2","1":"2","FormType":"7","2":"7","Genre":"9","3":"9","NumberOfPages":"129","4":"129","Filename":"9981287843.pdf","5":"9981287843.pdf","OriginalFilename":"MozartWunderkindQueryLetter.pd","6":"MozartWunderkindQueryLetter.pd"}][{"Title":"Mozart,
Wunderkind","0":"Mozart,
Wunderkind","WorkType":"1","1":"1","FormType":"4","2":"4","Genre":"12","3":"12","NumberOfPages":"250","4":"250","Filename":"6532744220.pdf","5":"6532744220.pdf","OriginalFilename":"MozartWunderkindQueryLetter.pd","6":"MozartWunderkindQueryLetter.pd"},{"Title":"Mozart,
Wunderkind Query-Letter","0":"Mozart, Wunderkind
Query-Letter","WorkType":"2","1":"2","FormType":"7","2":"7","Genre":"9","3":"9","NumberOfPages":"129","4":"129","Filename":"9981287843.pdf","5":"9981287843.pdf","OriginalFilename":"MozartWunderkindQueryLetter.pd","6":"MozartWunderkindQueryLetter.pd"}]

VM1161:1 Uncaught SyntaxError: Unexpected token [ in JSON at position
613n.parseJSON @ jquery.min.js:4getSuccess @ VM1137:13(anonymous
function) @ VM1136:97j @ jquery.min.js:2k.fireWith @ jquery.min.js:2x
@ jquery.min.js:4(anonymous function) @ jquery.min.js:4

Answer

Here closely looking at your JSON string I came to know that you are echoing the string two times ... so that it is sent to the client two times appended, and that is why it is not shown in correct way...

You can use JSON parser online tool to get idea about your JSON strings .... So you need to figure out in your php code, that why it is being sent two times, it must be something like you have echoed it twice... if you put your whole php code then we could help you more..

So all n all, you need to correct your response from the server, as JSON encoding is working fine and that encoded string should be responded only once

BINGO !!!! in your php code you are executing switch case twice after line if (!isset($_REQUEST['action']) || isEmpty($_REQUEST['action'])) , see below that is why it is echoing twice ... and spoils your JSON string

if (!isset($_REQUEST['action'])  || isEmpty($_REQUEST['action']))
    throw new Exception('Programmer error: action not posted.');
else {
    $action = $_REQUEST['action'];
    switch($action) {
    case 'get-writer-data':
        getWritersData();
        break;
    case 'update-writers':
        select();
        break;
    default:
        throw new Exception("Unknown action: " . $action);
        break;
    }
}

if (!isset($_REQUEST['action'])  || isEmpty($_REQUEST['action']))
    throw new Exception('Programmer error: action not posted.');
else {
    $action = $_REQUEST['action'];
    switch($action) {
    case 'get-writer-data':
        getWritersData();
        break;
    case 'delete-writers':
        deleteWritersData();
        break;
    case 'update-writers':
        saveWritersData();
        break;
    default:
        throw new Exception("Unknown action: " . $action);
        break;
    }
}
Comments