Transmit JSON information from one webpage and dynamically retrieve it from another page via AJAX while both pages are active

I am attempting to transfer JSON data from page1 when the submit button is clicked and then retrieve this data dynamically from page2 using AJAX in order to display it in the console. I am unsure of the correct syntax to accomplish this task. There was a suggested code that did not work as expected. The provided code is below:

page1:

<?php
if(isset($_POST["submit"])){
    $x = "ok";
    echo json_encode($x);
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>page1</title>
</head>
<body>
    <p>This page sends JSON data upon clicking the submit button.</p>
    <form method="post">
        <input type="submit" name="submit">
    </form>
</body>
</html>

page2:

<!DOCTYPE html>
<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
    <META HTTP-EQUIV="Pragma" CONTENT="no-cache">
</head>

<body>
<p>Retrieve JSON data from page1 dynamically using ajax</p>

<script>
    setInterval(checkVariableValue, 5000);
    function checkVariableValue() {
         $.ajax({
              method: 'POST',
              url: 'page1.php',
              datatype: 'json',
              success: function(data) {
                  console.log(data);
              }
         });
    }
</script>

</body>
</html>

What modifications should be made to ensure proper functionality?

Answer №1

Follow this example to achieve the desired result:

    Start a session;
    Check if the request method is POST and submit button has been clicked;
       If so, set a value such as 'I am test' to a session key named 'key';
    Otherwise, if the request method is POST without clicking submit button:
       Display the value stored in $_SESSION['key'].

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Incorporate a Music Collection onto a Webpage with API Integration (PHP)

Recently, I encountered an issue while trying to set up an album for a specific page. The error message that appeared was: [15-Sep-2011 22:38:14] PHP Fatal error: Uncaught OAuthException: (#100) Invalid ID for album owner thrown in C:\inetpub&bsol ...

Tips for resolving error "Exception in main thread java.lang.NoClassDefFoundError: com/fasterxml/jackson/annotation/JsonView":

I am attempting to assess a json string by utilizing the jackson library's ObjectMapper. I have included the jackson-annotation, jackson-databind, and jackson-core dependencies with the matching version in the pom.xml file. However, the code is produc ...

Ajax is struggling to achieve any positive outcomes

I recently started exploring ajax and I'm having trouble figuring out what's causing the issue with the code? page.html <html> <head> <title>Ajax request</title> <script src="https://cdnjs.cloudflare.com/ajax/ ...

Adjust the size of the Div and its content to fit the dimensions of

Currently, I have a div containing elements that are aligned perfectly. However, I need to scale this div to fit the viewport size. Using CSS scale is not an option as it does not support pixel values. https://i.stack.imgur.com/uThqx.png I am looking to ...

How to flip the value in v-model using VueJS

Below is the code snippet that I am working with: <input v-model="comb.inactive" type="checkbox" @click="setInactive(comb.id_base_product_combination)" > I am looking to apply the opposite value of comb.inactive to the v-model. Here are m ...

I encountered an error while trying to synchronize my Redux state with the component state

Upon clicking the advanced sports search button, I need to display a drawer containing my API values. Currently, when mapping my Redux state with component state, an error is occurring stating "Actions must be plain objects. Use custom middleware for async ...

Error message encountered while using SPARK: read.json is triggering a java.io.IOException due to an excessive number

Encountering an issue while trying to read a large 6GB single-line JSON file: Error message: Job aborted due to stage failure: Task 5 in stage 0.0 failed 1 times, most recent failure: Lost task 5.0 in stage 0.0 (TID 5, localhost): java.io.IOException: Too ...

Android response JSON scrambled

The server's response looks something like this: { "data": { "table": { "0": { "pay_date": "2017-04-28", "status": "Paid", "bill_date": "2017-04-27", }, "1": { "pay_date": "2 ...

What causes the discrepancy in the expiresIn value of my JWT when it is transmitted from the server to the front-end?

After setting the token expiry date on the server, I decided to log out the value to double-check it. However, upon checking the value on my React front-end, I noticed a significant change in the value received compared to what was sent from the server. Is ...

Vue CLI Plugin Electron Builder displays a completely empty screen after compiling

After building my electron app using this specific plugin, I encountered a frustrating issue where the installed package would only display a blank, white screen. Despite setting up the window to open dev tools in the built version, inspecting the page rev ...

Which option is more beneficial for intercepting API data in Angular 6: interfaces or classes?

My API returns JSON data that is not structured the way I need it, so I have to make changes. { "@odata.context":"xxxxxx", "id":"xxxxxxxx", "businessPhones":[ ], "displayName":"name", "givenName":"pseudo", "jobTitle":null, "ma ...

Why isn't my data appearing when using $http.get in AngularJS?

I'm encountering an issue where my bar graph doesn't display data when using $http.get. However, if I eliminate $http.get and directly call the URL, the data shows up perfectly. Any suggestions on what might be causing this problem? AngularJS v ...

An error occurred while trying to serialize the `.res` response received from the `getServerSideProps` function in

I encountered the following issue while utilizing the getServerSideProps function to fetch data from Binance API. import binance from "../config/binance-config"; export async function getServerSideProps() { const res = await binance.balance(( ...

Troubleshoot the issue of ng-click not functioning properly when used in conjunction with ng-repeat with direct expressions

Having some trouble with an ng-repeat block and setting a $scope variable to true with an ng-click expression. It doesn't seem to be working as expected. Can anyone help out? Check the plnkr for more information. HTML: selected: {{selected}} < ...

The result of Document.getElementById can show as "undefined" despite the presence of the element

Currently, I am tackling a project that involves extracting information from a website. I have opted to use the 'puppeteer' library in Node.Js for this task. However, I am encountering an issue where Document.getElementById is returning "undefine ...

Encountering a TypeError in Material UI React Autocomplete

I tried using the demo code from here in my application, but it's not functioning as expected. I'm unsure of the differences between my code and the example on the website. The errors I'm encountering are: react-dom.development.js:14724 Unc ...

Updating a database with a loop of React Material UI toggle switches

I am trying to implement a material UI switch feature that can update the Active and De-Active status of users in the database directly from the Admin Panel. Currently, the database updates are functioning correctly when toggling the switches. However, th ...

Is there a way for me to retrieve dynamic text?

I used an "IF" statement to display dynamic text - if it's null, show something, otherwise show something else. However, I am getting a blank result. What did I do wrong? <View style={styles.rightContainer}> { () =>{ if(t ...

Error: The initial parameter must be a string, Buffer, ArrayBuffer, Array, or Array-like Object. An object type was passed in instead in CryptoJS

In my quest to encrypt and decrypt data in react-native, I embarked on using the crypto node module by incorporating it into my react native project through browserify. While attempting encryption with the code snippet provided below, an error surfaces sta ...

How can I retrieve the position of a div or an image within a div (specifically the top and left coordinates) and incorporate these values into CSS?

I'm currently working on a website that is dynamic and utilizes bootstrap. I am looking to incorporate an animation where the dynamic thumbnails in the col-md-4 div zoom to 100% when clicked, appearing at the center of the container. I am struggling ...