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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…