This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 6 years ago.
I have this code:
<html>
<body>
<script>
var x;
if (confirm("Press a button!") == true) {
x = "You pressed OK!";
<?php $kk="ok"; ?>
} else {
x = "You pressed Cancel!";
<?php $kk="not ok"; ?>
}
document.getElementById("demo").innerHTML = x;
</script>
<?php
echo $kk;
?>
</body>
</html>
When I echo $kk, I obtain always not ok
But I want to print OK or NOT OK. Any helps please?
What you are asking for is absolutely impossible as is, because all PHP code is completely executed before the html is sent to the browser, where the javascript is executed in its turn, hence after.
If you need the result on the http server, you must describe a form in the html page and create a server PHP script at the URL of the form action, then the PHP can get the form elements.
If you need the result in the browser (eg. to change some elements in the page displayed), you must code in javascript.
If you want to exchange between PHP and javascript while staying in the same page, you can use Ajax, or you can use directly the javascript XMLHttpRequest object which can call a server script from the browser javascript. See some examples at w3schools.com
Related
This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 2 years ago.
i have following code:
if(isset($_POST['Button']) && (!empty($_POST['Button']))){
echo '<script language="JavaScript">alert("ALERT MESSAGE");</script>';
echo $classFunctions->Function($db, $_POST);
echo '<meta http-equiv="refresh" content="0;URL=\'refertarget\'">';
}
but the alert message does not appear before the function is executed. Any suggestions how i can handle that alert message appears before the function will be executed?
thanks and regards
This cannot be done in PHP itself. Since PHP is executed on the server, builds the page and then sends it to the client where the JavaScript is executed.
To achieve something close to what you're trying to do would require you to send another request to the PHP file when the alert is closed, which does then execute the function:
<script>
alert('ALERT');
fetch('url/to/php-file');
</script>
remember that there is also confirm instead of alert where you can select Yes or No and only proceed on Yes:
<script>
if (confirm('PLEASE CONFIRM')) {
fetch('url/to/php-file');
}
</script>
This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 6 years ago.
I have the php page with javascript code inside it.
If I have php variable retrieved by back-end server, can it be passed in javascript code?
For instance, if I want to check the flag(php variable) inside the javascript code, do I need to hardcode it inside the javascript?
Below are the "checkServiceCategory"? (Should it be Dynamic or static)
<?php
foreach ($result as $id=>$value) {
if($value[0]->isServiceCategory)
return true;
}
OR
isEmptyUploadFile(function(r)
{
var checkServiceCategory=document.getElementById('category-group').value;
if(checkServiceCategory!=85 && (fileList == null || fileList.length == 0))
{
$("#uploadImgError").html('<em><span style="color:red"> <i class="icon-cancel-1 fa"></i> Please Upload at least one image!</span></em>');
location.href = "#uploadImgError";
return false;
}
else
Yes you can use php variables inside the javascript code and php variable is dynamic as
<?php $your_variable = "some value"; ?>
<script>
var js_variable = '<?php echo $your_variable; ?>';
alert(js_variable);
</script>
You can write PHP data into JavaScript before that JavaScript is loaded. So, for example:
<script>
var count = 0;
<?php
echo 'count = 5;';
?>
console.log(count); // Will give 5
</script>
You can do this because the PHP is run on the page before it is ever sent to the client. However, once the code is sent to the client, JavaScript and PHP cannot talk to each other. What you can do at that point is make AJAX requests via JavaScript from your client back to your server, and use PHP to respond to the AJAX request.
You can pass value from php to js like this.
var js_var = '<?php echo $some_php_variable; ?>';
This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 7 years ago.
I am facing issue regarding passing javascript variables to php within same function. My code looks like this
else if(msg_type[i] == 'code' ){
var code_action = 'test';
<?php
function foobar_func(){
return "<script>document.writeln(action[i]);</script>";
}
add_shortcode( 'foobar', 'foobar_func' );
?>
}
what i am doing is passing that code_action variable of javascript and returning it to function without using ajax or jquery...is there any possible method to do so...??
any possibilities will be appreciated. Thank you
When you make a request to invoke this page, your <?PHP ?> block is executed in the server. It creates a processed output in the web page (in your code) and send it to the browser. Now the browser executes your <script> </script> blocks.
I hope you understand that passing variables from <script></script> to <?PHP ?> is impossible since the latter happened in the past.
But you can use it other way around by trying to pass variables from the PHP to JS.
When you write
<?PHP
$fromServer = "from php";
echo "<script> var fromServer = " . $fromServer . " </script>
?>
.. it passes data from your PHP to JS.
You can, however, use HTTP POST or GET method to pass data from JS to PHP to be used in the next session.
This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 7 years ago.
I have a simple checklist form with a number of input fields and counters to check them. Form consists of only few text fields and some radio buttons, whose value is set to either conforms or notConforms:
error counter ($errCounter) = counts errors like illegal input format and missing fields
non conformance counter ($notConforms) = checks if/how many input fields are set to notConforms.
I am trying to alert the user and get their confirmation if any inputs are set to notConforms.
Two problems with the outcome of my code below:
it makes two entries (duplicate) into database
after database update, it does not header the user to the indicated page (inspectionbatch.php)
What is wrong with the following?
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if($errCounter == 0){ // provided there are no errors found during form validation
// warn user if there is a non-conformance
if($notConforms !== 0){ ?>
<script>
if(confirm("A not-conforms 'N/C' result has been recorded for one or more inspection criteria. If this is accurate, click OK to continue.")) {
<?php echo updateDatabase(); header("location: inspectionbatch.php");?>
} else {
<?php echo updateDatabase(); header("location: inspectionbatch.php");?>
}
</script>
<?php } else {
updateDatabase(); header("location: inspectionbatch.php");
}
} else { // if errors are found during form validation, return how many errors were found
echo "Error count: " . $errCounter;
}
}
I also tried putting the header() function inside the updateDatabase() immediately after the syntax to update database. Database was updated fine but header() did not work...
This code doesn't work because PHP, a server-side technology, runs to completion before javascript, a client-side technology, even begins. All the PHP code will execute on your web server, and a response will be sent to the client and then all the javascript will run in the the web browser.
If you want to mix the 2, you'll have to imagine how the completely rendered dynamic result will look to a web browser.
Additionally, a call to the header() function cannot be made if any bytes have already been written to the HTTP body. From the docs:
Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP.
This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 8 years ago.
i would like to do a script something like this:
<script>
function termektorol(kod)
{
<?php $parancs="delete from mex_telefon where id='?>kod<?php'";
if(mysql_query($parancs))
{
?> alert (kod); <?php
} ?>}
</script>
If i replace the 'kod' with just an actual id it deletes the thing,but i cant get it to work with the 'kod' from the function.I think its only synthax error,but i dont know how to fix it.
A possible solution is to reload page and add this parametre to the request
window.location = ...var='+kod
and in php
<?php
$parancs="delete from mex_telefon where id='.$_REQUEST["var"].'";
?>
Other solution is to use AJAX : send request from Javascript to PHP