doubu1950 2016-03-11 21:36
浏览 172
已采纳

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

I am posting some data to a PHP file using ajax and saving it to a MySQL database. This works fine, but I also want to save one of the data elements to a text file (which should be created) on the server but I can't get it to save to a file.

This is how my code looks:

jQuery (snippet)

        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
", 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条回答 默认 最新

  • dotaer1993 2016-03-11 21:53
    关注

    change this:

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

    to this:

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

    Also, in JS you need to remove the quotations from your location object.

    It should be like this:

    var location = {"locationInfo": [{"title": "home", "lat": -16.450902223672625, "lng": 10.6103515625, "speed": ""}, {"title": "work", "lat": -14.94621907436008, "lng": 17.99560546875, "speed": ""}]};
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?