简体   繁体   中英

pass an array of objects from jquery to php and save to database

Hi I have been trying to pass an array of objects with geolocation data from jquery to a php script to save to a database. been up all night trying to get this working so may be missing something small from lack of sleep.

the jquery objects stucture is the following

var testData = [];            

        var coords = {
        lat: 12.6544885,
        lng: 23.545665
        };

        var pos = {
         timestamp: 1222355465,
          latlng: coords
            };

            testData.push(pos);


            var coords = {
        lat: 55.6544885,
        lng: 55.545665
        };

        var pos = {
         timestamp: 555,
          latlng: coords
            };

            testData.push(pos);

I am trying to post this via .ajax using the following

$.ajax({
            type: 'POST',
            data: JSON.stringify(testData),
            //change the url for your project
            url: 'www.mydomain.com/save2.php',
            success: function(data){
                console.log(data);
                alert('Sucess');
            },
            error: function(){
                console.log(data);
                alert('Error');
            }
        });

and I am decoding at the php side and attempting to place in a database using the following.

$myData = json_decode($_REQUEST['testData']);

$sql = "INSERT INTO walk (timestamp, latitude, longitude) ";
$sql .= "VALUES ($myData->timestamp, $myData->latlng->lat, $myData->latlng->lng)";

I would appriciate any input on this issue thanks.

In ajax options, try changing data: JSON.stringify(testData), to

data: { 'testData': JSON.stringify(testData) },

otherwise you won't have a valid query string.

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