1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

parseJSON-problem

Discussion in 'jQuery' started by PoPSiCLe, Oct 29, 2013.

  1. #1
    Okay. I have a $.post-function which sends a bit of info to a .php-file, and then returns whatever it's set to return.

    This mostly works just fine, but for some reason, when using this to parse some return values, it breaks, with a
    SyntaxError: JSON.parse: unexpected character
    data = $.parseJSON(data);
    error.

    I can't for the life of me understand what is causing it to balk.

    Here's the code snippets:
    the json_encoded from the php file:
    
      if ($stmt->rowCount() == 1) {
           $result = 'success';
       } elseif (isset($stmt) && !$stmt->execute()) {
         $workdone = displayErrors($stmt)[2];
         $result = 'error';
       } else {
         $workdone = "Det oppstod en feil - vennligst prøv igjen senere";
         $result = 'error';
       }
                 
       echo json_encode(array("content" => $workdone, "infotype" => $result));
    
    PHP:
    And the code used in the return functions in my js-file is the same for all returns, both the ones that work and those which doesn't.
    
    function(data) { data = $.parseJSON(data); showUpdateInfo(''+data.content+'',''+data.infotype+''); },"json");
    
    Code (markup):
    For some reason it breaks in weird places. At first I thought it was because of some scandinavian letters or similar in the json-return values, but they seem to be escaped properly, so probably not that.

    Here's the return value (console.log(data)) from the one that breaks:
    {"content":"Det oppstod en feil - vennligst pr\u00f8v igjen senere","infotype":"error"}

    And here's one from one that doesn't break:
    {"content":"Skiftleder & Jobbe alene oppdatert","infotype":"success"}

    I must admit I'm not very used to JSON, so I might be doing something horribly wrong, but... help?
     
    PoPSiCLe, Oct 29, 2013 IP
  2. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #2
    And, just to answer myself - removed the "json" on the end of each function, and everything works without a hitch. Not really sure why or how, since the documentation I've seen says it should be there, but as long as it works, I'm happy. Also had to do some tinkering on the PHP-side to actually get it to return what I wanted each time, but that was irrelevant to the problem presented here (basically, it returned the wrong type (error instead of success and such)).

    So, at least, it's working now.
     
    PoPSiCLe, Oct 29, 2013 IP