Transfer data Javascript to PHP (on click on confirm box) -
i wanted when user clicks on 'ok', write string in file (.txt) on server.
<script> if(confirm('capteur') == true){ /*write on file*/ } </script>
i thought can write javascript it, doesn't work way. so, want transfer data javascript php, indicates if php must write (or not) in file.
<script> if(confirm('capteur') == true){ /*send data php*/ } </script> <?php $var = //data send javascript if($var==1){ $fichier = fopen("log.txt",'a'); $puts($fichier,"restart"); fclose($fichier); } ?>
i tried solutions (ajax, redirection, post/get, jquery) never managed transfer data.
here test jquery:
<script> if(confirm('capteur') == true){ var variabletosend = 1; $.post('jv.php', {variable: variabletosend}); } </script> <?php $var = $_post['variable']; ?>
and here get/post :
<script>if(confirm('capteur') == true){ var xhr_object = null; if(window.xmlhttprequest){ xhr_object = new xmlhttprequest(); }else{ alert("your browser doesn't support xmlhttprequest object"); } xhr_object.open("post", "jv.php", true); xhr_object.setrequestheader("content-type","application/x-www-form-urlencoded"); xhr_object.send("variable=1"); /*xhr_object.open("get","jv.php?variable=1",true); xhr_object.send();*/ } </script>
what should best/simplest option?
you should try avoid using:
confirm("capteur") == true
since expression equivalentconfirm("capteur")
try following jquery:
var variabletosend = 1; $.post("somefile.php", {variable: variabletosend});
in
somefile.php
<?php if(isset($_post["variable"])) { $var = $_post["variable"]; //do stuff $var here } ?>
also, think have fundamental misunderstanding of how php works. of processing php occurs before see resultant page. if use ajax send data php page, nothing update on current page unless page result , update current page appropriately.
try understand little better:
<html> <head> <script type="text/javascript" src="http://code.jquery.com/jquery-2.1.4.min.js"> <script type="text/javascript"> if(confirm("click ok!")) { $.post("myphpfile.php", {data: "ok"}) .done(function(data) { alert(data); }); } </script> </head> <body> </body> </html>
in myphpfile.php
<?php if(isset($_post["data"])) { print "your message: " . $_post["data"]; } ?>
Comments
Post a Comment