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?

10
  • 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 Commented Dec 24, 2015 at 14:38
  • @Tredged thanks for the reply yeah its index.php Commented Dec 24, 2015 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. Commented Dec 24, 2015 at 14:39
  • @Bergi oops typo error I edited the index.html to index.php Commented Dec 24, 2015 at 14:43
  • @Bergi please help I really need your help. Commented Dec 24, 2015 at 15:16

2 Answers 2

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');
    }
});
Sign up to request clarification or add additional context in comments.

1 Comment

Im writing it on a 'api/order.json' and my add_order.php is my url. Whats wrong with this?
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.