Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
612 views
in Technique[技术] by (71.8m points)

ajax - How to write values coming from form input to json using php

Since I needed a server side language I used PHP. However I cannot write the data coming from the ajax using the JSON.stringify method.

$('#add-order').on('click',function(){

    //create an object for orders
    var order = {   

        name : $('#name').val(),
        drink : $('#drink').val()
    };

    $.ajax({
        url : 'add_order.php',
        type : 'POST',
        data : order,
        dataType : 'json',
        success : function(newOrder){
            console.log(newOrder.name);
            $('#orders').append('<li>' + newOrder.name + ' : ' + newOrder.drink + '</li>');
        },
        error: function(){
            console.log('error connecting');
        }
    });

});

Here's the index.php

<h4>Add a Coffee Order</h4>
<ul id="orders">

</ul>

<p><input type="text" id="name"></p>

<p><input type="text" id="drink"></p>

<button type="submit" id="add-order">Add</button>

add_order.php

   if (isset($_POST['submit'])) {
        $orders = $_POST['data'];
        $orderFile = fopen('api/orders.json', 'w');

       fwrite($orderFile, $orders);
       fclose($orderFile);
   }

When I hard coded any string to fwrite($orderFile, "my orders") it will write on the orders.json however when I used the $orders it's not working. Am i missing something here?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

you're posting to api/orders.json which is incorrect, you should be posting to the file that processes the request, like index.php.
Passing an object as the data parameter does not convert it to json, you have to actually do it yourself. So if you want $_POST['data'] to hold the order data as json

$.ajax({
    url : 'index.php',
    type : 'POST',
    data : {data: JSON.strinify(order)},
    dataType : 'json',
    success : function(newOrder){
        console.log(newOrder.name);
        $('#orders').append('<li>' + newOrder.name + ' : ' + newOrder.drink + '</li>');
    },
    error: function(){
        console.log('error connecting');
    }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...