Tommy
Tommy

Reputation: 697

jQuery show array from PHP (json encoded)

I'm trying to show an array with jQuery, but it doesn't show anything i want :P

So im asking here after been sitting on google and here for the nearest hour and still can't figure out what im doing wrong..

My array is this:

if (isset($_POST['imageID'])) { 
            $array = array();
            list($width, $height, $type, $attr) = getimagesize("../img/libary/".$_POST['imageID'].".JPG");

            $array["dimension"] = $width.' x '.$height;
            $array["filesize"] = formatBytes(filesize("../img/libary/".$_POST['imageID'].".jpg"),0);
            $array["extensions"] = strtoupper(pathinfo("../img/libary/".$_POST['imageID'].".jpg", PATHINFO_EXTENSION));
            $array["filename"] = $_database->query("SELECT * FROM imglibary WHERE imageID='".$_POST['imageID']."' LIMIT 1")->fetch_object()->name; 
            $array["fileurl"] = $_SERVER['DOCUMENT_ROOT'].'/img/libary/'.$_POST['imageID'].'.JPG';

            echo json_encode($array);
        }

And jQuery code:

$.post("jQuery.post.php", {imageID: imageID}, "json").done(function(data) { 
 // What to do here to get it to work? 
  });

Hope you guys have an answer im all out of them :(

Missed to show the answer from "data":

{"dimension": "210x214", "filesize", "214kb", "extensions", "JPG", "filename": "somefile.jpg", "fileurl": "/img/libary/40.JPG"}

Upvotes: 0

Views: 57

Answers (1)

TheCarver
TheCarver

Reputation: 19713

Use $.parseJSON to parse the data returned from the server, unless you're sending an application/json header from your PHP page.

If you want to start sending the correct JSON headers from your PHP pages, add this to the top of your pages, by default it's set to text/html, which is why your data needs to be parsed:

header('Content-type: application/json');

Then, it's as simple as console.log(data.dimension) without any need of parsing. As long as you set json as the dataType, jQuery will automatically parse the data for you.

If you don't want to/can't send the correct headers or you're unsure what they are, then use parseJSON().

Example with parseJSON:

$.post("jQuery.post.php", {imageID: imageID}, "json").done(function(data) { 
   var d = $.parseJSON(data);
   console.log(d.dimension);
});

Upvotes: 2

Related Questions