<?php
// json_code.php
// RJM Programming
// November, 2018
// Use PHP json_encode and json_decode
// {a:{b:"c",d:["e","f",0]}}
// [{"river":Nile,"miles":4180},{"river":Amazon,"miles":3912},{"river":Mississippi,"miles":3710},{"river":Yangtze,"miles":3602},{"river":Ob,"miles":3459},{"river":Yellow,"miles":2900},{"river":Yenisei,"miles":2800},{"river":Parana,"miles":2795},{"river":Irtish,"miles":2758},{"river":Congo,"miles":2716}]

$cstyle = "<style> body { background-color: yellow; }  #trhead { border: 2px solid black; }  #trcontent { background-color: pink; } </style>";

$jscr = "<scr" . "ipt type='text/javascript'>

var biggestsofar=0;
var lastone=0;

var form=null;
var xhr=null;

function seldo(sois) {
  if (sois.value != '') {
  if (sois.value.trim() == '') {
  if (sois.value == ' ') {
  clickit(document.getElementById('phpit'));
  } else {
  clickit(document.getElementById('ajaxit'));
  }
  } else {
  var jj=0, cval='';
  var colis=sois.id.replace('sel','');
  var earlierthere=false;
  var yo='';
  for (var ii=1; ii<eval('' + colis); ii++) {
   if (document.getElementById('td' + ii).innerHTML != '') { earlierthere=true; } 
  }
  if (biggestsofar != 0 && eval('' + colis) != lastone && ('' + colis) != '5' && !earlierthere && document.getElementById('trcontent').innerText != '') {
   document.getElementById('dtd' + eval(1 + eval('' + colis))).innerHTML=','; 
  } else if (biggestsofar != 0 && eval('' + colis) != lastone && ('' + colis) != '5' && document.getElementById('trcontent').innerText != '' && eval('' + colis) <= biggestsofar) {
   document.getElementById('dtd' + eval(1 + eval('' + colis))).innerHTML=','; 
  }
  if (eval('' + colis) > biggestsofar) {  biggestsofar=eval('' + colis);  }
  for (jj=2; jj<=4; jj++) {
    if (document.getElementById('dtd' + jj).innerHTML == ',' && document.getElementById('td' + jj).innerHTML == '') {
      if (document.getElementById('dtd' + eval(1 + eval('' + jj))).innerHTML == ',') {
        document.getElementById('dtd' + jj).innerHTML='';
      }
    }
  }
  lastone=eval('' + colis);
  if (sois.value == 'days_of_the_week') {
   cval='\"' + sois.value + '_' + colis + '\"' + ':[' + '\"Sunday\",' + '\"Monday\",' + '\"Tuesday\",' + '\"Wednesday\",' + '\"Thursday\",' + '\"Friday\",' + '\"Saturday\"' + ']';
  } else if (sois.value == 'top_ten_longest_river_lengths') {
   cval='\"' + sois.value + '_' + colis + '\"' + ':[' + '{\"river\":\"Nile\",\"miles\":4180},{\"river\":\"Amazon\",\"miles\":3912},{\"river\":\"Mississippi\",\"miles\":3710},{\"river\":\"Yangtze\",\"miles\":3602},{\"river\":\"Ob\",\"miles\":3459},{\"river\":\"Yellow\",\"miles\":2900},{\"river\":\"Yenisei\",\"miles\":2800},{\"river\":\"Parana\",\"miles\":2795},{\"river\":\"Irtish\",\"miles\":2758},{\"river\":\"Congo\",\"miles\":2716}' + ']';
  } else if (sois.value == 'continents_of_the_earth') {
   cval='\"' + sois.value + '_' + colis + '\"' + ':[' + '\"Africa\",' + '\"Antarctica\",' + '\"Asia\",' + '\"Australia\",' + '\"Europe\",' + '\"North America\",' + '\"South America\"' + ']';
  } else if (sois.value == 'months_of_the_year') {
   cval='\"' + sois.value + '_' + colis + '\"' + ':[' + '\"January\",' + '\"February\",' + '\"March\",' + '\"April\",' + '\"May\",' + '\"June\",' + '\"July\",' + '\"August\",' + '\"September\",' + '\"October\",' + '\"November\",' + '\"December\"' + ']';
  } else if (sois.value == 'your_own_array') {
   yo=prompt('Please enter array members as comma separated list and double quote is good character to delimit strings','');
   if (yo == null) { yo=''; }
   if (yo != '') {
     cval='\"' + sois.value + '_' + colis + '\"' + ':[' + yo.replace(/\[/g,'').replace(/\]/g,'') + ']';
   }
  } else if (sois.value == 'your_own_entry') {
   yo=prompt('Please enter your own entry and double quote is good character to delimit strings','');
   if (yo == null) { yo=''; }
   if (yo != '' && yo.indexOf(',') != -1) {
     cval='\"' + sois.value + '_' + colis + '\"' + ':[' + yo.replace(/\[/g,'').replace(/\]/g,'') + ']';
   } else if (yo != '') {
     if (isNaN(yo)) {
     cval='\"' + sois.value + '_' + colis + '\"' + ':\"' + yo.replace(/\[/g,'').replace(/\]/g,'').replace(/\\\"/g,'') + '\"';
     } else {
     cval='\"' + sois.value + '_' + colis + '\"' + ':' + yo.replace(/\[/g,'').replace(/\]/g,'') + '';
     }
   }
  }
  if (cval != '') {
   document.getElementById('td' + colis).innerHTML=cval;
   if (earlierthere) {  document.getElementById('dtd' + colis).innerHTML=',';  }
   if (document.getElementById('td' + colis).innerHTML != '') {
    if (document.getElementById('tdstart').innerHTML == '') {
      document.getElementById('thstart').innerHTML=\"<input id=phpit onclick=clickit(this); type=button value=PHP title='json_encode'></input>&nbsp;<input id=ajaxit onclick=clickit(this); type=button value=Ajax title='Ajax'></input>\";
    }
    document.getElementById('tdstart').innerHTML='{';
    document.getElementById('tdend').innerHTML='}';
   }
  }
  //alert(document.getElementById('trcontent').innerText.replace(String.fromCharCode(8),'').replace(String.fromCharCode(8),'').replace(String.fromCharCode(8),'').replace(String.fromCharCode(8),'').replace(String.fromCharCode(8),'').replace(String.fromCharCode(8),'').replace(String.fromCharCode(8),'').replace(String.fromCharCode(8),'').replace(/\,\,\,\,/g,',').replace(/\,\,\,/g,',').replace(/\,\,/g,',').replace(/\,\ \,/g,',').replace(/\ /g,'^'));
  document.getElementById('injson').value=document.getElementById('trcontent').innerText; //.replace(String.fromCharCode(8),'').replace(String.fromCharCode(8),'').replace(String.fromCharCode(8),'').replace(String.fromCharCode(8),'').replace(String.fromCharCode(8),'').replace(String.fromCharCode(8),'').replace(String.fromCharCode(8),'').replace(String.fromCharCode(8),'').replace(/\,\,\,\,/g,',').replace(/\,\,\,/g,',').replace(/\,\,/g,',').replace(/\,\ \,/g,',');
  //alert(document.getElementById('trcontent').innerText);
  }
  }
}

function clickit(bois) {
 if (bois.id == 'ajaxit') {
  form = new FormData();
  xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      var myobj = JSON.parse(this.responseText);
      var str=syntaxHighlight(myobj); //JSON.stringify(myobj, null, 2); 
      document.getElementById('result').innerHTML=\"<br><br><a target=_blank title=JSON.Stringify href='//www.w3schools.com/js/js_json_stringify.asp'>JSON.stringify</a>(<a target=_blank title=JSON.Parse href='//www.w3schools.com/js/js_json_parse.asp'>JSON.parse</a>('\" + this.responseText + \"')) = <br><br>\" + str; 
      console.log(myobj);
    }
  };
    form.append('ajax', 'yes');
    form.append('injson', document.getElementById('trcontent').innerText);
    xhr.open('post', 'json_code.php', true);
    xhr.setRequestHeader('Cache-Control', 'no-cache');
    xhr.send(form);
 } else {
  document.getElementById('mysubmit').click();
 }
}

function syntaxHighlight(json) { // thanks to https://stackoverflow.com/questions/4810841/how-can-i-pretty-print-json-using-javascript
    if (typeof json != 'string') {
         json = JSON.stringify(json, undefined, 2);
    }
    json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
    return json.replace(/(\"(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\\"])*\"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
        var cls = 'number';
        if (/^\"/.test(match)) {
            if (/:$/.test(match)) {
                cls = 'key';
            } else {
                cls = 'string';
            }
        } else if (/true|false/.test(match)) {
            cls = 'boolean';
        } else if (/null/.test(match)) {
            cls = 'null';
        }
        return '<span class=\"' + cls + '\">' + match + '</span>';
    });
}
</scr" . "ipt>
";

$selstuff = "&nbsp;<select onchange=seldo(this); id=selx><option value=>Optionally select a data idea below</option><option value='your_own_array'>Your own array</option><option value='your_own_entry'>Your own entry</option><option value='days_of_the_week'>Days of the Week</option><option value='months_of_the_year'>Months of the Year</option><option value='continents_of_the_earth'>Continents of the Earth</option><option value='top_ten_longest_river_lengths'>Top Ten Longest River Lengths</option><option value='  '>Am momentarily finished ...</option><option value=' '>Am finished ...</option></select>";

$tablestuff = "<table>
<tr id=trhead><th id=thstart></th><th>Column 1/5" . str_replace('selx','sel1',$selstuff) . "</th><th colspan=2>Column 2/5" . str_replace('selx','sel2',$selstuff) . "</th><th colspan=2>Column 3/5" . str_replace('selx','sel3',$selstuff) . "</th><th colspan=2>Column 4/5" . str_replace('selx','sel4',$selstuff) . "</th><th colspan=2>Column 5/5" . str_replace('selx','sel5',$selstuff) . "</th><th id=thend></th></tr>
<tr id=trcontent><td id=tdstart></td><td id=td1></td><td id=dtd2></td><td id=td2></td><td id=dtd3></td><td id=td3></td><td id=dtd4></td><td id=td4></td><td id=dtd5></td><td id=td5></td><td id=tdend></td></tr>
</table>
<form method=POST style=display:none; id=myform action=./json_code.php><input type=hidden id=injson name=injson value=></input><input style=display:none; type=submit id=mysubmit value=Submit></input></form>
";

if (isset($_GET['injson']) || isset($_POST['injson'])) {
if (isset($_GET['ajax']) || isset($_POST['ajax'])) {
if (isset($_GET['injson'])) {
  echo str_replace('+',' ',urldecode($_GET['injson']) );
} else {
  echo str_replace('+',' ',urldecode($_POST['injson']) );
}
} else {
if (isset($_GET['injson'])) {
  echo "<!doctype html><html>" . $cstyle . $jscr . "<body><h1>Using PHP <a target=_blank title='PHP json_encode information, thanks' href='//php.net/manual/en/function.json-encode.php'>json_encode</a> and <a target=_blank title='PHP json_decode information, thanks' href='//php.net/manual/en/function.json-decode.php'>json_decode</a> or Ajax FormData and Javascript <a target=_blank title=JSON.Parse href='//www.w3schools.com/js/js_json_parse.asp'>JSON.parse</a> and <a target=_blank title=JSON.Stringify href='//www.w3schools.com/js/js_json_stringify.asp'>JSON.stringify</a></h1><h3>RJM Programming</h3><h3>November, 2018</h3><div id=result>JSON in is " . str_replace('+',' ',urldecode($_GET['injson']) ) . "<br>";
  echo "<br>\$jd=json_decode('" . str_replace('+',' ',urldecode($_GET['injson']) ) . "'); // results in ...<br>";
  $jd=json_decode(str_replace('+',' ',urldecode($_GET['injson']) ));
  var_dump($jd);
  echo "<br>json_encode(\$jd); // results in ...<br><br>";
  echo json_encode($jd) . "<br>";
  echo "</div><br><hr><br>" . $tablestuff . "<br></body></html>";
  exit;
} else {
  echo "<!doctype html><html>" . $cstyle . $jscr . "<body><h1>Using PHP <a target=_blank title='PHP json_encode information, thanks' href='//php.net/manual/en/function.json-encode.php'>json_encode</a> and <a target=_blank title='PHP json_decode information, thanks' href='//php.net/manual/en/function.json-decode.php'>json_decode</a> or Ajax FormData and Javascript <a target=_blank title=JSON.Parse href='//www.w3schools.com/js/js_json_parse.asp'>JSON.parse</a> and <a target=_blank title=JSON.Stringify href='//www.w3schools.com/js/js_json_stringify.asp'>JSON.stringify</a></h1><h3>RJM Programming</h3><h3>November, 2018</h3><div id=result>JSON in is " . str_replace('+',' ',urldecode($_POST['injson']) ) . "<br>";
  echo "<br>\$jd=json_decode('" . str_replace('+',' ',urldecode($_POST['injson']) ) . "'); // results in ...<br>";
  $jd=json_decode(str_replace('+',' ',urldecode($_POST['injson']) ));
  var_dump($jd);
  echo "<br>json_encode(\$jd); // results in ...<br><br>";
  echo json_encode($jd) . "<br>";
  echo "</div><br><hr><br>" . $tablestuff . "<br></body></html>";
  exit;
}
}
} else {
  echo "<!doctype html><html>" . $cstyle . $jscr . "<body><h1>Using PHP <a target=_blank title='PHP json_encode information, thanks' href='//php.net/manual/en/function.json-encode.php'>json_encode</a> and <a target=_blank title='PHP json_decode information, thanks' href='//php.net/manual/en/function.json-decode.php'>json_decode</a> or Ajax FormData and Javascript <a target=_blank title=JSON.Parse href='//www.w3schools.com/js/js_json_parse.asp'>JSON.parse</a> and <a target=_blank title=JSON.Stringify href='//www.w3schools.com/js/js_json_stringify.asp'>JSON.stringify</a></h1><h3>RJM Programming</h3><h3>November, 2018</h3>" . $tablestuff . "<br><div id=result></div></body></html>";
}

?>