javascript - How can I print PHP POST data using AJAX? (no jQuery) -
so i've got html.
<form method="post" id="myform" onsubmit="getdata()"> <fieldset> <legend>form</legend> <label>color: <input type='text' id="color" name='color'></label> <label><input type="submit"></label> </fieldset> </form> <div id="showoutput"> </div>
this php:
<?php $color = $_post['color']; if($color != "") { $color = htmlentities($color, ent_quotes); print "<p>the color $color</p>"; } else { print "<p>fill out form!</p>"; } ?>
and js:
window.onload = getdata; var req = new xmlhttprequest(); function getdata() { var poststr = "color=" + encodeuri( document.getelementbyid("color").value ); req.open("post", "lab11-1.php", true); req.onreadystatechange = useresponse; req.setrequestheader("content-type", "application/x-www-form-urlencoded"); req.send(poststr); } function useresponse() { if(req.readystate == 4) { if(req.status == 200) { document.getelementbyid('showoutput').innerhtml = req.responsetext; } } }
i'm trying able input color in form, hit submit, , use ajax print php "showoutput" div in html. i've tried can think of , haven't been able figure out.
i think not correct. ajax don't need form submit function,
i did this, think want it.
<form method="post" id="myform"> <fieldset> <legend>form</legend> <label>color: <input type='text' id="color" name='color'></label> <label><input type="button" onclick="getdata()" value="submit"></label> </fieldset> </form> <div id="showoutput"> </div> <script> window.onload = getdata; var req = new xmlhttprequest(); function getdata() { var poststr = "color=" + encodeuri( document.getelementbyid("color").value ); req.open("post", "test.php", true); req.onreadystatechange = useresponse; req.setrequestheader("content-type", "application/x-www-form-urlencoded"); req.send(poststr); } function useresponse() { if(req.readystate == 4) { if(req.status == 200) { document.getelementbyid('showoutput').innerhtml = req.responsetext; } } } </script>
Comments
Post a Comment