When I try to access the object property outside the ajax when getting the value of an input it returns the correct value. But when I try to log and append that value inside the success function it returns undefined. How do I address this type of issue? It seems that object is local and cannot accessed by the ajax? Below is my code.
$('#add-order').on('click',function(){
//create an object for orders
var order = {
name : $('#name').val(),
drink : $('#drink').val()
};
$.ajax({
url : 'api/orders.json',
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.html
<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>
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.
<?php
if (isset($_POST['submit'])) {
$orders = $_POST['data'];
$orderFile = fopen('api/orders.json', 'w');
fwrite($orderFile, $orders);
fclose($orderFile);
}
I also updated my code on top.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?