Send data to json file using jquery/ajax and php

时间:2022-11-24 14:22:25

I'm having some trouble writing to a JSON file using ajax/jQuery along with PHP. The code I have currently is:

我在使用ajax / jQuery和PHP编写JSON文件时遇到了一些麻烦。我目前的代码是:

jQuery

 var object = {
    name: 'John',
    occupation: 'Lawyer'
}

$(".testing-php").click(function () {
    $.ajax({
        type: 'POST',
        data: {params:object},
        url: 'details.php',
        success: function (data) {
        console.log(object);
        alert('success');
        },
        error: function () {
            alert('error');
        }
    });

This part seems to be working correctly as the console.log statement correctly displays - {"name":"John","occupation":"Lawyer"}

这部分似乎正常工作,因为console.log语句正确显示 - {“name”:“John”,“Occup”:“Lawyer”}

My PHP file is currently like this:

我的PHP文件目前是这样的:

      <?php
var_dump($_POST);
if (isset($_POST['params']) && strlen($_POST['params'])) {
    $params = $_POST['params'];
    $jsonObject = json_encode($params);
    if (is_writable('js/details.json')) {
        file_put_contents('js/details.json', $jsonObject);
        echo "success";
    } else {
        echo "file is not writable, check permissions";
    }
} else {
    echo "invalid params";
}
?>

Finally, the current JSON file looks like this:

最后,当前的JSON文件如下所示:

{
"name": "Neil",
"occupation": "web developer"
}

Update

This is the information which the var_dump($_POST) displays. Along with the message .invalid params'.

这是var_dump($ _ POST)显示的信息。随着消息.invalid params'。

array(1) {
  ["params"]=>
  array(2) {
  ["name"]=>
string(4) "John"
["occupation"]=>
string(6) "Lawyer"
}
}
invalid params

The AJAX request parameters are on two different rows and are displayed as

AJAX请求参数位于两个不同的行上,并显示为

params[name]:"John"

params[occupation]:"Lawyer"

I am simply hardcoding values at the moment until I get the process working. Can anyone tell me what I am doing wrong here as the JSON file isn't being written to?

我只是简单地编码值,直到我让这个过程正常工作。因为没有写入JSON文件,任何人都可以告诉我我在做错了什么吗?

Many thanks

2 个解决方案

#1


3  

One extra ! in this test got you the exact opposite of what you meant to do (read it as "not"), removing it should help. Also added/changed some tests.

一个额外的!在这个测试中,你得到了与你想要做的完全相反的东西(读作“不是”),删除它应该有帮助。还添加/更改了一些测试。

It's also good practice to output something in your ajax query, so you can get some feedback from the server in your browser dev tools.

在ajax查询中输出内容也是一种很好的做法,因此您可以在浏览器开发工具中从服务器获得一些反馈。

<?php
var_dump($_POST);

if (isset($_POST['params'])) {
    $params = $_POST['params'];
    $jsonObject = json_encode($params);
    if (is_writable('js/details.json')) {
        file_put_contents('js/details.json', $jsonObject);
        echo "success";
    } else {
        echo "file is not writable, check permissions";
    }
} else {
    echo "invalid params";
}

UPDATE : Also updated your jQuery code to pass the params variable under a params key, for it to be picked up correctly server-side (no need to stringify as json by the way, jQuery does it on your behalf):

更新:还更新了你的jQuery代码,以便在params键下传递params变量,以便在服务器端正确选择它(顺便说一句,不需要将字符串化为json,jQuery代表你做):

    var object = {
        name: 'John',
        occupation: 'Lawyer'
    }

    $(".testing-php").click(function () {
        $.ajax({
            type: 'POST',
            data: {params:object},
            url: 'details.php',
            success: function (data) {
                console.log(params);
                alert('success');
            },
            error: function () {
                alert('error');
            }
        });

UPDATE : Also removed a test to accomodate an array-typed $_POST['params'].

更新:还删除了一个测试,以容纳数组类型$ _POST ['params']。

#2


0  

You may wish to do some validation to make sure your params got there safely.

您可能希望进行一些验证,以确保您的params安全到达那里。

#1


3  

One extra ! in this test got you the exact opposite of what you meant to do (read it as "not"), removing it should help. Also added/changed some tests.

一个额外的!在这个测试中,你得到了与你想要做的完全相反的东西(读作“不是”),删除它应该有帮助。还添加/更改了一些测试。

It's also good practice to output something in your ajax query, so you can get some feedback from the server in your browser dev tools.

在ajax查询中输出内容也是一种很好的做法,因此您可以在浏览器开发工具中从服务器获得一些反馈。

<?php
var_dump($_POST);

if (isset($_POST['params'])) {
    $params = $_POST['params'];
    $jsonObject = json_encode($params);
    if (is_writable('js/details.json')) {
        file_put_contents('js/details.json', $jsonObject);
        echo "success";
    } else {
        echo "file is not writable, check permissions";
    }
} else {
    echo "invalid params";
}

UPDATE : Also updated your jQuery code to pass the params variable under a params key, for it to be picked up correctly server-side (no need to stringify as json by the way, jQuery does it on your behalf):

更新:还更新了你的jQuery代码,以便在params键下传递params变量,以便在服务器端正确选择它(顺便说一句,不需要将字符串化为json,jQuery代表你做):

    var object = {
        name: 'John',
        occupation: 'Lawyer'
    }

    $(".testing-php").click(function () {
        $.ajax({
            type: 'POST',
            data: {params:object},
            url: 'details.php',
            success: function (data) {
                console.log(params);
                alert('success');
            },
            error: function () {
                alert('error');
            }
        });

UPDATE : Also removed a test to accomodate an array-typed $_POST['params'].

更新:还删除了一个测试,以容纳数组类型$ _POST ['params']。

#2


0  

You may wish to do some validation to make sure your params got there safely.

您可能希望进行一些验证,以确保您的params安全到达那里。