I have a Javascript variable which I am setting a PHP variable to.
function cancel(number) {
var message = "<?= $message[" + number + "]; ?>";
}
$message is an array. "number" is the element of the array I want to set message to. Basically, I want to set a Javascript variable to a PHP variable using a Javascript variable as the element picker. So if "number" was 2, it would select:
$message[2];
However, the above approach doesn't work, and I'm not even sure if this is possible.
It isn't. Use XHR to retrieve the value from the server.
It doesn't seem at all possible; PHP is evaluated server-side, and javascript is evaluated client-side. So PHP would see it as $message["+number+"], and try to find the value at the index of "+number+". You'd probably have to do something like an AJAX request to get the data you're looking for.
What you are doing isn't possible; since php is a server-side language, it's executed first, and the js is executed after; there isn't any way to control which is executed first. You must retrieve the variable using AJAX.
Something like this will work:
<script type="text/javascript">
var messages = <?= json_encode($message) ?>;
function cancel(number) {
var message = messages[number];
}
</script>
Of course this will output the entire array in the JavaScript source. If it is large, then you are better off using AJAX.
Tip: if you "view source" it should be painfully obvious why your method doesn't work.
You simply cannot do this using this methodology. PHP is server-side code, meaning that it runs on the server, while JavaScript is client-side code, meaning it runs on the client, or your browser.
Once the PHP runs, it generates an HTML document and sends that document in the response to the browser. Once that's complete, the only way you can get data back to the server is to send it via a form POST, send it via AJAX, or send it via script tag remoting.
Consider looking at some examples on the Internet of how to POST data back to the server via a form and via AJAX. It's clear you're struggling with some concepts regarding how to properly architect your program, and looking at some examples would be a great way for you to learn and master these techniques.
PHP Submit Form Example
PHP Tutorial
You need to use AJAX call to resolve your issue.
Related
I know PHP runs first but is there a way to get PHP to wait on an ajax request and then run its script? I have a php script here that I want to run but I NEED a variable from my JS file in order for it to run successfully. So was wondering if it's possible?
What I have is a normal request in my JS:
var myvar = data;
$.get('phpscript.php', {myvar: myvar} );
And in PHP:
$myphp = $_GET['myvar'];
But if i echo $myphp it returns "undefined", if I alert it however It displays the value; which means the php script is running before it even gets the request from ajax. Any way I could make the PHP wait?
Thanks.
Put the PHP that requires a variable in its own script and call it from the ajax call, once the ajax call gets a response update the DOM as needed.
PHP runs on server, then javascript runs on client to make the ajax call, then PHP runs on server returning data, then the javascript gets the data and does something with it.
$.get('phpscript.php', {myvar: myvar}, function(data) {
$('.result').html(data);
});
Inside the php file have something like:
$myphp = $_GET['myvar'];
echo $myphp;
The short answer is, no, you can't make PHP wait. PHP only runs on the server-side, by the time the AJAX request is sent, by definition, the page is already been sent to the client.
You'll probably have to do some refactoring. If the variable absolutely needs to be used for a PHP function, then you may need to move that logic into 'phpscript.php' or (less optimally) you may need to issue another AJAX request when you get the response from the first.
But my guess is that more commonly, you'll probably just have to figure out how to do what you want with javascript. If all you want is something equivalent to a PHP echo, you'll want to use Javascript (or JQuery) DOM manipulation for that.
EDIT: I forgot to mention, the other option is simply to do all the PHP stuff on the server-side before you send the page at all, instead of AJAX you'd want to do something in PHP like including your other php script and calling methods from it. But, everything you do on the server-side, the user is sitting there looking at a blank screen waiting for the page to load. So this isn't an option for anything that's not very quick.
The code looks like this:
PHP file
<?php
...
$arrayName = ['ArrayValue_0', ..., 'ArrayValue_n'];
...
php?>
JavaScript
$('.elementClass').each(function(index, id) {
$(id).html('<?php echo $arrayName[index - 1]?>');
});
But you can't just insert a JavaScript variable like that into php tags so index is never received.
I know this can be done via AJAX but is there any other way? Thanks in advance.
Additional info:
I've been told to do this in PHP so there's no posibility of switching the array to a JS file.
You can define arrayName variable in JS and initialize it with the value from the server:
var arrayName = <?php echo json_encode($arrayName); ?>;
$(".elementClass").each(function(index, id) {
$(id).html(arrayName[index-1]);
});
What you're trying to do will not work. For example this:
$(id).html('<?php echo $arrayName[index - 1]?>');
The above will never, ever work, because PHP is run on a server, not on your user's browser.
What you need to do is send the variable somehow to the server. You have a plethora of options:
Use a form and read a $_POST variable
Append it to a URL and read a $_GET variable
Use AJAX and asynchronously send that variable to the server
Return the whole array from PHP to your Javascript code
etc. etc.
Remember, PHP runs on the server, which renders the page, which then in turn is read by your browser where you run Javascript. You can't paste PHP code into the page and expect it to be parsed by PHP!
You need to get back to the server if you wish to get info from it (PhP runs on the server), so either you create a javascript variable on-the-fly when loading the page with the complete content of your PhP array , either you use ajax to get back to the server without refreshing the whole page.
I am working on a project where I used ajax for asynchronous DB access.
I store the value in JavaScript variable as follows..
var content=xmlhttp.responseText;
now what I wanted is to pass this value to the php module on same page..
Please suggest me..its urgent
You'll have to make a separate AJAX request to another script to achieve this. PHP is server-sided and therefore cannot directly interact with the client.
You should handle the data (which you are assigning to content) in PHP because, as the other answers here tell you, PHP is server-side and JavaScript is on the client. If you are getting this data from a page you control, instead of var content = xhr.responseText; just modify the data BEFORE you send it. For example, if you are making an AJAX call to a process.php file on your server to get the data you are otherwise assigning to content in JavaScript, be sure to handle the data in process.php PRIOR to echo()'ing the data (which you are then storing inside content on the client):
In process.php:
// below is the normal server script which you are storing in content on the client
// echo $result;
// instead, we are going to operate on the data first:
return doSomething($result);
Then on the client:
var newContent = xhr.responseText;
And the newContent variable will contain the data you previously wished to modify with PHP. If you DO NOT have control of the server script which you are calling with AJAX, then as mentioned here already, you will need to send a SECOND AJAX call to the server with your PHP, and use $_GET or $_POST to retrieve that content data and then play with it there.
Am unclear about your need to pass value from javascript to php.
But I can give you,
A non-recommended but working approach towards your problem:
You said, you are making an Ajax call at first. While processing the corresponding server side php function, Store the response value (value of xmlhttp.responseText) into a $_SESSION variable. Finally Reload the page (using location.reload()) inside the ajax response handler function.
And a recommended approach towards your problem:
You might have added some if-else control-flow structures in the php code and expecting to execute them after getting the ajax response value (sadly you cannot do that). So if you do have some logic like that, then convert those if-else conditions to corresponding Javascript code. May be a javascript function and call that function by passing the ajax response value to it. This new function will use your ajax response value and make changes in some parts of your webpage by applying necessary logic.
I want the value of JavaScript variable which i could access using PHP.
I am using the code below but it doesn't return value of that variable in PHP.
// set global variable in javascript
profile_viewer_uid = 1;
// php code
$profile_viewer_uid=$_POST['profile_viewer_uid'];
this gives me the following error :-
A PHP Error was encountered
Severity: Notice
Message: Undefined index: profile_viewer_uid
Another php code i used which give empty value
$profile_viewer_uid = "<script language=javascript>document.write(profile_viewer_uid);</script>
When I echo it shows nothing.
Add a cookie with the javascript variable you want to access.
document.cookie="profile_viewer_uid=1";
Then acces it in php via
$profile_viewer_uid = $_COOKIE['profile_viewer_uid'];
You will need to use JS to send the URL back with a variable in it such as:
http://www.site.com/index.php?uid=1
by using something like this in JS:
window.location.href=ā€¯index.php?uid=1";
Then in the PHP code use $_GET:
$somevar = $_GET["uid"]; //puts the uid varialbe into $somevar
Here is the Working example: Get javascript variable value on the same page.
<script>
var p1 = "success";
</script>
<?php
echo "<script>document.writeln(p1);</script>";
?>
You might want to start by learning what Javascript and php are. Javascript is a client side script language running in the browser of the machine of the client connected to the webserver on which php runs. These languages can not communicate directly.
Depending on your goal you'll need to issue an AJAX get or post request to the server and return a json/xml/html/whatever response you need and inject the result back in the DOM structure of the site. I suggest Jquery, BackboneJS or any other JS framework for this. See the Jquery documentation for examples.
If you have to pass php data to JS on the same site you can echo the data as JS and turn your php data using json_encode() into JS.
<script type="text/javascript>
var foo = <?php echo json_encode($somePhpVar); ?>
</script>
If you want to use a js variable in a php script you MUST pass it within a HTTP request.
There are basically two ways:
Submitting or reloading the page (as per Chris answer).
Using AJAX, which is made exactly for communicating between a web page (js) and the server(php) without reloading/changing the page.
A basic example can be:
var profile_viewer_uid = 1;
$.ajax({
url: "serverScript.php",
method: "POST",
data: { "profile_viewer_uid": profile_viewer_uid }
})
And in the serverScript.php file, you can do:
$profile_viewer_uid = $_POST['profile_viewer_uid'];
echo($profile_viewer_uid);
// prints 1
Note: in this example I used jQuery AJAX, which is quicker to implement. You can do it in pure js as well.
PHP runs on the server. It outputs some text. Then it stops running.
The text is sent to the client (a browser). The browser then interprets the text as HTML and JavaScript.
If you want to get data from JavaScript to PHP then you need to make a new HTTP request and run a new (or the same) PHP script.
You can make an HTTP request from JavaScript by using a form or Ajax.
These are two different languages, that run at different time - you cannot interact with them like that.
PHP is executed on the server while the page loads. Once loaded, the JavaScript will execute on the clients machine in the browser.
In your html form make a hidden field
<input type="hidden" id="scanCode" name="SCANCODE"></input>
Then in your javascript update the field value by adding;
document.getElementById("scanCode").setAttribute('value', scanCode);
This could be a little tricky thing but the secure way is to set a javascript cookie, then picking it up by php cookie variable.Then Assign this php variable to an php session that will hold the data more securely than cookie.Then delete the cookie using javascript and redirect the page to itself.
Given that you have added an php command to catch the variable, you will get it.
You need to add this value to the form data that is submitted to the server. You can use
<input type="hidden" value="1" name="profile_viewer_uid" id="profile_viewer_uid">
inside your form tag.
I want to call a PHP function when pressing on a button, sort of like:
<?php
function output(){
// do something
}
?>
<input type="button" value="Enter" onclick="output()"/>
I tried to make something like:
<input type="button" value="Enter" onclick="test.php?execute=1"/>
where test.php is current page and then by php
<? if(isset(&execute)){ echo "Hello"; } ?>
but it doesn't work.
Since PHP runs on the webserver, and buttons (and JavaScript in this case) appear on the client, you have to make an HTTP request to the server.
The easiest way to do this is to use a form. No JavaScript is required. You can add JavaScript (although it should be layered on top of a working non-JS version). Using JavaScript to make an HTTP request without leaving the page is known as Ajax, and generally achieved with the XMLHttpRequest object. There are various libraries such as YUI and jQuery that can do some of the heavy lifting for you.
I think using an AJAX call would do sort of what you are asking. I don't know PHP very well but you can use the following example, and add another variable with the data you are passing in to the server to indicate which function you want to call on the server. On the server you can add some "IF" statements that will call a certain function based on the name passed in and return the result.
Here is what you could use on in your javascript client using the jQuery library as a helper to do the AJAX call:
<input type="button" value="Enter" onclick="output()"/>
<script type="text/javascript">
function output(){
$.ajax({
type: "POST",
url: "submit_data.php",
data: "username=" + "SomeUser"
+ "&email=" + "someEmail#google.com"
+ "&functionName=" + "theFunction1",
success: function(html){
alert('sucess! Result is:' + html);
}
});
}
</script>
and you can use code such as this to catch the data your javascript is passing in. In this example you would want to call this file name as "submit_data.php" to match the javascript above:
<?php
// Variables
$Username = $_POST['username'];
$Email = $_POST['email'];
$FunctionName = $_POST['functionName'];
//Add code here to choose what function to call and echo the result
// If $FunctionName equals 'theFunction1' then execute theFunction1
// If $FunctionName equals 'theFunction2' then execute theFunction2
echo "You called A Page!";
?>
Here I am doing nothing with the "username" and "email" simply grabbing it and storing them into holding variables. But you can easily add extra functionality here, such as checking for a name of a function that you want to run.
PHP is server side and javascript is client side. So I'm not sure if that is really what you want to be doing??
Perhaps you could explain why you want to specifically call a php function?
I googled PHP function from button and found this question on webdeveloper.com
It doesn't use Javascript.
This is PHP you're talking about, not ASP.NET. In PHP, there is no such thing as a button click event. PHP runs entirely on the server and has absolutely no knowledge of client-side events.
Your first try won't work because the PHP code only runs when the page first loads. It does not run when you call a JavaScript function. Your second example won't work because JavaScript and PHP can't talk directly to eachother like that. Trying to directly call a PHP function from JavaScript just doens't make sense. Remember, PHP only runs on the server. By the time you get to the point where JavaScript can run, the PHP code has long since completed its work.
If you want to do something when a button is clicked, you have to explicitly make a request back to the server. You can do this by just POSTing the form as CTphpnwb suggested. Just be aware that this will reload the page and you will have to manually save and restore the page state, e.g. repopulate input boxes. There is no built-in magic that will do this for you.
Alternatively, you can get all AJAXy and do the POST in JavaScript. However, you will have to write the JavaScript to send the request and process the response, and write the server-side PHP code to handle the request. This gets a little awkward to do in a single page.
From : http://www.dreamincode.net/forums/showtopic72353.htm
You cannot directly invoke a PHP function from Javascript this way :
PHP code is executed on the server
HTML / Javascript are interpreted on the client-side.
One the HTML page has been generated and sent to the client (the browser), there is nothing more PHP can do.
One solution would be to use an Ajax request :
Your onclick event would call a Javascript function
This Javascript function would launch an Ajax request : a request sent to the server
The server would then execute some PHP code
And, then, return the result of that execution to the client
And you'd be able to get that result in your Javascript code, and act depending on what was returned by the server.
There are plenty of solutions to do an Ajax request :
You can re-invent the wheel ; not that complex, I should say -- but see the next point
If already using a Javascript framework, like jQuery, Prototype, ... Those provide classes/methods/functions to do Ajax requests
Googling a bit will get you lots of tutorials/examples, about that ;-)