0

I have an input field generated by PHP with a variable inside. Sometimes it is a string, sometimes it can be an array:

// IF IT IS A STRING
//$var = "value";

// IF IT IS AN ARRAY
$var = array("value1", "value2", "value3");

<input type="text" id="test" value="<?php if ( is_array($var) ) { echo json_encode($var); } else { echo $var; } ?>"

Now this input field is passed to a second page and i need to check ONLY VIA JAVASCRIPT if the input is a string or an array:

$(document).ready(function(){
  var test = $("#test").val();
  if ( Object.prototype.toString.call(test) === '[object Array]' ) {
    alert("YES");
    var ok = JSON.parse(test); //manage "ok" like an array
  } else {
    alert("NO");
    var ok = test; // manage "ok" like a string
  }
});

But i always get the NO alert! I've also tried if ( JSON.parse(test) ) {}. It works ok if is an array. But if it is a string my script break with console error: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

Philipp Maurer
  • 2,480
  • 6
  • 18
  • 25
Giuseppe Lodi Rizzini
  • 1,045
  • 11
  • 33
  • 2
    for js both will be a string. You'd need to check _if it can be parsed as json successfully_. So instead of `if ( Object.prot...` do a `JSON.parse(test)`, check the return – Jeff Jan 09 '18 at 13:52
  • yes. what is the command to check? JSON.parse break my script – Giuseppe Lodi Rizzini Jan 09 '18 at 13:53
  • 1
    [Array.isArray](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray) – James Jan 09 '18 at 13:56
  • 2
    [how-to-test-if-a-string-is-json-or-not](https://stackoverflow.com/questions/9804777/how-to-test-if-a-string-is-json-or-not) – Jeff Jan 09 '18 at 13:56
  • You could also `json_encode` the string variable in PHP, which would turn the string `value` into the string `"value"`. It then could be parsed by `JSON.parse`. – Philipp Maurer Jan 09 '18 at 13:58

0 Answers0