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