What is the best way to retrieve data from a JavaScript function and store it in a user's custom meta field using PHP?

Currently, I am utilizing a platform that automates the device registration process for my users through Onesignal.

Upon user login, I invoke the function by using gonative_onesignal_info(); within script tags (the full function is provided below). This successfully registers the devices with Onesignal.

Now, as per the platform's guidelines, I am supposed to send this information to my server via AJAX, which is where I am facing difficulties. As mentioned in the platform's documentation, if you call gonative_onesignal_info() as shown below:

function gonative_onesignal_info(info) {
    console.log(info);
}

...the 'info' object will contain the following details:

{
    oneSignalUserId: 'xxxxxxx',
    oneSignalPushToken: 'xxxxxx',
    oneSignalSubscribed: true,
}

Here is the complete function implementation:

function onesignal_mobile_registration( $user_login, $user ) {

    // Obtain user data
    $user_id = $user->ID;
    $user_email = $user->user_email;

    ?>

        <script>
            gonative_onesignal_info(info);
        </script>

    <?php

    $oneSignalPushToken = ???;
    update_user_meta( $user_id, 'oneSignalPushToken', $oneSignalPushToken);

}
add_filter( 'wp_login', 'onesignal_mobile_registration', 10, 2 );

Hence, my question is - how can I extract the 'oneSignalPushToken' from the JavaScript object and assign it to $oneSignalPushToken for storage in my user records? Do I need to utilize AJAX for this extraction process? If so, could you guide me on how to proceed?

Answer №1

To transfer a php variable from javascript, you need to consider the difference in their environments - php runs on the server-side while javascript runs on the client-side browser. One way to achieve this is by fetching the $oneSignalPushToken value from a php source or by using an ajax call from the browser to pass data to the php variable:

Here's where the script should be placed:

<script>
    var data = gonative_onesignal_info(info);
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open('GET', 'test.php?oneSignalPushToken=' + data.oneSignalPushToken, true);
    xmlhttp.send();
</script>

In test.php:

function onesignal_mobile_registration( $user_login, $user ) {

    // Retrieve user data
    $user_id = $user->ID;
    $user_email = $user->user_email;

    $oneSignalPushToken = $_GET['oneSignalPushToken'];
    update_user_meta( $user_id, 'oneSignalPushToken', $oneSignalPushToken);

}
add_filter( 'wp_login', 'onesignal_mobile_registration', 10, 2 );

Answer №2

Understanding the functionality of your code is crucial:

  • The PHP segment will generate an HTML page
  • The JavaScript portion will run in the browser once the page is fully loaded and displayed

This implies that you cannot access a JavaScript variable within the PHP process responsible for creating the page, primarily due to two reasons:

  • JavaScript and PHP operate in separate execution environments
  • JavaScript runs after the PHP process completes

To address this, you need to create an endpoint on your PHP server, such as using a POST method on a /token URL. You can then make a call to this endpoint from your JavaScript code like

fetch('/token', { method: 'POST', body: info });
, retrieve the token from the $_POST global variable, and finally execute your
update_user_meta( $user_id, 'oneSignalPushToken', $oneSignalPushToken);
command

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

Including JavaScript in HTML Error 404

https://i.stack.imgur.com/aQDPG.png I am struggling to understand why this import is not functioning as expected. I have tried using script/import.js but it still fails to work. The error message I keep receiving is: 127.0.0.1 - - [09/Sep/2020 15:09:35] ...

Upon executing the `npm start` command, the application experiences a crash

When I tried following the steps of the Angular quickstart guide, I encountered some errors after running "npm start". Here are the errors displayed: node_modules/@angular/common/src/directives/ng_class.d.ts(46,34): error TS2304: Cannot find name 'Se ...

Is it possible to store a JavaScript object (including methods) within MongoDB?

I am looking for a solution to store objects containing text formatting methods and CSS styles in a MongoDB collection using Mongoose. The structure of the objects I have is more complex than this example: const myStyle = { book: { templates: ...

What is the best way to use regular expressions in Javascript to validate an empty JSON response?

I'm encountering an issue where my ajax response is coming back empty with multiple lines of blank spaces. I need to figure out how to verify this in my success function. Is there a way to use regex in JavaScript to check for an empty JSON response? ...

Incorporate a div block using JavaScript

When calling the function below, I attempt to include a div block but struggle with setting the left position. The alert function displays a message of '600px', however, the block appears in a different position on my screen. function show(){ ...

Angular 2 doesn't reflect changes in component variables in the view until mouseover happens

Since updating from angular2-alpha to the latest version, I've noticed that when a boolean value changes in my *ngIf directive, it doesn't reflect in the view until certain actions are taken. Here is the specific component code: declare var CKE ...

Developing a comprehensive Java web service project with AngularJS, test-driven development/behavior-driven development, using Maven and Eclipse

Encountering some challenges while setting up a project to implement the full Java, Angular.js, TDD/BDD stack. While these challenges are not causing any major obstacles as of now, they have the potential to become one. Using Eclipse 4.6.0 Neon with WTP, ...

Fetching data based on date range from a MySQL database using AJAX in Laravel PHP - A step-by-step guide

In the process of developing a basic holiday management system, I have implemented CRUD operations successfully. However, I am facing an issue with retrieving data based on a selected date range via an ajax call. This project marks my first attempt at buil ...

An interactive data organizing tool on a website

Similar Question: Is there a Spreadsheet-like control for web applications? I am exploring different tools available, unsure of how to implement what I have in mind. Currently, my webpage uses javascript to parse user-provided information. Users copy ...

Mistakes encountered while creating a simple JavaScript slideshow featuring navigation buttons

Currently, I am attempting to create a JavaScript slideshow with both forward and back buttons. The task seems simple enough - I just need 8 images that can be navigated through by clicking the buttons. However, I am facing a frustrating issue with my code ...

How can Redux help persist input value through re-rendering?

Handling Input Value Persistence in Redux despite Re-rendering? I am currently able to store and save input values, but only the data from one step ago. For example, when I click on the second input field, it displays the value from the first input fiel ...

Utilizing an Entity's Location for triggering an Action in AFrame

Looking to create a custom component that can track the position of a sphere within an AFrame scene and trigger an event when it reaches a specific coordinate (for example, resetting to its default position as shown below): AFRAME.registerComponent("t ...

Having trouble establishing a connection with the OpenWeather API in your Javascript code

I'm trying to show the current weather conditions for the state I enter, but every time I do, it gives an error saying "wrong city name" and then shows as undefined. const button = document.querySelector('.button'); const inputValue = docume ...

`Problem with event propagation`

I am dealing with propagation issues caused by a series of click events. The container's data is loaded via ajax, hence the need for the body on-click method. Below is the code: $(function () { $("body").on("click","#top-div",function(){ ...

Exploring the relationship between AngularJS and HTTP headers

I am trying to send a custom HTTP header to the REST service with every request I make. My setup involves using Apache HTTP Web Server, and below is the code snippet I have created: app.config(['$httpProvider', function($httpProvider){ if(!$ ...

What steps can be taken to prevent the controller action if the password and confirm password do not match?

Currently utilizing .Netcore MVC for my project. I am developing a registration page where users are required to input their email, password, and confirm the password. Although I can verify if the entered password matches the confirmation password, the con ...

How can I utilize VeeValidate 3's locale message JSON files without the need for Node.js or an HTTP server?

With VeeValidate 2, the locale message files are in javascript format, making it possible to use them by including <script src='./vee-validate/dist/locale/ja.js'> without needing Node.js or an Http Server. However, with VeeValidate 3, the ...

Tips on accessing InnerText with VUEJS

I'm struggling with displaying the innerText generated by my generatePseudonym() function in a modal dialog. To better illustrate, here is a screenshot of what I mean: https://i.sstatic.net/pEl5P.png I am aiming to show the output Anastasia Shah as th ...

The styling of divIcons in React Leaflet Material UI is not applied as expected

When using divIcon in React Leaflet to render a custom Material UI marker with a background color prop, I noticed that the background style is not being applied correctly when the marker is displayed in Leaflet. Below you can find the code for the project ...

Finding the nearest value by searching through data attributes using numeric values

How can I target the first div with a data-score value just above a specified user score? The code snippet I have tried doesn't seem to be working. Any suggestions? var userscore = $("#userScore").val(); var next = $("div[data-score >=" + users ...