3

I will start by saying that I am learning how to program in jquery/javascript, and am running into an issue using JSON.parse(). I understand the format, and why people use it... but have not been able to get it to work in any of my code projects.

I have read in books/online on here in how to use it, but I think I read too much on it. I am now confused and second guessing what I know about it.

With that said, my jquery/javascript class I am taking is asking me to use it for an assignment, through AJAX using MAMP/localhost as the server.

The two codes below are for the section that I need to fill in the //TODO information. One is javascript (client-side), the other is php (server-side). I think that I've set the other //TODO information correctly, but I keep getting a token error for the JSON part.

I looked on here for a solution, but again, I think I've confused myself badly and need help. Appreciate any feedback, insight, or information.

-Javascript-

var calculateMpg = function () {
    // These lines are commented out since the server will perform these checks
    // if (!checkNumber("miles") || !checkNumber("gallons")) {
        // return;
    // }
    var miles = $("#miles").val();
    var gallons = $("#gallons").val();
    console.log("ajax request issued.");
    var result;
    $.ajax({
        url: "service.php?action=calculateMPG&miles="+miles+"&gallons="+gallons, 
        cache: false,
        dataType: "text",
        success: function(msg) {
            console.log("ajax response received.");
        //  TODO: parse the JSON string returned from the server (see JSON.parse())
        JSON.parse("result");
        if (result.status === 'success') {
        //  TODO: get the mpg value returned from the server and display it to the user.
            $("#mpg").val($_GET("result"));
            console.log("JSON Working!");
        }
        else {
            // TODO: get the name of the variable with the error. Hint: look at the 'fail' result from service.php 
            $_GET[fail(id)];
            // TODO: report the error to the user using invalidNumber() function.
            alert("{status: 'failure', variable: <variable name>}");
        }
    }
});
};

$(document).ready( function () {
    $("#miles").blur(function () {
        checkNumber("miles");
    });
    $("#gallons").blur(function() {
        checkNumber("gallons");
    });
    $("#calculate").click(calculateMpg);
    $("#miles").focus();
});

-PHP-

<?php
if ($_GET) {
    if ($_GET['action'] == 'calculateMPG') {
        $miles = htmlspecialchars($_GET['miles']);
        $gallons = htmlspecialchars($_GET['gallons']);
        // validate miles
        if (strlen($miles) == 0) {
            fail("miles");
        }
        $miles_chars = str_split($miles);
        for ($i=0; $i< count($miles_chars); $i++) {
            if ($miles_chars[$i] < "0" || $miles_chars[$i] > "9") {
                //error_log("miles_chars check failed at: " + $i);
                fail("miles");
            }
        }
        // validate gallons
        if (strlen($gallons) == 0) {
            fail("gallons");
        }
        $gallons_chars = str_split($gallons);
        for ($i=0; $i< count($gallons_chars); $i++) {
            if ($gallons_chars[$i] < "0" || $gallons_chars[$i] > "9") {
                fail("gallons");
            }
        }
        // validate $miles and $gallons calling $fail along the way
        $result = $miles/$gallons;
        if ($result) {
            success($result);
        } else {
            fail("mpg");
        }
        exit ;
    }
 }

function fail($variable) {
    die(json_encode(array('status' => 'fail', 'variable' => $variable)));
}

function success($message) {
    die(json_encode(array('status' => 'success', 'message' => $message)));
}

Edited Additional 1 I have made changes to the JSON information in regard to 'var result' (thanks to several of the responses here). I'm starting to understand JSON a bit better.

Another question I have (now) is how to isolate a part of the JSON message from the whole being transmitted?

A piece of the 'JSON.parse(msg)' returned DOES include the answer to the equation miles/gallons, but I don't know how to... extract it from the JSON.

The solution to the equation miles/gallons appears in the 'msg' output.

Thanks.

Edited Additional 2 This question has been solved! While perusing around stackoverflow for a solution to the question in my previous edited section, I found my answer here: JSON response parsing in Javascript to get key/value pair.

The answer is this: under the //TODO section asking for the mpg value, I put the following code - $("#mpg").val(result.message); - which says that in the JSON section of the variable result, take the part of the JSON marked 'message', the value being the equation solution.

Thank you to all who responded with their solutions to my problem. I appreciate the fast responses, the great suggestions, and the information in understanding JSON.

-ECP03

Community
  • 1
  • 1
ECP03
  • 67
  • 8
  • What do you think will happen with `JSON.parse("result");`? –  May 11 '15 at 15:14
  • Having not worked with JSON before, I initially thought it was similar to '$_GET' (but for grabbing information from a server). Since the PHP (presented) is a mock of a server response, I though putting '("result")' would pull the '$result = $miles/$gallons;' solution from the server, which is one of my '//TODO' objectives. – ECP03 May 11 '15 at 20:15

6 Answers6

1

Instead of parsing the JSON yourself, jQuery already provides you with a convenient function that will parse JSON:

var path = "service.php?action=calculateMPG&miles="+miles+"&gallons="+gallons;
$.getJSON(path, function (data) {
  if (data.status == 'success') {
    console.log('Success! Message:', data.message);
  } else {
    console.log('Failed :( Variable:', data.variable);
  }
});

For your original code, what you would need to do is call JSON.parse(msg) in your success callback, which would return a JavaScript object with the values you sent from your PHP script. By specifying dataType: 'json' in the $.ajax call, jQuery does this for you. The $.getJSON method does this and some other things for you.

Blixt
  • 49,547
  • 13
  • 120
  • 153
1

JSON.parse() requires that you send it a valid JSON string.

"result" is not a valid JSON string. In your success function you have defined a parameter msg - what does this contain? Try console.log(msg) at the beginning of your success function and look at the console output.

Alex McMillan
  • 17,096
  • 12
  • 55
  • 88
  • I did use console.log(msg) to test whether a previous viewers response, and it did work (in that, in the php, it did spit out the success function). Got me on the right track. Thank you. – ECP03 May 11 '15 at 20:28
1

You have two options:

Option 1: -- Parse the string returned.

Change JSON.parse("result"); to:

var result = JSON.parse( msg );

Option 2: -- Request JSON instead of plain text - no need to parse

Use $.getJSON() which is shorthand for:

$.ajax({
  dataType: "json",
  url: url,
  data: data,
  success: success
});
PeterKA
  • 24,158
  • 5
  • 26
  • 48
  • I added your option 1 solution. With another reviewers response (using console.log(msg)), JSON is starting to become clearer for me. Thank you very much for providing me option 2, however. I will be using it while moving forward with using and understanding JSON further. – ECP03 May 11 '15 at 20:18
1

You need to use the result returned by the success function:

var result = JSON.parse(msg);

Then, you could do stuff like result.status.

When you put JSON.parse("result") you're saying "parse the string 'result'," which doesn't make any sense. However, if you say JSON.parse(msg) you're saying "Parse the variable that was returned from the ajax action," which makes sense.

Travis Heeter
  • 13,002
  • 13
  • 87
  • 129
0

JSON.parse() is used to convert your json data to object, then you can manipulate it easly.JSON.parse(msg); instead of JSON.parse("result"). For example:

var json = '{"value1": "img", "value2":"img2"}'
var obj = JSON.parse(json);
for ( k in obj ) {
    console.log(obj[k])
}
Radonirina Maminiaina
  • 6,958
  • 4
  • 33
  • 60
  • Okay. In your response, are you saying that that I can add 'k' into 'obj' ? How does that work? And what would the code look like? – ECP03 May 11 '15 at 20:24
-1

This is totally wrong: JSON.parse("result");. .parse() expects a JSON string, e.g. the string that came back from you ajax request. You're not providing that string. you're providing the word result, which is NOT valid JSON.

JSON is essentially the right-hand side of an assignment expression.e.g.

var foo = 'bar';
          ^^^^^---this is json
var baz = 42;
          ^^---also json
var qux = ['a', 'b', 'c'];
          ^^^^^^^^^^^^^^^---even more json

var x = 1+2;
        ^^^---**NOT** json... it's an expression.

What you're doing is basically:

var x = parse;
        ^^^^^^---unknown/undefined variable: not JSON, it's an expression
Marc B
  • 356,200
  • 43
  • 426
  • 500
  • Umm, your first 3 examples are *not* JSON either. JSON requires an entire object, with keys surrounded by double-quotes. JSON !== Javascript. `'{"foo": "bar", "baz": 42}'` is JSON. – Alex McMillan May 11 '15 at 15:21
  • yes, and? `[]` is an array. I might have the wrong quotes for json, but it'd still be technically valid. And a bare number **IS** valid json. e.g. `echo json_encode(42)` will return `42` exactly. – Marc B May 11 '15 at 15:25
  • 1
    @MarcB While `json_encode` (and `JSON.parse`) do support encoding (and parsing) primitives in the JSON spec, that doesn't mean you can compare it exactly to JavaScript code. Try this: `JSON.parse("'hello world'")` or this: `JSON.parse("{a: 42}")`. They both fail because they fail to follow the JSON spec. Have a look at http://www.json.org/ – Blixt May 11 '15 at 15:31
  • @MarcB `"[]"` is valid JSON. `[]` is a javascript array. Regardless, your example is *not* "technically valid" - it is exactly the opposite - *technically invalid*. Examples like this only serve to confuse newcomers who are trying to learn - it doesn't help them at all. – Alex McMillan May 11 '15 at 15:43
  • no. `[]` by itself is valid json. `"[]"` is what you have to use in OTHER languages to embed the array-in-json-format in that language's string constructs. e.g. `$json = "[]";` in php. `"[]"` in json is a **STRING** that contains `[` and `]` characters. – Marc B May 11 '15 at 16:40
  • Ok. I highly recommend you go and learn the [JSON spec](http://www.json.org) before answering questions about JSON tho. – Alex McMillan May 12 '15 at 04:02