Code Post

From rbachwiki
Revision as of 20:42, 16 November 2016 by Bacchas (talk | contribs) (Created page with "== Posting Data == ''' HTML FILE ''' <pre> <body> <div id="output"> </div> <input type="text" id="ftext" name="" value=""> <input type="text" id="dtext" name...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Posting Data

HTML FILE

  <body>
    
<div id="output">


</div>
    <input type="text" id="ftext" name="" value="">
    <input type="text" id="dtext" name="" value="">
    <button id="btn" type="">Click Me</button>

    <!--<script src="script.js"> </script>-->
     <script src="script2.js"> </script>

    </body>

JavaScript File

(function() {

    document.querySelector('#btn').addEventListener('click', showData);

    function showData() {
        var mydata, nameKey;
        var httpRequest = new XMLHttpRequest();

        mydata = document.getElementById('ftext').value;
        nameKey = document.getElementById('dtext').value;

        var myPost = "nameKey=" + encodeURIComponent(nameKey) + "&mydata=" + encodeURIComponent(mydata);

        httpRequest.onreadystatechange = function() {

            if (this.readyState === 4 && this.status === 200) {
                var response = JSON.parse(httpRequest.responseText);
                document.querySelector('#output').innerHTML = response.name + ' ' + response.data;
            } else {
                console.log('Not ready yet:');
            }

        };
        httpRequest.open('POST', 'test.php', true);
        httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        httpRequest.send(myPost);
        console.log(myPost);

    }

})();

PHP File

<?php

// ternerary if statement 
$name = (isset($_POST['nameKey'])) ? $_POST['nameKey']: 'No Name';
$data = (isset($_POST['mydata'])) ? $_POST['mydata']: 'No Data';


  $array = array("name"=>$name, "data"=>$data, "response"=>"Success");

echo json_encode($array);
?>

Back to previous page