Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
220 views
Welcome To Ask or Share your Answers For Others

1 Answer

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...