-1

I have a json file in localstorage and i have assigned that json to a variable with javascript so that i can access that with php. Now i want to append the values of that json file in my localstorage to the json file in my webserver.

this is the sample javascript code how i added the localstorage json to variable

var lstore = ('data:application/json;charset=utf-8,' + encodeURIComponent(localStorage.regions));

now when i run window.open(lstore); in javascript program, i am able to see the complete json array in the browser window.

sample json array looks like this

[{
  "start":6,
  "end":8.2,
  "data":{
          "note":"ex1"
         }},
 { 
   "start":8.6,
   "end":12.2,
   "data":{
           "note":"rtt save"
          }},
 {
   "start":12.8,
   "end":16.2,
   "data":{
            "note": "rtl rss"
          }},

what i want to do is call a php script from javascript and then append the values of my localstorage json data to the json file on my webserver. But also i want to check if the same "start" and "end" values is already present in the json file in my server then just update the "note" value orelse add the new "start", "end" and "data" value.

Álvaro González
  • 142,137
  • 41
  • 261
  • 360
prem pattnaik
  • 165
  • 4
  • 9
  • Welcome to Stack Overflow. You can format source code with the [Code Sample `{}`](http://i.stack.imgur.com/VYd26.png) toolbar button—I've done it for you this time. – Álvaro González Oct 31 '16 at 15:20
  • I didn't quite understand what you want but if i am right, you should that json object you have to a .php file, and then in .php file use json_decode() to decode a json object to string. I don't know if that was helpful. – Antonios Tsimourtos Oct 31 '16 at 15:29

1 Answers1

1

First we have to understand 3 core concepts here:

  1. Your javascript lives in the browser of your local computer(clientside).
  2. Your PHP runs on the remote server(serverside).
  3. The life circle of a web-app gets executed in requests(each time you send/getsomething from your browser).

You can't directly communicate them in realtime out of the box. You can however, send a request from your javascript(clientside) to your server(serverside).

Using JQuery its quite easy. In your javascript file you do:

$.post('/yoursite.com/your_php_script.php', lstore);

That will send an AJAX request to your server. Now in your_php_script.php you have to capture the content of that JSON.

$data = json_decode(file_get_contents('php://input'));

This reads the JSON from the body of the request you just sent.

You might want to use Chrome dev-tools and check out the network tab. There you can see all the information about the request. Good luck!

Patrick
  • 203
  • 1
  • 9