jQuery ajax/post response encoding

encoding, jquery, json

Solution

Add the correct PHP header and decode the string:

<?php
  header("Content-type: application/json");
  $val1 = "Productmanager m / f";
  $val2 = "test";
  $arr = array("first" => $val1, "second" => $val2);
  echo json_encode($arr);
?>

<script>

    $(document).ready(function() {
      $.post("test.php", function(data){
        var response = $.parseJSON(data);
        console.log(htmlDecode(response.first));
        console.log(response.second);
      }
    });

function htmlEncode(value){
  return $('<div/>').text(value).html();
}

function htmlDecode(value){
  return $('<div/>').html(value).text();
}

</script>

Problem

I have a problem with json encoded information which loaded via ajax. The PHP code (test.php): ``` <?php $val1 = 'Productmanager m / f'; $val2 = 'test'; $arr = array('first' => $val1, 'second' => $val2); echo json_encode($arr); ?> ``` The JavaScript code inside a html file: ``` $(document).ready(function() { $.post("test.php", function(data){ var response = $.parseJSON(data); console.log(response.first); console.log(response.second); } }); ``` And the result in console looks like: ``` Productmanager&#x20;m&#x20;&#x2f;&#x20;f ``` and ``` test ``` Both files are UTF-8 encodet. I´m realy dont know why and how to convert it back to a readable string. You may have an idea how this can occur? I have found no suitable solution at first go, just search&replace approaches.

Original source