Answers for "php data in js"

PHP
8

php pass a variabele to js

<script>
'var name = <?php echo json_encode($name); ?>;
</script>'
Posted by: Guest on February-08-2020
1

get data from javascript to php

Passing data from PHP is easy, you can generate JavaScript with it. The other way is a bit harder - you have to invoke the PHP script by a Javascript request.

An example (using traditional event registration model for simplicity):

<!-- headers etc. omitted -->
<script>
function callPHP(params) {
    var httpc = new XMLHttpRequest(); // simplified for clarity
    var url = "get_data.php";
    httpc.open("POST", url, true); // sending as POST

    httpc.onreadystatechange = function() { //Call a function when the state changes.
        if(httpc.readyState == 4 && httpc.status == 200) { // complete and no errors
            alert(httpc.responseText); // some processing here, or whatever you want to do with the response
        }
    };
    httpc.send(params);
}
</script>
<a href="#" onclick="callPHP('lorem=ipsum&foo=bar')">call PHP script</a>
<!-- rest of document omitted -->
Whatever get_data.php produces, that will appear in httpc.responseText. Error handling, event registration and cross-browser XMLHttpRequest compatibility are left as simple exercises to the reader ;)

See also Mozilla's documentation for further examples
Posted by: Guest on March-20-2021
0

js data php

// In your controller
if(isset($_POST)){

    $obj = new MyObject();
    $obj->name = $_POST['name'];
    $obj->date = date("Y-m-d");
    $obj->validatePost();
    $obj->update();

    $result = $obj->getData();
    return $result;

}


// Your model
class MyObject {

    public $name;
    public $date;

    public function validatePost(){
        if($this->name == null){
            // print error
        }
    }

    public function update(){
        // database cheets
    }

    public function getData(){
        return $json;
    }

}
Posted by: Guest on June-23-2021

Browse Popular Code Answers by Language