0

Im having some problems getting different variables from a JSON variable.

I do a $.post on get_shop.php file that gets data from a database, take the results and put it into a array and do a json_encode on it and prints it.

get_shop.php:

$id = $_GET["id"];

    $query = " 
        SELECT 
            *
        FROM shop
        WHERE 
            id = :id
    "; 

    // The parameter values 
    $query_params = array( 
        ':id' => $id
    ); 

    try 
    { 
        // Execute the query against the database 
        $stmt = $db->prepare($query); 
        $result = $stmt->execute($query_params); 
    } 
    catch(PDOException $ex) 
    { 
        // Note: On a production website, you should not output $ex->getMessage(). 
        // It may provide an attacker with helpful information about your code.  
        die("Failed to run query: " . $ex->getMessage()); 
    } 

    // Retrieve the user data from the database.  If $row is false, then the username 
    // they entered is not registered. 
    $row = $stmt->fetch(); 

    $database_data = array(
    "name" => $row["name"],
    "description" => $row["description"],
    "category" => $row["category"],
    "price" => $row["price"]
    );

    print(json_encode($database_data, JSON_UNESCAPED_UNICODE));

After that i do a console.log with the data received in shop.php (The file that makes the $.post request)

shop.php $.post sample:

$(document).ready(function(){
console.log("ID: " + id );

$.post("get_shop.php?id="+id+"",
function(data,status){

console.log(data + "\nStatus: " + status); )};

An example for a result:

{"name":"Hardrive 5GB","description":"Speed 10MB/s","category":"Hardrive","price":"1000"}

Now, the problem is that i want to show a part of the result (Like just "name") but it says "undefined" (I use data[name]). How do i solve this? Thanks!

4
  • Try to use: data.name Commented Apr 18, 2014 at 15:41
  • Received data is just a string, not a JSON object. So You have to run it through JSON.parse() or use jQuery's AJAX option to do this parsing automatically (dataType: 'json'). Commented Apr 18, 2014 at 15:42
  • @RomanHocke $.post is a wrapper around $.ajax and has it's own mechanism to specify the return dataType (last argument). Commented Apr 18, 2014 at 15:54
  • @izuriel: You are correct. You may specify the dataType as the last argument or include it in settings argument. Commented Apr 18, 2014 at 15:56

4 Answers 4

2

Received data is just a string, not a JSON object. So You have to run it through JSON.parse() (as in Pitchinnate's answer) or use jQuery's AJAX option to do this parsing automatically (see the dataType 'json' in the example below):

$.post('get_shop.php?id='+id, function(data, status) {

    console.log(data + "\nStatus: " + status);

}, 'json');

You may also have the jQuery intelligent guess, but You must hint it with proper http header in Your PHP code:

<?php

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

In such a case jQuery knows the received data is in JSON and parses it automatically.

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

Comments

0

You need to parse the Json string first, this will convert it into an object you can then reference the individual values using obj.attribue or obj['attribute'].

$.post("get_shop.php?id="+id+"",function(data,status){
    var obj = JSON.parse(data);
    var name = obj.name;
});

Look at @RomanHocke's answer to see other ways to allow Jquery to automatically convert the response into a javascript object.

3 Comments

This is by far the best option, turning the JSON string into a proper JavaScript object.
If the data comes back as valid JSON, jQuery will parse it automatically before passing it into the the callback. If not, then you can explicitly tell jQuery that it's a JSON return so that it will parse it for you. Manually parsing JSON is not something you should be doing when using jQuery request methods.
@izuriel I agree with you, my main goal was to show OP that the information received was simply coming in and being stored as text not as an object. The way I am showing applies to any situation regardless of whether the response is coming from a Jquery $.post() or $.get() or something else, i'm simply showing how to turn a json string into a javascript object.
0

It's telling you that name is undefined in the line data[name] unless you defined name to some string that could be used as a key. There are two options for accessing properties on JavaScript objects:

Access via dot notation:

data.name // Similar to how you were trying to do it without a string key

With a key (string/number):

data["name"] // Also similar, but notice the quotes around name.

Bothe of these methods will give you the same result, the only time where it really makes a difference is when your key has a space, hyphen or other character in it that makes it an illegal identifier in JavaScript you should choose the second method. Otherwise, either method will work for you.

If you're data is not being parsed properly by jQuery you can modify you're request like so:

$.post("get_shop.php", {id: id}, function(data, status) {
  // data is an object now
}, "json");

I did two things differently, I leveraged jQuery's data utility instead of building the URL manually (the second argument), and I provided a data type for the return (the last argument) telling jQuery to treat the return value as JSON which means that data will be the resulting parsed object.

4 Comments

One note if you utilize jQuery's data utility instead of building the url the value for id will come in as a $_POST variable not a $_GET variable so you would need to update your php code accordingly.
Or use $_REQUEST, IMHO if you're making a POST request you should have been using $_POST to begin with so I don't feel it was necessary to mention (the request was POST). I hate seeing $_GET when a POST request is made.
Agreed all depends on if other services are using the same API call though and they are sending the information as a GET variable, he could change the jQuery to a $.get() instead of a $.post() if he is going to use the url to send the value.
Or use $_REQUEST and not care if it's passed via GET or POST.
-1

Use this to get JSON data properly

$.getJSON("get_shop.php?id="+id,
function(data,status){

console.log(data + "\nStatus: " + status); 
alert(data.name); //to get name
alert(data.description); //  to get description
alert(data.category); //to get category
alert(data.price); //to get price
});

2 Comments

Why use this instead, why change to GET instead of POST, where is your explanation? This is not an answer, it's a snippet of code. What is wrong with the other mechanisms of fetching JSON data with $.post?
Ok,sorry, I was concentrated only on JSON decode and getting seperate data.

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.