PHP method calls from Javascript not showing up in Wordpress source - javascript

I am running a Wordpress website, and trying to call PHP methods from my Javascript code.
When a button is tapped, the saverFoo() Javascript method is called, and attempts to call the PHP method save_image_data().
function saverFoo() {
var dataURL = canvas.toDataURL();
<?php echo save_image_data(dataURL); ?>;
}
function loaderFoo() {
var loadedImage = <?php echo loadimagedata(); ?>;
console.log(loadedImage);
}
The PHP method's implementation is in the function.php file, and is simply attempting to save some image data (dataURL) in the user's meta
function save_image_data($imageData) {
global $current_user;
update_user_meta( $current_user->ID, 'user_design', $_POST['$imageData']);
}
function loadimagedata() {
global $current_user;
$old_notes = get_user_meta($current_user->ID, 'user_design', true);
return $old_notes;
}
Inspecting my web-page in Chrome, shows me an empty space where loaderFoo () (javascript) is supposed to be calling loadimagedata() (php) , and loadedImage is an undefined variable, when I try to log it, such as:
function loaderFoo() {
var loadedImage = ;
console.log(loadedImage);
}
Not sure what fundamental mistake I'm making here.

Always remember that PHP runs on the server side, and javascript on the client side. So we have an order here, the server receives the request PHP processes what it should process and render the page, only here Javascript will be executed.
In this example, when the 'saverFoo()' function is executed, this function <? Php echo save_image_data (dataURL); ?>; has already been written on the page. PHP will not be able to get the information contained in the dataURL variable, not on this way. To do this, we must make a request to the server with this desired information, but with an "image" is not trivial to do this, as there is a limit on the size of the post when using a normal String field.
function saverFoo () {
    var dataURL = canvas.toDataURL ();
    <? php echo save_image_data (dataURL); ?>;
}

PHP doesn't work that way. It is a pre-processor. It is all run and done server side and the resulting text/html/binary data/whatever is sent out to the client. In the case of a content type of text/html the browser will load it, parse it, render it, and run whatever javascript is called.
How you can mix PHP and JavaScript in-line like that would be to use PHP to fill in variables. For example
alert("<?php print($_SERVER['SCRIPT_FILENAME']); ?>");
would work because the client would see
alert("/path/to/foo.php");
and render that for the user.
To really interact with PHP using JavaScript, you'll want to look into using a http based REST type service and perhaps one of the various popular tool sets like Angular, Vue, etc.

Related

How do I get data from Javascript function and save it to a user's custom meta field in php?

I'm working with a service that automatically registers my user's devices with Onesignal.
I call the function on login by calling gonative_onesignal_info(); inside script tags (full function will be below). That registers devices perfectly fine with Onesignal.
Now, according to the service's documentation, I can POST it to my server via AJAX, which is what I'm struggling with. From the documentation for the service, if you call gonative_onesignal_info() like this:
function gonative_onesignal_info(info) {
console.log(info);
}
... info will look like this:
{
oneSignalUserId: 'xxxxxxx',
oneSignalPushToken: 'xxxxxx',
oneSignalSubscribed: true,
}
And here's my full function:
function onesignal_mobile_registration( $user_login, $user ) {
// Get 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 );
So, how can I extract the oneSignalPushToken from that Javascript option, and store it in $oneSignalPushToken to be saved to my user? I think I need to use AJAX to pull it out, right? How would I do that?
You can't assign a php variable from javascript because php run in server but javascript run in browser. You must get $oneSignalPushToken value from a php source OR call a ajax from browser when send js data to php variable:
Script place:
<script>
var data = gonative_onesignal_info(info);
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', 'test.php?oneSignalPushToken=' + data.oneSignalPushToken, true);
xmlhttp.send();
</script>
test.php
function onesignal_mobile_registration( $user_login, $user ) {
// Get 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 );
It is important to understand what your code does:
The PHP part will render an HTML page
The JavaScript part will execute in the browser once the page is fully rendered and served
That means you won't be able to retrieve a JavaScript variable in the PHP thread that generates the page, for two main reasons:
JavaScript and PHP execution contexts are not shared at all
JavaScript will execute once the PHP thread has ended
What you have to do is expose an endpoint on your PHP server, let's say POST on a /token URL. You will call this endpoint from your JavaScript with some code like fetch('/token', { method: 'POST', body: info });, then retrieve the token from the $_POST global variable, and then execute your update_user_meta( $user_id, 'oneSignalPushToken', $oneSignalPushToken); line

fingerprintjs2 to php variable

I like to get fingerprint as php variable, I get the follow but do not want to work.
<p>fingerprint2: <strong id="fp2"></strong></p>
<script src="/fingerprintjs2/fingerprint2.js"></script>
<script>
var fp2 = new Fingerprint2();
fp2.get(function(result) {
console.log(result);
$("#fp2").text(result);
});
</script>
$myphpvar = "<script>document.write(fp2.get());</script>";
echo $myphpvar;
That's really not how PHP works at all. PHP cannot process client side JavaScript. If you want access to client side information in PHP then you should probably put it in a form and post it to another page in PHP. There are many good tutorials on PHP forms, such as this one.
The Javascript is run after the PHP has completed. Client side VS server side code. I have solved this in the past by running the PHP within a PHP file that renders an image. This method is often referred to pixel tracking.
Here are the basics, you need to pass your variables in Javascript to a PHP file that renders an image:
document.write("<img src=fingerprint.php?x="+x+"&y="+y+" width=1 height=1>");
In the above case it passed Javascript variables x and y to the PHP image.
Then the fingerprint.php script looks like:
<?php
header("Content-type: image/png");
session_start();
$x = $_REQUEST['x'];
$y = $_REQUEST['y'];
$_SESSION['x'] = $x;
$_SESSION['y'] = $y
// SHOW THE IMAGE
$im = imagecreatefrompng("fingerprint.png");
imagepng($im);
imagedestroy($im);
?>
The png image can be anything you want as it will just be a 1 x 1 image on your final screen. You now have the Javascript variables in your PHP. As the code starts a session you could write the variables to a session and collect them later in another script, or write them to a database and recover later. Try with my simple example to ensure you have it working then expand from there.
There are lots of ways you can send data from JavaScript back serverside
set a cookie and read it in the next request
request further content by injecting a script / IMG / iframe tag (but not using document.write) adding the fingerprint in the query of the url
make an AJAX request
add a hidden input to a form on the page - requires the user to navigate out of the page using the form

How i can get a variable from javascript to PHP or HTML

if i make a variable in javascript with this script
var kakakSisa = 10;
and i wanna call it in PHP for example
<?php echo <script type="text/javascript">kakakSisa;</script> ?>
and that doesn't work!! how i can make it work?
You can't use javascript variable in php code. Php code run's on the serverside and javascript code runs in the client side (If you are not using Node.js). You can't ask the browser to run php code.
Your variable loc will have a value only when the code reaches the browser.
If you want to get some value from server and combine it with javascript variables then do the following.
Use an ajax request and send the desired values to server. The server will return with a response. Use that response text and store it in your action variable.
Use AJAX to communicate client and server side.
$.get('/path/to/file', kakakSisa: 10, function(data, textStatus, xhr) {
/*optional stuff to do after success */
});
Get variable in php using $_GET['kakakSisa'];

Calling PHP script with Cordova

I'm working on an app that's supposed to contain the same information as an already existing website.
What I wanted to do was create a Cordova app that calls an external PHP script which in turn gets information from the database that the website is using.
Right now I'm working on calling the PHP script but it just doesn't seem to work.
Here is the script I'm trying to call:
<?php
$a = 1;
$b = json_encode($a);
return $b;
?>
Ofcourse this is just to test the connection. The URL for this file is http://localhost:8888/get_posts.php
Here is the code for the app:
$('#page1').bind('pageshow', function () {
$.get('localhost:8888/get_posts.php', function (data) {
$(this).find('.homeText').html(data);
});
});
This fetches the file whenever the page is shown (handy) and then puts the new data into the page. The problem is that the page remains empty at all times, when it should be showing a "1". Can anyone see where it goes wrong?
Error message: XMLHttpRequest cannot load localhost:8888/get_posts.php. Cross origin requests are only supported for HTTP.
UPDATE: The error message dissapeared when adding http:// to the url, but the problem persists.
I've changed the code to:
$('#page1').bind('pageshow', function () {
$.get('localhost:8888/get_posts.php', function (data) {
alert(data);
});
});
and it shows me an empty alert box.
Solution: Had to use echo instead of return for the script to show me a result.
http:// was also required so the script is allowed to communicate.
You have to 'echo' your response not returning it like so
<?php
$a = 1;
$b = json_encode($a);
echo $b;
?>

I can't get a value from a PHP array...?

I'm writing a script to retrieve the scores from an osu! beatmap. The script uses the osu! API, which can be found here. I've obtained a valid API key, and got the info from the website. My project can be found here: failosu!.
This script is called by AJAX, and the variable s is passed via POST.
My problem is with the returned array.
In the following snippet (not really, it's pretty much my entire script), I make a request for the beatmap information first. In doing this, I am passing a variable, s (beatmap set ID), to the server, and trying to get the variable b (beatmap ID).
However, whenever I call $d1['beatmap_id'], it doesn't return anything to the main page. Instead, my AJAX script runs the error function rather than the success function. Does anyone know what my problem is?
if($_POST['id']) {
$s = $_POST['id'];
$k = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$u0 = "https://osu.ppy.sh/api/get_beatmaps?k=".$k."&s=".$s;
$d0 = json_decode(file_get_contents($u0));
$d1 = get_object_vars($d0[0]);
$b = $d1["beatmap_id"];
// THE CODE STOPS WORKING HERE FOR SOME REASON ????
$u = "https://osu.ppy.sh/api/get_scores?k=".$k."&b=".$b."&m=0";
echo $u;
$d = json_decode(file_get_contents($u));
for($i=0;$i<count($d);$i++) {
echo "<li>".$i." ".$d[$i]['username']."</li>";
}
}
Does anyone know what's wrong? Do you need me to tell you more information about my code?

Categories