1

I have come codes like this:

<script>
CONT_TEXT = 'Some Text'

var jsobj = <?php json_encode(array(
   'prop1' => 'something',
   'prop2' => 'CONT_TEXT',
   'prop3' => 'location.host',
)) ; ?>;


alert(jsobj.prop2);
alert(jsobj.prop3);
</script>

output is:

<script>
CONT_TEXT = 'Some Text'

var jsobj = {"prop1":"something","prop2":"CONT_TEXT","prop3":"location.host"};


alert(jsobj.prop2);
alert(jsobj.prop3);
</script>

I wanna first alert show: Some Text and second show website host property. that means this:

<script>
CONT_TEXT = 'Some Text'

var jsobj = {"prop1":"something","prop2":CONT_TEXT,"prop3":location.host};


alert(jsobj.prop2);
alert(jsobj.prop3);
</script>

" is my problem!

how can I pass javascript constrants via json_encode in PHP?

whats your idea?

2
  • Did you try to display prop3 only? Commented Aug 3, 2013 at 22:52
  • JSON can only contain data. You cannot have references to external variables in JSON encoded data. You could encode that information (i.e. a reference to a variable) as (e.g.) string and then decode it on the client side. But you'd have to create your own logic for that. How you encode the information is up to you, there is no best practice for that. Commented Aug 3, 2013 at 23:02

4 Answers 4

1

I looked around in the PHP flags for json_encode but could't find anything that would help. So why don't you try to use the javascript eval() metode.

like this:

alert(eval(jsobj.prop2));
alert(eval(jsobj.prop3));

View these docs: eval()

I don't know if this is the best way, but i got inspired by this post. Try to use this function instead of eval:

function safe_eval(prop)
{
    try {
       return eval(prop);
    } catch (e) {
        return prop;
    }
}

It will either return the eval()-ed variable value or only the string in case eval() fails.

Sign up to request clarification or add additional context in comments.

2 Comments

prop are so much and i dont know which must through eval functions. but +1 for that it is a solution.
I c. maybe adding meta_data like svidgen or segment your php array in 2 like this: $prop_array = array("js_variables" => array(...), "plain_text" => array(...)) and then process the values separatly in the frontend.
1

There's no "natural" solution. But, nothing prevents you from creating a "protocol" of sorts. You could use an inner object with a particular key to replace with the constant values as-needed.

{"a":"text", "b":{"_ref":"CONST"}}

Or give each object a type:

{
  "__type": "SomeClass",
  "propertyA": "valueA",
  "propertyB": {
    "__type": "Reference",
    "value": "CONST"
   }
}

And instantiate them accordingly. Something like this [completely untested code]:

function instantiate(o, classRepository) {
  var rv;
  var classes = classRepository || window;

  if (o.__type && classes[o.__type] && typeof(classes[o.__type]) == 'function') {
    rv = new classes[o.__type]();
  } else {
    rv = {};
  }

  // instantiate all potentially instantiable child objects
  for (var i in o) {
    if (typeof(o[i]) == 'object') {
      rv[i] = instantiate(o[i]);
    } else {
      rv[i] = o[i];
    }
  }

  return rv;
}

var typedObject = instantiate(untypedObject);

An alternative to copying properties over after object construction might be to set a pattern wherein all constructors accept an object from which to consume only the relevant properties.

4 Comments

if give me a fiddle or complete functions to do this, I click this answer as accepted answer.
@EmRa228: Don't you understand the answer or what's your problem? We help you to find a solution, but we don't code everything for you. You have to do a little on your own. Or pay someone to do it for you.
@FelixKling I didnt understood that answer and with an example maybe I found it!
@EmRa228 I'll pass on the fiddle. I've added some untested sample code to hopefully set you in a right direction though ...
0

I was also thinking of another way. I don't think it's a very "clean" way but since you are echo-ing a string in php, you could also process this string and simply remove the quotes, e.g. with some regex preg_replace.

$json_string = json_encode(array(
     'prop1' => 'something',
     'prop2' => 'CONT_TEXT',
     'prop3' => 'location.host',
)) ;

echo preg_replace('/("prop2":|"prop3":)"([a-zA-Z_\.]+)"/', '$1$2', $json_string);

Just a thought

1 Comment

That might work in this case, but not when you really have to parse the JSON.
-1

The javascript constrant is clientsite and php serverside. You may try using an ajax call passing a get parameter with the content of your constrant but that is a bit of a workaround.

1 Comment

PHP(server side) not need to know values of javascript constrant. just must echo var jsobj = {"prop1":"something","prop2":CONT_TEXT,"prop3":location.host};. JS do jobs yourself.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.