AJAX to post javascript variable to php -


my question is: using ajax, how pass variable in javascript php code?

i know php server-side , javascript client side , i've read @ least dozen questions asking or pretty same thing each 1 seem missing because none of them work. in essence, using geolocation user's latitude , longitude on page load , testing purposes displays on page in respective divs. part works fine. issue comes when try submit data php variables doesn't connect or goes wrong, or maybe code incorrect on part.

here page testing in entirety "test.php":

<!doctype html> <html>   <head>    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>     <script>      x = navigator.geolocation;       x.getcurrentposition(success, failure);       function success(position) {         var mylat = position.coords.latitude;         var mylng = position.coords.longitude;         $('#latit').html(mylat);         $('#longit').html(mylng);      }      function failure() {         $('#latit').html("<p>it didn't work</p>")      }       //sends javascript 'mylat' , 'mylng' above php script//     $.post("test.php", { lat: mylat , lng : mylng});     </script>      </head>   <body>     <!--only validate geolocation function works-->     <div id="latit"></div>     <div id="longit"></div>      <div id="splash">         <h2>click button</h2>         <form action="test.php" method="post">           <input type="submit" name="submit" value="do thing!" />         </form>     </div>      <?php         //used validate passing of coordinates     if (isset($_post['lat'])) {         echo $lat = $_post['lat'];     }     if (isset($_post['lng'])) {         echo $lng = $_post['lng'];     }     ?>   </body> </html> 

i attempting pass js 'mylat' , 'mylng' php's $lat , $lng respectively. sincerely appreciated , apologize duplicate question, i'm not sure of better way frame i'm asking for.

additionally, if there's way without having click bonus i've found nothing that. i'm new web development/programming in general , have no experience javascript/jquery/ajax.

firstly, line:

$.post("test.php", { lat: mylat , lng : mylng}); 

should in success function. gets executed browser parses <script> tag, need make post request when location.

and secondly ajax request you've made won't have effect on loaded page, results of vanish, unless processed.

what can use $.load() on body element, replace contents of current body received one:

$(document.body).load("test.php", { lat: mylat , lng : mylng}); 

although better approach have script processes location send via ajax , render received content custom element html page.


Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -