1

I wanted to know if I can pass back individual parameters from a php script to be stored in dfferent JS variables on the page I'm working on, while also returning generated html code from the php script along with those parameters.

Basically I would like to return some data like this from php using ajax:

$valid = "true";
$access = "false";
$htmlcontent="lorem ipsum<br/>some more text<b>bold</b>";

And all of this should go into equivalent javascript variables on my page, using ajax, so that I can contruct my response on the page using this data...

2 Answers 2

3

Add the data to an array and json_encode then:

$ret = array();
$ret["valid"] = "true";
$ret["access"] = "false";
$ret["htmlcontent"] ="lorem ipsum<br/>some more text<b>bold</b>";
echo json_encode($ret);

And in your client side:

$.ajax({
    url:"your_script.php",
    success:function(resp) {
        var json = jQuery.parseJSON(resp)
        alert(json.valid)
    }
})
Sign up to request clarification or add additional context in comments.

Comments

1

Just let PHP print them directly as JS variables. It also saves your client one HTTP request.

<script>
    var valid = <?= $valid ?>;
    var access = <?= $access ?>;
    var htmlcontent = <?= json_encode($htmlcontent) ?>;
</script>

1 Comment

firs carefull with php short tags , and second what if he needs to build the variables depending on the users actions tracked with js ? he would need ajax instead of reloading the page .

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.