使用PHP将Ajax POST数据保存到文件

时间:2016-03-11 21:36:07

标签: php jquery mysql ajax

我使用ajax将一些数据发布到PHP文件并将其保存到MySQL数据库。这工作正常,但我也想将一个数据元素保存到服务器上的文本文件(应该创建),但我无法将其保存到文件中。

这是我的代码的外观:

jQuery (摘录)

        var uid = "1";
        var name = "bruno";
        var number = "0889-123-123";
        var location = "{"locationInfo":[{"title":"home","lat":-16.450902223672625,"lng":10.6103515625,"speed":""},{"title":"work","lat":-14.94621907436008,"lng":17.99560546875,"speed":""}]}"
        $.ajax({
        type: "POST",
        url: "process.php",
        data: {uid:uid, name:name, number:number, location:location},
        dataType: 'json',
        cache: false,
        })

PHP - process.php

<?php
    $inputvalues = $_POST;
    $errors = false;
    $result = false;
    $mysqli = new mysqli('localhost', "root", "", "tp");

        if (mysqli_connect_errno()) {
            printf("Connect failed: %s\n", mysqli_connect_error());
            exit();
        }
            foreach ($inputvalues as $key => $value) {
            if(isset($value) && !empty($value)) {
            $inputvalues[$key] = $mysqli->real_escape_string( $value );
            } else {
                $errors[$key] = 'The field '.$key.' is empty';
            }
        }

        if( !$errors ) {
            $mysqli->query("
                INSERT INTO `table`(`uid`, `name`, `number`) 
                values ('".$inputvalues['uid']."', '".$inputvalues['name']."', '".$inputvalues['number']."');
            ");
            file_put_contents('saved/file.txt', file_get_contents('".$inputvalues['location']."'));
        }
        mysqli_close($mysqli);
        $returnResult ="success";
        echo json_encode(['result' => $returnResult, 'errors' => $errors]);
        exit;
?>

2 个答案:

答案 0 :(得分:0)

改变这个:

file_put_contents('saved/file.txt', file_get_contents('".$inputvalues['location']."'));

到此:

file_put_contents('saved/file.txt', $inputvalues['location']);

此外,在JS中,您需要从location对象中删除引用。

应该是这样的:

var location = {"locationInfo": [{"title": "home", "lat": -16.450902223672625, "lng": 10.6103515625, "speed": ""}, {"title": "work", "lat": -14.94621907436008, "lng": 17.99560546875, "speed": ""}]};

答案 1 :(得分:0)

@CodeGodie $ inputvalues [&#39; location&#39;]似乎不包含文件位置。

也许是这样的?

file_put_contents('saved/file.txt', $inputvalues['location']);