简体   繁体   中英

Trying to pass POST from JavaScript to PHP

For a few days now I have been trying to pass a simple POST call to a php script from JavaScript. I've done countless amounts of searching online without any positive results.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">

function successHandler(location) {
    var dataString = '?lat=' + location.coords.latitude + '&long=' + location.coords.longitude + '&accuracy=' + location.coords.accuracy;
    alert(dataString);
    if (location.coords.latitude == '0') {
    } else {
        alert("AJAX made");
        $.ajax({
            type: "POST",
            url: "updatepos.php",
            data: dataString,
            cache: false,
            success: function(html) {
                alert(html);
            }
        });
        setTimeout(navigator.geolocation.getCurrentPosition(successHandler),15000);
    }
}

function getLocation() {
    navigator.geolocation.getCurrentPosition(successHandler);
}

getLocation();

</script>

Above is my JavaScript file. The datastring gets made, and it alerts it out to my browser. No problem there. The problem is, my variables don't get passed to PHP whatsoever.

Here is the PHP that is in the same directory as the JavaScript.

<?php
include 'wp-load.php';
/*global $current_user;
get_currentuserinfo();

echo $current_user->user_login;*/

include('dbconnect.php');
global $current_user;
get_currentuserinfo();
$lat = $_POST['lat'];
$long = $_POST['long'];
$accuracy = $_POST['accuracy'];
/*$lat = $_GET['lat'];
$long = $_GET['long'];
$accuracy = $_GET['accuracy'];*/
$query = "UPDATE ltc_users SET lat='$lat',accuracy=$accuracy,lon='$long' WHERE name='$current_user->user_login'";
mysqli_query($GLOBALS['DB'],$query);
echo mysqli_error($GLOBALS['DB']);
echo $lat;
echo $long;
echo $accuracy;
echo $current_user->user_login;
?>

I may note that before the script would return mysql syntax errors as it was echoed in php due to missing variables. The syntax works if I use the $_GET method and just type in the data into my browser address bar for testing. It just doesn't get the JavaScript variables for whatever reason.

You're passing a string to jquery. When you do that, the string is sent out as-is by jquery. Since it's just a bare string, and not a key:value pair, there's no key for PHP to glom onto and populate $_POST with.

In fact, you shouldn't ever have to manually build a string of key:value pairs for ajax - jquery will take an array/object and do it all for you:

var stuff = {
    lat : location.coords.latitude,
    long : location.coords.longitude,
    accuracy : location.coords.accuracy
}

$.ajax({
   data: stuff
});

Here is your code combined with @Marc B

<script src = "http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" > </script>
<script type="text/javascript">

function successHandler(location) {

    if (location.coords.latitude == '0') {
    } else {
        alert("AJAX made ");
        $.ajax({
            type: "POST",
            url: "updatepos.php",
            data: {
              "lat":location.coords.latitude,
              "long":location.coords.longitude,
              "accuracy":location.coords.accuracy
            },
            dataType: "json",
            async:true,
            cache: false,
            success: function(html) {
                alert(html);
            },error: function(a,b,c){
                console.log(a.responseText);
            }
        });
        setTimeout(function(){navigator.geolocation.getCurrentPosition(successHandler);},15000);
    }
}

function getLocation() {
    navigator.geolocation.getCurrentPosition(successHandler);
}
$(function(){
  getLocation();
});

</script>

code in jsfiddle http://jsfiddle.net/y7f1vkej/ it seems to be working for me

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