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." );
Related
How do I use php and javascript together? from doing my own research, it seems impossible. I understand that they are different, and they each have their own special things that they do. But let's say you are validating a form. You use javascript to validate the form, then if there are no errors, you run php to insert a record. How would you do this? Is there any way to run php in javascript or call on a php method?
Generally you will see Javascript used as client side code. This means that a browser that visits your website will download your Javascript code, compile it, and run it itself. Client side code simply means that the client (person who visits your website) runs the code.
PHP, on the other hand, is used as server side code. This means that your web server parses and runs your code. Server side code simply means that the code is run on your web server.
You can give information to Javascript from PHP code. For example:
<?php
$myVariable = 'a testing variable';
?>
<script type='text/javascript'>
var fromTheServer = '<?php echo $myVariable; ?>';
</script>
The Javascript variable fromTheServer is set to the value of the php variable myVariable. All this is really doing is outputting the value of the php variable as a string, which Javascript uses. This approach can be useful, say if you wanted a Javascript array of shopping cart items the user currently has in their cart.
<?php
// get some shopping cart items using a function
$shoppingCartItemsArray = getShoppingCartItems();
?>
<script type='text/javascript'>
var shoppingCartItemsArray = "<?php echo implode('|', $shoppingCartItemsArray); ?>";
// split the string value by the | delimeter to get an array
shoppingCartItemsArray = shoppingCartItemsArray.split('|');
</script>
Now you have seen how you can integrate php with Javascript a little bit. Once again, this isn't really integrating, just outputting information from the server. What about sending information to the server? This is where AJAX comes in.
Say you are implementing a drag and drop shopping cart with Javascript. The idea is that the user picks an item from your site and drags it to their shopping cart. Upon letting go of the item, the item should be added to the users cart on the server. You would be using AJAX to post the item number to the server and wait for the server to tell you whether the item was successfully added. Note: You can build your own AJAX methods making use of native Javascript code, however, why do that when you can use a framework that has it built in? I generally use jQuery, but there are a number of other JS frameworks out there you can use.
The following very simple example shows how an interaction with Javascript and php could look like under the above circumstance. It uses jQuerys $.ajax(); function.
<?php
/** File: https://www.example.com/cart.php **/
// .. code
if($_POST['action'] === 'addItem'){
$result = addItemToCart($_POST['itemId']);
echo $result;
}
// ... code
?>
<script type='text/javascript'>
// code ....
$.ajax({
url: 'https://www.example.com/cart.php'
type: 'POST',
data: {
action: 'addItem',
itemId: getDraggedItem() // get the item id from a function
}
success: function(result){
$('#ServerMessage').html(result);
}
});
// code ....
</script>
Ok, so now you can very briefly see how php and Javascript are acting if javascript is being used as client side code.
Javascript can also be used as Server Side code, for example, IIS allows you to run JScript in tangent with VBScript.
<script type='text/javascript' runat='server'>
Response.Write("MS Server here.")
</script>
In addition to this, CommonJS provides an API for server-side Javascript code which many projects are now implementing. You may have heard of some of these, Node.js in particular. One of these projects may allow you to run php and javascript in conjunction with eachother, you'll have to look.
The bottom line is, Javascript is not only client side code. It's simply code that can be executed on either the server or the client, or as a way to clean up your iTunes library.
You need to validate in both JavaScript and PHP. But most important is PHP validation because remember: Javascript is frontend code, therefore can be modified or simply disabled by the user. So before inserting you must validate in PHP.
There are thousands of javascript validation plugins, a good one is jQuery Validate:
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
You have an example here on PHP validation:
http://buildinternet.com/2008/12/how-to-validate-a-form-complete-with-error-messages-using-php-part-1/
You can validate using javascript and insert records using php. But, it is much better if you will validate the records with javascript and php. Why? Because javascript validation will be useless when you turn off javascript in your browser, that means, if browser javascript is off, no validations will run and that means the invalid records will be inserted to your database. So it is much better to have a backup php validation.
<?php
if(PHP VALIDATION) {
echo 'You were not validated';
} else {
echo "<script src=\"FILE WITH UR JAVASCRIPT\"><script>"
}
?>
This javascript will only load and executed if the php validation is complete.
lets have this simple example:
the example given uses jquery, you might google that up.
html:
<html>
<body>
<input type = "text" name = "username" id = "username"></input>
<input type = "button" name = "submit" id = "save_button" value = "insert"></input>
<div id = "save_stat"></div> <!--This will be the status of the insertion. "loading or sucess!"---->
<script>
$('#save_button').click(function(){ //assign an event handler
//grab values
var name = $('#username').val(); //get the value of whatever the user entered
//perform HTTP ajax request
//could be $.get instead
$.post('phpfile.php', (name:name)/*this could be modified to (name:name, password: password) etc.*/, function(data){ //send the data to the php file.
$('#save_stat').html(data);
});
});
</script>
</body>
</html>
Now all that is left to do is create the php registration page and link it instead of the "phpfile.php"
And to load values in that file, sinply use $_POST['name'];
OR $_POST['password']; etc.
The above answers(suggested by others) are perfect, as they suggest the essence of what you actually require to create an in-sync Javascript and php application.
***EDIT NOTICE********
When creating the php, use echo statement when giving the user messages, i.e
if(!empty($_POST['name'])){
echo "You successfully entered your name!";
}else
echo "you forgot to enter a name";
Sample #2
if(!empty($_POST['name'])){
$message = "You successfully entered your name!";
}else
$message = "you forgot to enter a name";
echo $message;
Today I am trying to echo this php mysql statement within my javascript code, which commences onclick. However, this php statement seems to run when the page loads on not wait until the onlclick event. Is there any way to solve this? I know that I could use javascript to open other pages and then call back the php statement, but I want this to be light weight.
Thanks!
<script type="text/javascript">
function exitchatfriend() {
document.getElementById("clicktoenteraconversation<?php
echo $otherchatuser ?>").style.display='none';
document.getElementById("chatcontainer").style.display='none';
<?php mysql_query("DELETE FROM currentconversation
WHERE username='$username' and otherchatuser='$otherchatuser'"); ?>
}
</script>
You have a fundamental misunderstanding of the relative roles of PHP and javascript. PHP is a server-side will always execute before the page is sent to the client. This means that the code is never sent to the client, only the results. So if I have:
<?php echo "1+1 is ".(1+1); ?>
the source code that is sent to the client is
1+1 is 2
Javascript, on the other hand, is executed on the client's side. The code is sent to the user's computer, and you expect (hope) that the user's browser correctly interprets the code and does what is being asked. (this is why javascript can't be relied upon for validation, etc, as you can't control what the client does with the code you send them).
If you want an onclick event to run a php script, you must use AJAX (which is basically just javascript executing a new page load in the background and doing something with the result). However, ajax is not super fast (you wouldn't want to run
for(i=0;i<10000;i++){
//some ajax call
}
and you can't rely on it (so if it's super important that this query gets run:
mysql_query("DELETE FROM currentconversation WHERE username='$username' and otherchatuser='$otherchatuser'");
you will want to look for other ways of closing the conversation.
<script type="text/javascript">
function exitchatfriend() {
document.getElementById('clicktoenteraconversation'+ id_of_otherchatuser ).style.display='none';
document.getElementById("chatcontainer").style.display='none';
//A Jquery AJAX Call
var url = "YOUR_SITE_URL/ajax/deleteUser.php";
$.post(url,{" id_of_otherchatuser": id_of_otherchatuser ,"username":username},function(res){
if(res)
{
alert('deleted')
}
});
}
}
</script>
//on the server side /ajax/deleteUser.php
<?php
$otherchatuser=$POST['id_of_otherchatuser'];
$username=$POST['username'];
if(mysql_query("DELETE FROM currentconversation WHERE username='$username' and otherchatuser='$otherchatuser'"))
{
return true;
}
?>
Just to give an idea on concept.
Is there any way I could get the value of a html text field without using GET or POST or REQUEST? Alternatively, is there any way to get the field value in the same form or page else where.
This works with direct value such as "james", "system" and so on. the only problem is how do i make it work with html field values
Like:
<input type = "submit" onclick = "
<?php $username = "kut";
$result = checkname($username);
if($result)
{
?> alert("success"); <?php
}
else {?> alert("failed"); <?php
}?>
">
How can i replace "kut" with the value of a text field with id = "username" ?
<?php $username = "?>document.getElementById('username').value;<?php"?>
or something like that...???
In short, I need to get the value of a html field else where in the same page inside a javascript function, using PHP... like in the above javascriptFunction(), function
You have fundamental misunderstanding of how client-server architecture works.
PHP can be executed thousands of miles away, even days apart, from place where and when JavaScript does.
First PHP generates whole page, all of HTML, all of JavaScript source code (unexecuted), and then, after PHP is done and gone, browser starts running JavaScript.
These two can't be mixed together like you wanted, even though it may seem so in the PHP source code.
Although you can communicate with the server again using AJAX or similar, you probably should first understand how client-server architecture works and try to solve the problem without AJAX (e.g. handle all of it on server side, or all on client side).
You can not directly call a PHP function in JavaScript. You could set a JavaScript value from php before the page loads via echo. PHP is executed on the server while JavaScript is executed on the client side.
1> I suggest using jQuery to handle the Ajax part.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
function check_user(){
var user_el=document.getElementById('username');
if(!user_el){ return false; }
var username=user_el.value; // this could all be replaced with $('username').val()
$.getJSON('check_var.php',{"user":username},function(data){
if(data.result=='error'){ alert('something was wrong with the PHP stuff'); }
alert(data.userstatus);
});
}
</script>
2> On the PHP side, as check_var.php, you need a script that takes the username input, checks the DB, and sends back the result as JSON data.
<?php
if(!isset($_GET['user']){ exit; }
$username=preg_replace('#['^\w\d]#','',$_POST['user']);
//do your database query. I assume you have that part all set.
//since I'm not filling in all of that, you'll need to fix this next part to work with your system
//let's pretend it's like $found=check_user($username);
//be sure to use mysql_real_escape_string or prepared statements on the $username var since you're working with user input
$status=$some_db_error ? 'error' : 'success';
$results=array('result'=>$status,'userstatus'=>$found);
header('Content-Type: application/json');
echo json_encode($results);
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>";
}
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.