Put js variable inside wordpress function - javascript

I've faced with a problem. I use Mafnific popup. Below the popup I add a button to download image and different actions like social icons etc.
so, I need to find out a filesize of image uploaded to media of Wordpress. I have js variable where I have link to image.
For this in functions.php I put a function for searching id of this image by link like this:
function pippin_get_image_id($image_url) {
global $wpdb;
$attachment = $wpdb->get_col($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid='%s';", $image_url ));
return $attachment[0];
}
And now I can find out the filesize if I put a link of image to this function like this:
echo size_format(filesize( get_attached_file(pippin_get_image_id($link)) ),2);
But the main problem is: I am now inside js script and I need to pass to function a JS variable var link:
Inside a function I have a snippet:
return 'Download (<?php echo size_format(filesize( get_attached_file(pippin_get_image_id( VARIABLE LINK )) ),2); ?>)
p.s. see where VARIABLE LINK is.
How can I put js variable there ?
Thank you so much in advance!

you can just print image size in hidden field like this:
<input style="display:none" id="image_link" value="<?php echo size_format(filesize( get_attached_file(pippin_get_image_id($link)) ),2); ?>" />
and then in script fetch this value in jQuery like this:
var imageLink = jQuery('#image_link').val();
return '<a href="' + link + '" download target="_blank" class="btn btn-success" id="original">Download (<?php echo size_format(filesize( get_attached_file(pippin_get_image_id(
'+imageLink +' )) ),2); ?>)</a>

Edit - Explanation: What you want to do is not directly possible because PHP execution stops before JavaScript execution starts. PHP is a server-side script language, meaning that it runs when the user requests a page from the server. It prepares the page, stops execution and the server sends the results to the requesting user. Only then it is displayed in the users browser and JavaScript execution (which runs on the users machine by the way) starts.
You might want to take a look at wp_localize_script(). This function takes information available at PHP runtime and puts it into a JavaScript variable, which you can then use in your JavaScript scripts.
In the (likely) case that you don't know at PHP runtime which file-size you need (for example when you have a huge list of files and don't want to pre-fetch file-sizes for all of them) your go-to solution will be AJAX. This is more complicated, but once you understand how it works, you can do many exciting things with it. The process is as follows:
In your JavaScript files, you "make a call" to an URL. In this case, the URL is your WordPress site. This call is made by JavaScript, so the user will not see anything of it. You can add addition data (variables) to this call.
You tell WordPress how to handle this call. Once again, the users sees nothing of this. The output of this call, that, in normal scenarios, would be shown in the browser, will instead be passed back to the calling JavaScript file from step 1.
After your calling JavaScript file has received a response from the call, you can use the response in any way you like.
Translated to your case: JavScript script runs when popup is opened. This script calls WordPress, WordPress handles the call with your file size function and returns file-size, JavaScript script takes file-size and adds it to the link-button.
Using jQuery makes the whole process of AJAX calls much more straightforward.

Related

Using "A little vanilla framework" to build an upload feature

Looking at this document; I am trying to make a file upload using XMLHttpRequest.
Here is how I start: I take the code in the A little vanilla framework section of the document. Then I first make it work on my own site. Then to implement the upload functionality I want to modify the end of the register.php file. Indeed a file transfer to the server is already happening there. To call it an upload I only have to save the file on the server.
I do that after these lines:
echo "\n\n:: Files received ::\n\n";
print_r($_FILES);
There, I want to write the contents of $_FILES[0] on the server. For that I use this code:
$myfile = fopen("MyData.jpg", "w");
fwrite($myfile, $_FILES[0]);
// The three lines below that I have tried instead of the one above do not work either.
//fwrite($myfile, json_encode($_FILES['photos']);
//fwrite($myfile, json_encode($_FILES[photos[0]]);
//fwrite($myfile, json_encode($_FILES['photos'][0]);
fclose($myfile);
As a result, there is a file named MyData.jpg written on the server as expected, but its length is zero.
I think there is a mistake in the three lines above but, what did I do wrong?
Right method is to use
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], "MyData.jpg");
where "fileToUpload" is the field name you gave for the file button
I think you'll get data here: $_FILES['photos']['tmp_name'][0].
Try it please.
Or
You could rewrite your code like below:
foreach($_FILES['photos']['tmp_name'] as $i=>$file){
if($_FILES['photos']['error'][$i] == 0){
move_uploaded_file($file, "MyData_".$i.".jpg");
}
}

Print a javascript variable in php

I am selecting a payment method and making an AJAX call But I am not able to print the paymentOption parameter
I tried storing it in a cookie
if(paymentOption == "default_cod"){
processOrderWithCOD();
optionPayment = Cash;
}
document.cookie = "$payment_option = $this.optionPayment";
PHP:
<?php
$paymentOptionDisplay = $_COOKIE['payment_option'];
echo $paymentOptionDisplay ?>
I am just trying to print paymentOption but later on its value is changed so need to save it and print
You have to remember that if JS and PHP live in the same document, the PHP will be executed first (at the server) and the JS will be executed second (at the browser)--and the two will NEVER interact (excepting where you output JS with PHP, which is not really an interaction between the two engines).
In other words, if the two live in the same document and no extra interaction with the server is performed, JS can NOT cause any effect in PHP. Furthermore, PHP is limited in its effect on JS to the simple ability to output some JS or something in context of JS.
$paymentOptionDisplay = $_COOKIE['payment_option'];
Cookies usually will not be available until the page is reloaded / refreshed, which is why you're not getting the value that you're expecting. You'd really have to do the payment calculation in PHP and store it in a $_SESSION if you're looking for it to persist like a cookie.

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 to get url of main page with php from within a javascript include?

I have a page with a header include, and the include needs a phone number to change on it ONLY if the filename of the current page contains a certain word.
Normally, for a change that is not within an include, the below code would work.
<?php if (strpos($_SERVER['REQUEST_URI'],'example-match') !== false)
{
echo '555-555-5555';
}
else
{
echo '1-800-555-5555';
}
?>
However, since the code is in an included file on the page, rather than the original page itself, the server instead is returning the name of that included file.
Example: www.example.com/im-on-this-page.html returns the name of the include the php file is in - www.example.com/header-include.php.
Is there a way to grab the URL of the page the include is "included on", rather than the url of the include, from code that is within the include?
UPDATE:
The file is being included via Javascript, since the page is it being included on is an html file:
<script>
$('#Header').load('/includes/header.php');
</script>
As of your last comment:
Then it is not an include but a GET request to the PHP delivering a JavaScript. And then, the given URL is proper. In order to find out from where the script has been included you may either look for the referer header (which is instable) or pass the current file to the script itself:
<script> $('#Header')
.load('/includes/header.php?from=encodeUriComponent("<?php echo $_SERVER['REQUEST_URI'] ?php>")'); </script>
Within your script, instead of $_SERVER['REQUEST_URI'] then use $_GET['from']
As commentors have mentioned as well. This is incorrect. $_SERVER does not change for the duration of the script (and includes). Including a file will not alter it.
A javascript include, meaning it is actually called by the client by an ajax call, and not included on the server before the page is presented.
(you load a page, and then load another page which you "print" somewhere on the first)
a quick and dirty fix would be to write something along these lines on the first php file
<?php if (strpos($_SERVER['REQUEST_URI'],'example-match') !== false)
{
echo "<script> var phone_number = '555-555-5555';</script>";
}
else
{
echo "<script> var phone_number = '1-800-555-5555';</script>";
}
?>
which will create a variable on the client side, which you then can call from the loaded page as a javascript variable

How to pass javascript variables to php variables with yii

First: I KNOW this is a duplicate. I am creating this because none of the answers to all the other questions satisfy me. I have a very particular situation where I'm using yii and tryi I can't send it through ajax because the php and javascript are on the same page on the same page.
Basically what I'm asking is if you have a page that uses yii and chart js, and you need to render a page that requires two arguments from the clicked bar, which is represented by activeBars[0]:
<script>
canvas.onclick = function(event) {
var activeBars = getBarsAtEvent(event);
<?php $controller->functionThatRendersView($arg1 /**(activeBars[0].value*/,$arg2 /**(activeBars[0].label*/); ?>
}
I don't care if it will render automatically, that is another problem. I just need to get those arguments to the php.
Thanks.
Also, if it helps, I am passing those two values to javascript through php for loops:
labels: [<?php for ($i=1;$i<=$numberIssues;$i++) {
echo $i . ",";
}?>],
The problem with grabbing $i and putting it into the label argument is that I don't know which bar label is the clicked one, I need javascript to pass the clicked bar values back to php.
Explain to us again why you can't use ajax. You say "because the php and javascript are on the same page". That's not what ajax is - you need a different URL for the ajax request, and a separate PHP file or something to handle it.
Without ajax it's impossible for javascript to send information to PHP, because the PHP runs on the server before the javascript runs on the client. Unless of course you want to do a complete page refresh, which is slower and generally worse from the user perspective.
I found an answer to my question! I'm just doing this for anyone else who is stumbling:
To pass javasctipt variable var jsInteger = 5; to php you type (in javascript):
window.location.href = "yourPhpFile.php?phpInteger="+jsInteger;
You access the variable in php like so:
$phpInteger = $_GET['phpInteger'];
This will require a page refresh, and will redirect you to the php file.

Categories