0

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?

Jay Gorio
  • 335
  • 2
  • 4
  • 22
  • Arent u writing it onto a JSON file, shouldnt u be writing it to the PHP file?and index.html should be index.php ;-)? or either replace the php code to correct file – Tredged Dec 24 '15 at 14:38
  • @Tredged thanks for the reply yeah its index.php – Jay Gorio Dec 24 '15 at 14:39
  • 1
    If you're sending the POST request that should write the file to `api/orders.json`, your PHP code that writes the file shouldn't be sitting in `index.html`. – Bergi Dec 24 '15 at 14:39
  • @Bergi oops typo error I edited the index.html to index.php – Jay Gorio Dec 24 '15 at 14:43
  • @Bergi please help I really need your help. – Jay Gorio Dec 24 '15 at 15:16
  • Now that you've fixed the issue with the resource URIs, your question is probably a dupe of [How can I use JQuery to post JSON data?](http://stackoverflow.com/q/6255344/1048572) – Bergi Dec 24 '15 at 22:16
  • Btw, if you expect `new_order` to have a value you'll need to respond back to the client with the written file. – Bergi Dec 24 '15 at 22:17
  • @Bergi the link you gave I already did with the stringify method. It doesnt solve my problem. – Jay Gorio Dec 25 '15 at 00:50
  • @JayGorio: Where do you already use the `JSON.stringify` method? What exactly is the problem? What is the value you are getting for `$orders`? – Bergi Dec 25 '15 at 23:44
  • @Bergi I already posted my solution anyways thanks for your long responses. – Jay Gorio Dec 26 '15 at 09:28

2 Answers2

1

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');
    }
});
Musa
  • 96,336
  • 17
  • 118
  • 137
0

Anyways I found already the solution. First I did was to serialize the inputs instead of using stringify.

    var order = {   
        name : $('#name').val(),
        drink : $('#drink').val()
    };     
    var inputs = $('form').serialize();
    $.ajax({
        url : 'add_order.php',
        type : 'POST',
        data : inputs,
        dataType : 'json',
        //some codes here...
   });

Then in my php file which is the add_order.php, I fetch the values passed by the data and make them as an array. I also make used of file_get_contents to read on the json file and file_put_content to write on the file as json.

$ordersFile = 'api/orders.json';
$order = array();

//grab the form input 

$formData = array(
            'name' => $_POST['name'],
            'drink' => $_POST['drink']
        );

$jsonOrders = file_get_contents($ordersFile);

$order = json_decode($jsonOrders, true);

echo json_encode($formData);

array_push($order, $formData);

file_put_contents($ordersFile, json_encode($order, JSON_PRETTY_PRINT));

But if you still have shorter solution then let me know.

Jay Gorio
  • 335
  • 2
  • 4
  • 22