简体   繁体   中英

how to use ajax to put value from javascript variable into a php variable

I need to get the value of a javascript variable and put it into a mysql database. I am trying to use jquery ajax function in (test.html) to Post the variable to a separate PHP file (external.php). I'm not sure why it's not working, I would appreciate any insight. Here are my two files:

Here is test.html:

<!DOCTYPE html>
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">

  </head>
  <body>

    <script>

$(document).ready(function () {
      var longitude = "print a longitude";


      $.ajax({
          url: "external.php",
          method: "POST",
          data: { "longitude": longitude }
      });
});



    </script>




  </body>
</html>

And here is external.php:

 <?php

    $longitude = $_POST['longitude'];
    echo json_encode($longitude);
    ?>

The code below works perfectly fine for me:

The external.php file:

<?php
    header('Content-Type: application/json');
    $longitude = $_POST['longitude'];
    echo json_encode($longitude);
?>

The test.html file:

<!DOCTYPE html>
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">

  </head>
<body>
<script>
$(document).ready(function () {
      var longitude = "print a longitude";


      $.ajax({
          url: "external.php",
          method: "POST",
          dataType: "json",
          data: { "longitude": longitude },
          success: function(data){
            console.log(data);
          }
      });
});
</script>
</body>
</html>

Also, make sure you are not running your file as:

file:///C:/Users/XXX/Desktop/XAMPP/htdocs/test.html

If you run it like this you would get this error:

XML Parsing Error: no root element found
Location: file:///C:/Users/XXX/Desktop/XAMPP/htdocs/external.php
Line Number 5, Column 3:

What you need to do is run Apache and then run the file as:

http://localhost/test.html

Below is the screenshot of what I get:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM