Using PHP in javascript's IF Statement [duplicate] - javascript

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 trying to make a confirm box which will desire which php code will be executed.
Heres my code:
<script type="text/javascript">
var answer = confirm('Are you sure?');
if(answer==true)
{
<?php $confirmation = 1; ?>
}
else
{
<?php define("CONFIRMATION", 1, true); ?>
}
alert('<?php echo $confirmation; ?>')
alert('<?php echo defined("CONFIRMATION"); ?>')
</script>
The problem is , even if i click YES, $confirmation and boolean from defined() function returns 1.
Whatever I click, (cancel or ok) one of them should be 0 (I've already declared $confirmation before)
But both of codes at if and else blocks are used!
Normally it works like this

You fundamentally misunderstand what PHP is doing.
PHP is evaluated on the server before the page is sent to your browser. By the time the browser sees it and executes the javascript, all the PHP is gone.
Use your browser's "view source" on the browser window with this code in it. You'll see it looks like this:
<script type="text/javascript">
var answer = confirm('Are you sure?');
if(answer==true)
{
}
else
{
}
alert('1')
alert('1')
</script>
You either need to implement what you want to do in javascript to run on the browser, or you need to send a new request to the server and get a new page back (either directly or indirectly) with your response.

That will never work because PHP is processed before the output is sent to the browser. If you really need to modify something in PHP then try using an AJAX call.
http://ajaxpatterns.org/XMLHttpRequest_Call
Or try using jQuery's $.ajax(); function. Start by looking here.
Here is a quick example:
<script type="text/javascript">
var answer = confirm('Are you sure?');
$.ajax({
type: 'GET',
url: '/path/to/script.php',
data: 'answer=' + answer,
success: function(response) {
alert(response);
}
});
</script>
Contents of script.php:
<?php
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH'])
&& strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'
) {
// AJAX request
$answer = $_GET['answer'];
// ...
}

You can't trigger a PHP code exection without a post/get request.
For your needs, you should choose between a form submisssion or load a page-link with parameters stuffed in the query string on confirmation.
P.S.
the query string parameters are the ones following the "?" in the format variable=value
for example:
index.php?answered=1
you will be then able to retrieve these vatiable/values using PHP $_POST, $_GET or $_REQUEST variables in a way like this:
if ($_REQUEST['answered'] == 1) { //confirmed
...
}

You are misunderstanding the order of what will happen here.
Firstly, PHP will output the javascript layer. Your if block will then look like this:
if (answer == true)
{
}
else
{
}
The javascript engine should then optimise that out and totally ignore it. Consider using AJAX if you need to get PHP to process something with an input from the javascript layer.

Normally it works like this
No, it never works like this. PHP is executed before the javascript so it will never work like this.
I think from what I see you would want something like
Your link
This will go to the current page with $_GET['confirmation'] set to "1".

php executed before javascript so you can't do this because
when you check it via javascript if else statement php is already executed so you can't do it
but however you can use ajax for it

Related

Load php file within javascript (AJAX or others)

I am trying to finish one page of my website the last couple of hours while achieving the following.
While clicking on a button, the following should happen
Download link appears (done - works)
The mySQL table should be opened and a counter should be incremented
As far as I got the points. Javascript cannot handle that and thus we can use AJAX or jQuery. I was already checking out different posts and websites such as:
how to execute php code within javascript
https://www.w3schools.com/js/js_ajax_database.asp
and much more. However, I guess I do have problems with the AJAX syntax and I actually don't know if the requested php files is loaded/opened or not. Especially the second link given above is almost similar to what I am searching for. However, it does not work. To check if the php file is called, I set an alert which works if I do call the file explicitly in the browser. Maybe this does not work with AJAX as I expect it. Here the code to get more familiar with the inconstency I am doing.
The page code:
<?php
echo '<div><button onclick="incrementAndDownload('testPath', 'fileName'); ">Click me</button></div>';
?>
<script>
function incrementAndDownload (link, fileName)
{
$.ajax({
url: 'openfoam/increment.php',
success: function(data) {
// Print something if necessary
}
});
//- Open the link
// window.open(arguments[0], "_blank");
//- Increment download inside mysql
//var xhttp;
//xhttp = new XMLHttpRequest();
//xhttp.open("GET", "openfoam/increment.php?foo=nana", true);
//xhttp.send();
}
</script>
The increment.php looks as follows:
<?php
echo '<script type="text/javascript" language="Javascript">
alert("Test message if the script is called...");
</script>';
// Code for accessing the mysql database and manipulate the data
//$page_id = mysql_real_escape_string(html_entities($_POST['file']));
?>
Now when I click the button, the javascript is executed (e.g., if I uncomment the window.open) this works as expected. However, as already said, the second part is to open the database via php and increment a number (counter). For any reason, I am not able to figure out where the problem is located. I am even not sure if AJAX opens the increment.php file (the alert messages never appears so I guess it is never called). Any suggestion is appreciated and I hope that this question does not just contain a fundamental small error. Thank in advance, Tobi
It's not the way the AJAX works. If you call alert() on a destination page it won't show in your browser. Your case is very basic so I will keep my solution on a basic level.
In increment.php just echo something, it can be just OK string. So when you go to increment.php page you will see only OK, nothing more, nothing less.
Then go back to your javascript and check what is your response.
$.ajax({
url: 'openfoam/increment.php',
success: function(data) {
if (data == 'OK') {
console.log('It works, sir!');
}
}
});
If you don't see a message in a console after these modifications something doesn't work. However, I think your page is executed properly, but you just don't get feedback, because you don't handle the response (data param in your case).
Check it out and don't forget to give me a feedback!🤓

Call a javascript function from php [duplicate]

How to call a JavaScript function from PHP?
<?php
jsfunction();
// or
echo(jsfunction());
// or
// Anything else?
The following code is from xyz.html (on a button click) it calls a wait() in an external xyz.js. This wait() calls wait.php.
function wait()
{
xmlhttp=GetXmlHttpObject();
var url="wait.php"; \
xmlhttp.onreadystatechange=statechanged;
xmlhttp.open("GET", url, true);
xmlhttp.send(null);
}
function statechanged()
{
if(xmlhttp.readyState==4) {
document.getElementById("txt").innerHTML=xmlhttp.responseText;
}
}
and wait.php
<?php echo "<script> loadxml(); </script>";
where loadxml() calls code from another PHP file the same way.
The loadxml() is working fine otherwise, but it is not being called the way I want it.
As far as PHP is concerned (or really, a web server in general), an HTML page is nothing more complicated than a big string.
All the fancy work you can do with language like PHP - reading from databases and web services and all that - the ultimate end goal is the exact same basic principle: generate a string of HTML*.
Your big HTML string doesn't become anything more special than that until it's loaded by a web browser. Once a browser loads the page, then all the other magic happens - layout, box model stuff, DOM generation, and many other things, including JavaScript execution.
So, you don't "call JavaScript from PHP", you "include a JavaScript function call in your output".
There are many ways to do this, but here are a couple.
Using just PHP:
echo '<script type="text/javascript">',
'jsfunction();',
'</script>'
;
Escaping from php mode to direct output mode:
<?php
// some php stuff
?>
<script type="text/javascript">
jsFunction();
</script>
You don't need to return a function name or anything like that. First of all, stop writing AJAX requests by hand. You're only making it hard on yourself. Get jQuery or one of the other excellent frameworks out there.
Secondly, understand that you already are going to be executing javascript code once the response is received from the AJAX call.
Here's an example of what I think you're doing with jQuery's AJAX
$.get(
'wait.php',
{},
function(returnedData) {
document.getElementById("txt").innerHTML = returnedData;
// Ok, here's where you can call another function
someOtherFunctionYouWantToCall();
// But unless you really need to, you don't have to
// We're already in the middle of a function execution
// right here, so you might as well put your code here
},
'text'
);
function someOtherFunctionYouWantToCall() {
// stuff
}
Now, if you're dead-set on sending a function name from PHP back to the AJAX call, you can do that too.
$.get(
'wait.php',
{},
function(returnedData) {
// Assumes returnedData has a javascript function name
window[returnedData]();
},
'text'
);
* Or JSON or XML etc.
I always just use echo "<script> function(); </script>"; or something similar. You're not technically calling the function in PHP, but this is as close as you're going to get.
Per now (February 2012) there's a new feature for this. Check here
Code sample (taken from the web):
<?php
$v8 = new V8Js();
/* basic.js */
$JS = <<< EOT
len = print('Hello' + ' ' + 'World!' + "\\n");
len;
EOT;
try {
var_dump($v8->executeString($JS, 'basic.js'));
} catch (V8JsException $e) {
var_dump($e);
}
?>
You can't. You can call a JS function from HTML outputted by PHP, but that's a whole 'nother thing.
If you want to echo it out for later execution it's ok
If you want to execute the JS and use the results in PHP use V8JS
V8Js::registerExtension('say_hi', 'print("hey from extension! "); var said_hi=true;', array(), true);
$v8 = new V8Js();
$v8->executeString('print("hello from regular code!")', 'test.php');
$v8->executeString('if (said_hi) { print(" extension already said hi"); }');
You can refer here for further reference:
What are Extensions in php v8js?
If you want to execute HTML&JS and use the output in PHP http://htmlunit.sourceforge.net/ is your solution
Thats not possible. PHP is a Server side language and JavaScript client side and they don't really know a lot about each other. You would need a Server sided JavaScript Interpreter (like Aptanas Jaxer). Maybe what you actually want to do is to use an Ajax like Architecture (JavaScript function calls PHP script asynchronously and does something with the result).
<td onClick= loadxml()><i>Click for Details</i></td>
function loadxml()
{
result = loadScriptWithAjax("/script.php?event=button_clicked");
alert(result);
}
// script.php
<?php
if($_GET['event'] == 'button_clicked')
echo "\"You clicked a button\"";
?>
I don't accept the naysayers' answers.
If you find some special package that makes it work, then you can do it yourself! So, I don't buy those answers.
onClick is a kludge that involves the end-user, hence not acceptable.
#umesh came close, but it was not a standalone program. Here is such (adapted from his Answer):
<script type="text/javascript">
function JSFunction() {
alert('In test Function'); // This demonstrates that the function was called
}
</script>
<?php
// Call a JS function "from" php
if (true) { // This if() is to point out that you might
// want to call JSFunction conditionally
// An echo like this is how you implant the 'call' in a way
// that it will be invoked in the client.
echo '<script type="text/javascript">
JSFunction();
</script>';
}
Ordering It is important that the function be declared "before" it is used. (I do not know whether "before" means 'lexically before' or 'temporally before'; in the example code above, it is both.)
try like this
<?php
if(your condition){
echo "<script> window.onload = function() {
yourJavascriptFunction(param1, param2);
}; </script>";
?>
you can try this one also:-
public function PHPFunction()
{
echo '<script type="text/javascript">
test();
</script>';
}
<script type="text/javascript">
public function test()
{
alert('In test Function');
}
</script>
PHP runs in the server. JavaScript runs in the client. So php can't call a JavaScript function.
You may not be able to directly do this, but the Xajax library is pretty close to what you want. I will demonstrate with an example. Here's a button on a webpage:
<button onclick="xajax_addCity();">Add New City</button>
Our intuitive guess would be that xajax_addCity() is a Javascript function, right? Well, right and wrong. The cool thing Xajax allows is that we don't have any JS function called xajax_addCity(), but what we do have is a PHP function called addCity() that can do whatever PHP does!
<?php function addCity() { echo "Wow!"; } ?>
Think about it for a minute. We are virtually invoking a PHP function from Javascript code!
That over-simplified example was just to whet the appetite, a better explanation is on the Xajax site, have fun!
For some backend node processing, you can run JS script via shell and return the result to PHP via console.log
function executeNode($script)
{
return shell_exec('node -e \'eval(Buffer.from("'.base64_encode($script).'", "base64").toString())\'');
}
$jsCode = 'var a=1; var b=2; console.log(a+b);';
echo executeNode($jsCode);

How to pass a value from JavaScript in php?

Translate translator from Google. So that did not swear if something is not clear. Itself from Russia.
The question arose. How to pass the value of the alert in the javascript in the variable $ value in php, and write it in the case file. And another question: how to hide the alert? or use instead to visually it was not visible, but the value was passed?
//a lot of code
{
console.log(data);
alert(data['value']);
}
});
So. Also there is a PHP script that writes logs (current page and the previous one) to a file. According to this principle here:
//a lot of code
$home = $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$referer = $_SERVER['HTTP_REFERER'];
$value = how the value of the java script to convey here?;
$lines = file($file);
while(count($lines) > $sum) array_shift($lines);
$lines[] = $home."|".$referer."|".$value."|\r\n";
file_put_contents($file, $lines);
It is necessary that the value of js is transferred to the php-script and write to the file. How to do it? Prompt please. I am a novice in all of this.
PHP scripts run before your javascript, which means that you can pass your php variables into javascript, but not the other way around. However, you can make an AJAX POST request from JavaScript to your PHP script, and grab the POST data in PHP through the global $_POST variable.
Assuming you use jQuery, your JavaScript would look something like:
// assign data object:
var data = { value: "test" };
// send it to your PHP script via AJAX POST request:
$.ajax({
type: "POST",
url: "http://your-site-url/script.php",
data: data
});
and your PHP script would look like:
// if the value was received, assign it:
if(isset($_POST['value']))
$value = $_POST['value'];
else
// do something else;

Use variable value on php webpage in separate javascript function

I have a server running which has a php function which returns true/false depending on input values. Currently I am just echoing the result on the page. I want to use this true/false in a to evaluate a condition in a javascript function running completely separately from the server.
Is there a javascript function I can use to get the text from a webpage and put it in a variable? I looked at the jquery load() function but this doesn't seem like it will work for this purpose.
Keep the output of the PHP script as simple as possible (a text response outputting only "true" or "false").
To send a text response (instead of an HTML response), you can use:
header("Content-Type: text/plain");
You have to call this function before outputting anything.
Now, assuming you can access the output of the script at the URL http://www.example.com/webpage.php
if($.ajax({type: "GET", url: "http://www.example.com/webpage.php", async: false}).responseText == "true")
{
// do something
}
else // "false"
{
// do something else
}
Not sure if it would work, but you might try using document.body.innerHTML. It gets you the innerHTML from the body element from the document (which, in your case, should be a true or false string).
If you are just wanting to use jQuery to get the echoed out result of your php you can do:
var whatever = "<?php echo $result ?>";
In your PHP/HTML (assuming you have a function named "yourFunction" that returns a boolean):
<div id="your_id">
<?php echo yourFunction()?'true':'false';?>
</div>
And in your JavaScript
if($('#your_id').text() == "true")
// do something
else
// do something else
You could treat it like html, update your doc to add a tag around the result. "true" at which point your almost using XML.
You should be able to get the raw response. I usually don't recommend consuming raw text tho as people could inject malicious js into the response.

How to assig a PHP variable a value inside a JavaScript block?

if ($page_title->exists()) {
//the rest of the code is in php.here i insert a javascript for the confirm box.
echo'<script type= "text/javascript" >
var b=confirm("This page already exists.would you want to edit");
if(b == true)
//here i want to assign a php variable , say for eg. $a to 1 so that i can use that value of $a in an if clause outside this javascript code.
</script>';
}
if($a==1)
..some code..
How do I do it?
The PHP code is executed on the server side and is all done at the point where your javascript is executed on the client side.
To communicate the value from the client to the server you typically either use AJAX (tutorial on how to do it here: http://www.w3schools.com/ajax/ajax_httprequest.asp) or store the value in a form and submit it together with data you are going to send down later anyway.
Good luck
Javascript runs on the client (browser) and PHP on your server. So you have to transport the variable to the server.
Most easy way to do this is to use the URL to send this information, for example: http://example.com/myscript.php?a=1. Then you can grab a using $_REQUEST['a'] and use it.
A more sophisticated (and complex) method is to use AJAX to send the variable to your PHP script, so it can return some data which you can use to modify your page.
What you need depends on your application, so you should provide some more details if you do not know what method is best to you in your situation.
you can send the result back to php using an ajax call, e.g.:
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script>
<script type="text/javascript">
x = confirm('Page exists, would you like to edit it?)
$.post('script.php', {x: x}, function(data) {
if (data == '1') {
alert('ok');
} else {
alert('not ok');
}
});
</script>

Categories

Resources