0

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.

3
  • try passing data in the correct format, as an object. creating a querystring yourself is shaky as hell, and is considered the incorrect method since jQuery 1.7 Commented Nov 6, 2014 at 14:57
  • Just a quick thought, could be wrong, but try taking out the question mark from the beginning of your data string. Commented Nov 6, 2014 at 14:57
  • When using mysqli you should be using parameterized queries and bind_param to add user data to your query. DO NOT use string interpolation to accomplish this because you will create severe SQL injection bugs. Commented Nov 6, 2014 at 15:44

2 Answers 2

2

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
});
Sign up to request clarification or add additional context in comments.

7 Comments

jQuery ajax documentations: data Type: PlainObject or String or Array
yes, and if you pass in a plain string, then you need to have data: {foo: yourstring}, which will show up as $_POST['foo']. OP has no key, just a bare string, so there's nothing in $_POST. The data could probably be retrieve from php://input, and then decoded manually.
You're making a post, not a get request. In a get request you may want your dataString to be formatted similar to how it is, but a post request sends the actual string or object, not url parameters.
@Marc B nope. var datastring = "param1=value1&param2=value2"; is also good, and it will be param1 and param2 value in the $_POST
Yes, and do not need that. Let's try it yourself.
|
0

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

7 Comments

Hi, after trying this I still have not had success. I'm still not quite sure what the problem is. I haven't changed the PHP script yet, other than changing the POST to GET and trying it with the browser address line to confirm that the SQL still works, and it does. It appears as if the variables just won't get passed in. I was able to echo the SQL error and I don't see any variables where text should be.
Nothing shows. No error no success. I'm using Firebug
are you getting the AJAX made alert? is there any error showing up in console.
Nothing is shown in console. AJAX made alert comes up. Success alert does not show
pls try the code now, there was a formatting issue in the earlier code
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.