Rahul Kashyap
Rahul Kashyap

Reputation: 977

Uable to send POST data to JSON file via JQuery/AJAX, Why?

I am learning to process JQuery/Ajax from this video on YouTube, click here..

I'm not having any problem in receiving data from order.json file but when I am trying to POST data. I am always getting Error.

The code structure with screenshot and code is below, please help me.

Project folder screenshot:

enter image description here

HTML code:

<div class="wrapper">
<h1>Jquery  Ajax Tutorial</h1>

<h3>Coffie Orders</h3>

<ul id="orders"></ul>

<h4>Add a Coffie Order</h4>
<p>  Name: <input type="text" id="name"> </p>
<p>  Drink: &nbsp;<input type="text" id="drink"> </p>
<button id="add-order">Add!</button>

JQuery/Ajax code:

$(document).ready(function () {

  var $orders = $('#orders');

  var $name = $('#name');
  var $drink = $('#drink');

  function addOrder(order){
    $orders.append('<li>Name: '+ order.name +', Drink: '+ order.drink +'</li>');
  }

  $.ajax({
    type: 'GET',
    url: '/api/orders.json',
    success: function (orders) {
      $.each(orders, function(i, orders) {
        addOrder(orders);
      });
    },
    error: function(){
      alert('Error Loading Page');
    }
  });

  $('#add-order').click(function(){
    var order = {
      name: $name.val(),
      drink: $drink.val(),
    }

    $.ajax({
      type: 'POST',
      url: '/api/orders.json',
      data: order,
      success: function(newOrder) {
        addOrder(newOrder);
      },
      error: function(){
        alert('Error Adding Orders');
      }
    });
  });

});

JSON: order.json

[{
    "id": 1,
    "name": "James",
    "drink": "Coffiee"
}, {
    "id": 2,
    "name": "John",
    "drink": "Latte"
}]

Upvotes: 0

Views: 751

Answers (1)

Chaitanya Ghule
Chaitanya Ghule

Reputation: 451

Client side scripting languages are used to send and retrieve data which resides on server side. We can't use them to write/edit data on server side.

For doing so, we have to use server side scripting languages like PHP or ASP or any other which you prefer.

The video you referred was an API written in Core PHP used for retrieving / writing data from / to a json file which resides on server.

In my below code i have used PHP to write submitted data to a json file via jQuery/AJAX.

Check this out..

api/process.php

if (isset($_POST['params'])) {
  $params = $_POST['params'];

  $oldData = file_get_contents('orders.json');
  $tmp = json_decode($oldData);
  array_push($tmp, $params);
  $newData = json_encode($tmp);

  if (is_writable('orders.json')) {
    file_put_contents('orders.json', $newData);
    echo $newData;
  } else {
    echo "file is not writable, check permissions";
  }
}

index.html

<h1>Jquery  Ajax Tutorial</h1>

<h3>Coffie Orders</h3>

<ul id="orders"></ul>

<h4>Add a Coffie Order</h4>
<p>  Name: <input type="text" id="name"> </p>
<p>  Drink: &nbsp;<input type="text" id="drink"> </p>
<button id="add-order">Add!</button>
<script src='js/jquery.min.js'></script>
<script src='js/main.js'></script>

js/main.js

let $orders = $('#orders');
let $name = $('#name');
let $drink = $('#drink');

function addOrder(order) {
  $orders.append('<li>Name: '+ order.name +', Drink: '+ order.drink +'</li>');
}

$('#add-order').click(function(){
  let order = {
    name: $name.val(),
    drink: $drink.val()
  };

  $.ajax({
    type: 'POST',
    url: '/api/process.php',
    data: { params: order },
    success: function(resp) {
      addOrder(resp);
    },
    error: function(){
      alert('Error Adding Orders');
    }
  });
});

$.ajax({
  type: 'GET',
  url: '/api/orders.json',
  success: function (orders) {
    $.each(orders, function(i, orders) {
      addOrder(orders);
    });
  },
  error: function(){
    alert('Error Loading Page');
  }
});

api/orders.json

[
  {
    "id": 1,
    "name": "James",
    "drink": "Coffiee"
  },
  {
    "id": 2,
    "name": "John",
    "drink": "Latte"
  }
]

Note: Here, i am not writing id to json file for new orders.

Hope, this piece of code works fine for you. :) :)

Upvotes: 2

Related Questions