Breaking a PHP code with Javascript confirm dialog? - php

I have PHP scrip that goes like this:
if ($cost_frm < $cost){
echo "<script type='text/javascript'>
var r = confirm('Input cost is lower than original. Sure?'));
If (r==true){
} else{
*** BREAK PHP SCRIPT ***
}
</script>";
}
And I'd like to stop ejecuting the script (or doing anything else) if the user clicks Cancel. Any tip?

You can't! PHP is server side, javascript is client side

Why not just put that entire validation into javascript?

Well I suppose if instead of running the whole script you broke it up into segments that you could activate using ajax, that might get you what you need.

You can't do that because the PHP is going to finish processing before the JavaScript runs.
PHP runs completely on the server, and only when it is done does it send the output to the browser, which then processes it. So by the time that box pops up, everything will be done.

Related

Equivalent of Alert() and Prompt() in PHP

In JavaScript, we have Alert() and Prompt() which open up a popup box for the user.
Is there an equivalent for PHP?
$Get_['asdf'] is one way to get user input... any others?
Also, one more question. Is it a requirement that PHP always be executed all at once? Or can it be like JavaScript, where it waits for the user input (e.g. popup box), then executes the rest of the code after that.
PHP is a server side language, it can't do alert messages on the client side. But you can use javascript within the php to do the alert.
<script type="text/javascript">
window.alert("Hi There, I am the Alert Box!")
</script>
For Prompt you can do something like this -
<?php
//prompt function
function prompt($prompt_msg){
echo("<script type='text/javascript'> var answer = prompt('".$prompt_msg."'); </script>");
$answer = "<script type='text/javascript'> document.write(answer); </script>";
return($answer);
}
//program
$prompt_msg = "Please type your name.";
$name = prompt($prompt_msg);
$output_msg = "Hello there ".$name."!";
echo($output_msg);
?>
Nope, there is no equivalent. All php is executed on the server-side only. Unless you're using it at the command-line, which I doubt.
It also cannot wait for user input like javascript, like you wanted. Sorry. You'll have to use ajax for that.
That's it:
$shouldProceed = readline('Do you wanna proceed?(y/n): ');
if (strtolower(trim($shouldProceed)) == 'n') exit;
proceed();
PHP can run anywhere there is a php interpreter available, that is, on a web server, or as a command line shell script. In the latter case , you could use ...
readline ( "Press Enter to continue, or Ctrl+C to cancel." );

php run before ajax is completed

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.

PHP GET variable in same document

how can i pass a variable from javascript to php using same file
in this example page keeps refreshing and i don't get to see the result
it works only if i separate the scripts... but i need it somehow like on ajax..
<SCRIPT language="JavaScript">
var carname="Volvo";
location.href="http://localhost/put.php?Result=" + carname;
</SCRIPT>
and this is the seccond part of the script ( they are both in same file )
<?php
Id = $_GET[Result];
echo $dbId;
?>
As Brian said you should put it in a conditional statement.. also your PHP is bad. Try the following
<?php if(isset($_GET["Result"])) : ?>
// do work with set variable
<?php $dbID = $_GET["Result"];
echo($dbID); ?>
<?php else : ?>
// "Result" not set
<SCRIPT language="JavaScript">
var carname="Volvo";
location.href="http://localhost/put.php?Result=" + carname;
</SCRIPT>
<? endif; ?>
I think this is a good exercise if you're trying to learn the Ajax method, in the real world I recommend using a framework like jQuery. Of course understanding how this works will help you build better applications in the end.
So you could do something like this in the PHP script:
if (!isset($_GET['Result']))
{
// include the javascript portion with the redirect
}
I'm with the others, though--I'm not seeing the value in a page load followed by an immediate redirect to the same page.
What you are trying to do cannot be done. Your script runs on the client in real time but the php will run on the server during the request. You will need to make an AJAX request.
First you will want to use Firefox with firebug and the web developer toolbar. Firebug gives a great view of ajax traffic and the web developer toolbar helps you see what's going on in the page.
Use jQuery make an ajax request to "send" the value to another php file. Don't be afraid to separate out files, in fact it's encouraged and considered good programming. If you find your sending a lot if information to a php script you will want to use JSON instead of as part of the url.
Man, you should follow a client-server pattern.. So the Client page can use some ajax to make a request to a Server page. This will response to the Client and you can make with the data what you want.
of course it will keep refreshing:)) Because as soon as the browser gets the js code, it will load that page you specify, which will send your browser the same page... you get the idea. It's like writing for(;;){}
Your question is difficult to understand (for me at least.) My guess is that you are wanting to use AJAX to send data to the server and receive a response without leaving the page.
Probably the easiest way to accomplish this is to use a library such as jQuery. (see jQuery.ajax())
PHP only runs on the server and the javascript only runs on the client. By the time your client is running the javascript, no more PHP can be executed on that request.

Is it okay to use PHP inside a jQuery script?

For example:
$(document).ready(function(){
$('.selector').click(function(){
<?php
// php code goes here
?>
});
});
Will this cause issues or slow down the page? Is this bad practice? Is there anything important that I should know related to this?
Thanks!
If you are trying to bound some PHP code with the click event then this is impossible in the way you are trying and PHP code will be executed as soon as page load without waiting for a click event.
If you are trying to generate final javascript or jquery code using PHP then this is okay.
It won't slow down the page; the PHP runs on the server and emits text which is sent to the browser, as on any PHP page. Is it bad practice? I wouldn't say "bad" necessarily, but not great. It makes for messy code - in the event where I need to do something like this, I usually try to break it up, as in:
<script>
var stuff = <?php print $stuff; ?>;
var blah = "<?php print $blah; ?>";
// Do things in JS with stuff and blah here, no more PHP mixed in
</script>
PHP is executed on the server, and then the javascript will be executed on the client. So what you'd be doing here is using php to generate javascript that will become the function body. If that's what you were trying to do then there's nothing wrong with doing it.
If you thought you were going to invoke some PHP code from javascript, then you're on the wrong track. You'd need to put the PHP code in a separate page and use an ajax request to get the result.
Sure, as long as you keep in mind that PHP code will be executed by the server before the page is sent out. Other than that, have fun.
PHP is a "backend" language and javascript is a "frontend" language. In short, as long as the PHP code is loaded through a web server that understands PHP - the downside is that you have to inline the JS, losing caching ability (there are workarounds to parse php in .js files but you shouldn't really do this). To the user it will just look like javascript and HTML. Here's the server order:
User requests page.
Apache (or equivalent) notices this
is a php file. It then renders all
the php that are between php tags.
Apache sends the page to the user.
User's browser sees the JavaScript
and executes it.
Just be sure the PHP is outputting valid JavaScript.
you have a better choice to use ajax that runs the php script when you are handling a click event
$(document).ready(function(){
$('.selector').click(function(){
$.ajax({url:"phpfile.php",type:"POST",
data:"datastring="+value+"&datastring2="othervalue,
,success:function(data){
//get the result from the php file after it's executed on server
}
});
});
});
No it's not. Just as long as you know that the JS is executed after the PHP page is parsed.

Can I add a javascript alert inside a PHP function? If yes, how? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
How to call a JavaScript function from PHP?
Can I add a javascript alert inside a PHP function? If yes, how?
Yes, you can, though I 100% guarantee this isn't what you want or what you mean:
<?php
function do_alert($msg)
{
echo '<script type="text/javascript">alert("' . $msg . '"); </script>';
}
?>
<html><head><title>Hello</title></head>
<body>
<h1>Hello World, THis is my page</h1>
<?php
do_alert("Hello");
?>
</body>
</html>
The browser runs the Javascript, the server runs the PHP.
You could also echo Javascript from your server (without HTML) and then include that script into your page by dynamically creating a <script> tag containing that Javascript. This is essentially creating Javascript on the fly for injection into your page with the right headers etc.
If you want to trace some PHP script execution, then you can use trigger_error() to create a log entry, or you could write a trace() function to store strings in a buffer and add them to a page.
If you want to trace Javascript, See Firebug for Firefox.
PHP Headers API Documentation
On-demand Javascript at Ajax Patterns
Assuming that what you mean is that you want an alert to pop up from the browser when the server reaches a certain point in your php code, the answer is "no".
While the server is running your php code, there's no contact with the browser (until the response starts coming back). There are situations in which a server may be streaming content back to the browser, and in such a case it'd be possible to have some agreed-upon convention for the server to mark the content stream with messages to be alerted out immediately, but I don't think that's what you're asking about here.
Yes, you can.
echo "<script>alert (\"js inside php\")</script>";
To explain; PHP is compiled at the server and the result is plain HTML. Therefore alerts and such cannot appear while compiling is a silent process.
If you want to show an alert in the HTML generated by PHP;
<?php
echo '<script type="text/javascript"> alert(\'Hi\'); </script>
?>
Yes, if you send Javascript code with alert to a html page from PHP.
No, if you want to call alert just by executing server side code and not sending JS to client browser.
echo "<script type='text/javascript'>alert('alert text goes here');</script>";
But i don't know how it can be useful because it will work only on the client side. If you want to debug your code you can simply print it on the screen, but if you use the alert take care of quotes because they can break the javascript part.
You can output a Javascript alert() within a PHP function in at least two ways:
A) Return it:
function sendAlert($text) {
return "<script type='text/javascript'>alert('{$text}');</script>";
}
B: Output it directly:
function echoAlert($text) {
echo "<script type='text/javascript'>alert('{$text}');</script>";
}

Categories