Send a php variable to a different js page - javascript

I am facing a little js/php issue. I have 2 different files (a .php one and a .js one containing some scripts the .php page will execute). I would like to send a php variable to the .js page. I looked over the internet but did not find anything that could help me...
Thanks for your help !

One solution is to define a JS variable in the HTML (produced by your PHP script):
<script type="text/javascript">
var SOME_VAR = <?= json_encode($myvariable) ?>;
</script>
I'm using json_encode(), since it will add quotes around strings, and write arrays etc so that it's valid JavaScript.
After that, link the external JS file, in which you can use SOME_VAR with the value that came from PHP.

You can't send php variable directly to js file. For this purpose you have to write php value in a hidden or text field then get that value in js.

You can try to embed the php variable in an hidden input field and try to access that input field in javascript.
<input type = "hidden" id = "phpvar" value <?php echo $hiddenVar; ?> />
in javascript
var hiddenPhpVar = document.getElementById('phpvar').value;

Related

using ajax to pass string from php to javascript

So I have a piece of javascript code in an html document that responds to a button click. I want a new url to open, and if I specify the link in javascript as I've done below, everything works fine.
<input type="submit" id="submitbtn" value="Purchase Module"/>
<script type="text/javascript">
document.getElementById("submitbtn").addEventListener("click",handle_click);
function handle_click() {
var link;
link="http://www.google.com";
window.location.href=link;
}
</script>
Problem is I want to hide the real link on the server side as it includes a username:password. The php script below calls a function (not shown) that generates the link (a string). This also works fine.
<?php
$link=get_page_link();
?>
I want to pass the link string to the javascript and have tried various iterations of
link=<?php echo $link ;?> to no avail. As I understand it you can't pass strings this way and you need to use ajax. That's where I'm stuck. Seems like I need a $_POST on the php side and a $_GET on the java side, but not sure on the specifics. Any help would be appreciated. Thanks.

Pass Javascript variable to another page via PHP Post

I am having two php pages:
page 1:
<form class="form-horizontal" role="form" method="post" action="Page2.php">
<button id="place-order" class="btn btn-lg btn-success">Place Order</button>
<div id="ajax-loader" style="display:none;"><img src="images/ajax-loader.gif" /></div>
</form>
<script>
var id = Math.random();
$(document).ready(function() {
$('#place-order').on('click', function() {
$(this).hide();
$('#ajax-loader').show();
});
});
</script>
As on form, it redirects to Page2.php, I want to pass the Javascript variable "id" from Page1 to receive it in Page2.
I have tried using cookies, but need an alternative approach.
I am not understanding the transistion from PHP to JS and vice-versa. Help is appreciated.
Thanks in advance
Dear you can do it very easily with ajax. Ajax has data attribute which helps you pass your data from javascript to another page.
This link will help you a lot
https://api.jquery.com/jquery.ajax/
You can use session storage or cookies.
Example for session storage:
// First web page:
sessionStorage.setItem("myVariable", "myValue");
// Second web page:
var favoriteMovie = sessionStorage.getItem('myVariable');
You could use a query string to pass the value to the next page.
Add an ID to the form
<form class="form-horizontal" role="form" method="post" action="Page2.php" id="order-form">
Update the action of the form to add this query string from our JS variable
var id = Math.random();
$('#order-form').attr('action', 'Page2.php?id=' + id);
Get this variable in PHP (obviously you might wanna do more checks on it)
<? $id = $_GET['id'] ?>
We can now use $id anywhere in our PHP and we'll be using the ID generated from JS. Neat, right? What if we want it in JS again though? Simply add another script tag and echo it there!
<script type="text/javascript">
var id = <? echo $id ?>;
</script>
EDIT: Updated to add a little about how it works as you said you're not too sure about the transition between PHP and JS.
PHP runs on the server. It doesn't know much about the browser, and certainly doesn't know about JS. It runs everything and finishes executing before the web page is displayed. We can pass PHP variables to JS by creating script tags and creating a new javascript variable, echoing the PHP value.
JS (JavaScript) runs in the browser. It doesn't know about anything that happens on the server; all it knows about is the HTML file it is running in (hit CTRL+U to see raw HTML). As JS runs at a completely separate time to PHP there is no easy way to transfer variables (e.g. $phpVar = myJSVar). So, we have to use server methods like POST or GET.
We can create a GET or POST request in 2 main ways:
Using a form
Using an AJAX request
Forms work in the way I've outlined, or you can create a hidden field, set the value you want and then check for that. This involves redirecting to another page.
AJAX (Asynchronous Javascript And Xml) works slightly differently in that the user doesn't have to leave the page for the request to take place. I'll leave it to you to research how to actually program it (jQuery has a nice easy API for it!), but it basically works as a background request - an example would be displaying a loading spinner whilst loading order details from another page.
Hope this helps, let me know if something's not clear!

Retrieve variable name from an HTML site

I am trying to retrieve simple javascript variable (which is written to a File Systems Object) from a website which is served by an apache host on my ubuntu laptop.
So I have the function that writes the variable set up as follows:
<script type ="text/javascript">
function WriteToFile(passForm) {
set fso = CreateObject("Scripting.FileSystemObject");
set s = fso.CreateTextFile("/home/lex/Downloads/goal.txt", true);
s.writeline(document.passForm);
s.Close();
}
</script>
and the section that takes the user input from the html website is
<div id="bot-right">
<form onsubmit="WriteToFile(this['goal'].value)">
<a align = "left"> <b><Strong>Enter a Goal name</Strong></b></a><br>
<input type="text" name="goal"> <br>
<input type="submit" value="Send Zeus">
<br>
</form>
</div>
For some reason, when I type in variable names to the form on the website, the file goal.txt gets created in the directory, /home/lex/Downloads/, but nothing gets written to it.
I also noticed that when I delete the goal.txt file and rewrite the variable from the html website, the file doesn't always get created.
I am not a JavaScript person and I am at a loss as to what I may need to fix this.
My intention is to get the variable written to the text file and have a processing c++ file process the variable.
Would someone be kind enough to lend an insight?
Thanks!
one way to do it is just calling the function without parameters and just getting the input value like this:
adding and id or a class to your input to get that specific value:
document.getElementById('goal').value
document.getElementByClass('goal').value
Or getting the value by name:
document.querySelector('[name="goal"]').value;
EDIT1
You could add a console.log to check if the value is beign passed correctly like this:
var inputValue = document.querySelector('[name="goal"]').value;
console.log(inputValue);
And if the value is being passed then the problem is your writeline or in the creation of the document
EDIT2
I just tested it and retrieving the value works just fine, so the problem must be in your document writing method, please check this documentation it can help you and i think is a better solution:
http://www.html5rocks.com/en/tutorials/file/filesystem/

PHP: Reading DOM info of own HTML page

So, let's say I have only one file on my server called index.php :
<!DOCTYPE html>
<html>
<body style="background-color: orange;">
<!-- On/Off button's picture -->
<?php
echo ("<img id='button' src='data/button.jpg' alt='off'/>");
?>
</body>
</html>
Now, let's say I attach a JavaScript that changes the buttons ALT to ON when I click the button at some point.
How can I read the DOM elements on this page using PHP?
So far, I've found this code:
$dom = new DOMDocument;
$dom->loadHTML($html);
$main = $dom->getElementById('alt');
but I can't figure out how I would fit that in my code above, what page should I call loadHTML() for?
How do I make PHP read DOM elements it generated using echo?
First of all, your button has id button, so searching for the id alt would return no results.
Second: The piece of php you found reads a page $html (probably file_get_contents('some_url'), puts it in the variable dom and parses it, searching for the id alt. In your case it would read your own page, breaking it down in pieces looking for that button.
Thats of no use if you can read the status with javascript on your own page. You can then pass it to php trough an ajax-call or by adding it to the url like mypage.php?button=off
$main = $dom->getElementById('button');

Html POST and return the same form with the values

I'm learning web development, and I don't know how do this simple thing.
I've a html form with "text", "radio" and "checkbox" controls, that POST the values to the server and it saves them, for example in a file. I save the POST in raw format:
key=value&key=value&key=value&key=value
and I'd like that when the user open the form back, return the form with the saved values already in the controls.
Is there any neat way to do this? Or should I parse the POST string and set the values one by one in the controls at the server level?
I think, I could return the saved data in a hidden input control, and after with a javascript I could do a getElementById(key) and set the value to each input control... but do I need to put the post string in a special format?
How would you do it?
Thank you in advance.
You should store the POST fields (preferably not in querystring style, your programming language probably has some serialization functions which are better for that) and then fill the form fields by setting value="..." attributes (or tag content e.g. for textareas).
What server side language are you using ?
If php :
< ?php
$myvar = $_POST['myvar']
?>
<input type="text" value="<?php echo $myvar; ?>" />

Categories