Skip to content
Advertisement

Fetch json data if json still not created [closed]

This is a sample of my form in php:

    echo "<form method='GET' action='queries.php'>
           <label>name1</label>
           <input type='checkbox' name='name1'/>
           <label>name2</label>
           <input type='checkbox' name='name2'/>
           <label>name3</label>
           <input type='checkbox' name='name3'/>
           <input type='submit' name='sendData' value='Send'/>
          </form>";

I take all the values in $_GET and i want to pass them in json to the frontend

$data = isset($_GET) ? $_GET : 0; 
 
 if (count($data)>0) {
   $res = $data;
   echo json_encode($res);
  } else {
   $noData -> Message = "No data passed";
    echo json_encode($noData); 
  }    

The problem is when i try to fetch with any http request the json generated from the form. I always get the $noData json instead of $res.

I need to use the data generated on a subsequent request. What would you suggest me to use to do that?

Advertisement

Answer

You need to store the data somewhere more permanent. Maybe in a file, or a database perhaps.

Or, if you only need the data for this user within their current usage session, then you could store it in the PHP Session. It depends on your exact requirements.

But the important thing to learn from this is that web applications are stateless – and therefore information held in ordinary PHP variables does not persist between different HTTP requests. If you want to keep the information submitted by the user, you need to have code to store it (and then more code to retrieve the correct information on a subsequent request).

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement