0

So my problem is actually pretty simple:

I have this function (simplified) - it is triggered when a button is clicked:

$search.onclick = function () {

    // let's just say the user did put in a valid documentname
    // something like "John"
    documentname = $('#userinput').val();

    url = "https://example.api.url.com/" + documentname + "&format=json"

    // looks weird but "source = $.getJSON(url).done..." works like expected
    source = $.getJSON(url).done(function () {
        sourcestring1 = JSON.stringify(source);

        // this findid(); below is just a function that takes the id i'm looking for
        // out of the just stringified JSON (works also), it does "id = "123456"
        // (just a number but in string format)
        findid();

        // id has a value now ("123456"), so lets console.log it
            console.log(id);
    });
};


What I want to do is:

After findid(); is executed and id has a value I want to save this value as a readable file on the server. It's filename should be the same as the name of the document it's coming from (in this case John). The content of the file should just be the value of id (in this case 123456). Which file format? I don't know. And here is the next problem...


Reuse the file:

The next thing I wish I would be able to do is, to load this generated file when the exact documentname was inputted again by another user. Because if the file already exists, it would be unnecessary to load the whole JSON again. So the updated code would look like this (i know that this isn't actual code, but maybe it's easier to understand with this):

$search.onclick = function () {

    // another user inputs "John"
    documentname = $('#userinput').val();

    // so we want to prove if a file called "John" already exists on the server

    if ([A FILENAME ON THE SERVER] == documentname) {

        // if it exists, we just have to open that file and take the content (the id we saved before) out of it
        [OPEN FILE/TAKE CONTENT]

        // and just assign it to the variable
        id = [CONTENT OF FILE]

        // console.log it
        console.log(id);
    }
    else {

        // if it doesn't already exist, just run the normal code
        url = "https://example.api.url.com/" + documentname + "&format=json"


        source = $.getJSON(url).done(function () {
            sourcestring1 = JSON.stringify(source);

            findid();

            // console.log it
            console.log(id);

            // and of course save this now on the server
            [SOME PHP ACTION HERE]
        });
    }
};


I already tried a lot of things with Ajax and jQuery's $.get, I just have no idea how to handle sent things with PHP. I don't know which file format is best for this, or if this is even possible. I don't know how to transfer variables from JavaScript to PHP documents or how to use them there or vice versa.
PS: My developer environment: I don't run a server by myself, I have some webspace and a domain from a web service. Yes it supports PHP. MySQL and other database types are available too, if that's a useful information. jQuery is also installed.
Sorry again, for my bad english and for my lack of knowledge and interest in PHP and other serverside things. However, I hope you can help me somehow.
Nano Miratus
  • 467
  • 3
  • 13
  • 1
    What specific problem are you trying to solve by storing the data in a file on your server and not just making the same request to the api? Also your flow process should be to handle all this server side and only make one ajax request. – charlietfl Oct 14 '16 at 23:51
  • 1
    You don't want what you asked for. Draw a picture showing where the data should be at each step. You'll see that the JavaScript (which *only* runs in a user's browser) can't know whether the server has a file or not (`if ([A FILENAME ON THE SERVER] == documentname) {`) without asking the server. Asking the server looks like: `source = $.getJSON(url).done(function () {`. In your PHP file, *all* of the PHP stuff will run, *then* the browser will run the JavaScript stuff. It happens in that exact order every time, so stuff like `[SOME PHP ACTION HERE]` isn't going to fly either. – LinuxDisciple Oct 14 '16 at 23:51
  • If you're pulling back json data, why not use a NoSQL db storage like MongoDB? It will be much quicker for you to query on larger data sets. – Halfpint Oct 15 '16 at 16:21

3 Answers3

1

You can use localStorage to store a file at users browser configuration folder : user filesystem. If file exists at localStorage, use the file from localStorage without making $.getJSON() request, else call $.getJSON(); at success of $.getJSON() set the file at localStorage.

$search.onclick = function () { 
  // another user inputs "John"
  documentname = $('#userinput').val();

  // so we want to prove if a file called "John" already exists on the server    
  if (localStorage.getItem(documentname) != null) {

    // if it exists, we just have to open that file and take the content (the id we saved before) out of it
    // and just assign it to the variable
    id = localStorage.getItem(documentname);
    // console.log it
     console.log(id);
  }
  else {
    // if it doesn't already exist, just run the normal code
    // and of course save this now on the server
    // [SOME PHP ACTION HERE]
    url = "https://example.api.url.com/" + documentname + "&format=json"
    source = $.getJSON(url).done(function () {
               sourcestring1 = JSON.stringify(source);
               findid();
               // console.log it
               console.log(id);
               // set `localStorage` item key to `documentname`
               // set value to `id`
               localStorage.setItem(documentname, id);
             });
   }
};

See also How to cache a downloaded javascript fle which is downloaded using script tag

Community
  • 1
  • 1
guest271314
  • 1
  • 15
  • 104
  • 177
0

Flow process to make this work should be more like:

  1. ajax request to php endpoint on server.
  2. php checks if data stored locally ( in file or database)
  3. If not stored already , php makes request to other api. When the api returns data, php stores it in file or database.
  4. php returns the data to ajax from either the local source or from api response.

So the javascript would only make one request to your server and get the data returned and not know or care how php found it

charlietfl
  • 170,828
  • 13
  • 121
  • 150
-1

jQuery has a $.post() function, https://api.jquery.com/jquery.post/

$.post(url, { id: 123456 });

or

$.ajax({
    method: 'POST',
    url: 'http://example.api.domain.net/document.php',
    data: { id: 123456 },
    success: function(responseData) {
    }
});

PHP will then be able to read it like so:

$post_data = $_POST['id'];
// Here you do whatever with it, for example store to database