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.
Related
Good evening ..
I have a form where you assign work to a worker, however, if that work is already assigned then user has a choice of either reassigning it or returning to previous page.
so I'm trying to write the syntax for a confirm alert that redirects user to one page or another depending on his choice ,
I placed it within the head section and it goes something like this:
function show_confirm() {
var con = confirm("Already assigned.. would you like to reassign?");
if (con ==true) {
window.location = "reassign.php"
} else {
window.location = "index.php"
}
}
The question is : how do you call this function depending on an if statement? I have seen some examples on the internet where people place the function (rather than just call it ) directly inside the if statement, but wouldn't that be mixing different kinds of script?
So .. how do you call the function from within this if statement?
I tried this but it didnt work:
$flat=$_POST['flat'];
$check= mysql_query("SELECT * FROM assignment WHERE flat = '$flat'");
$num= mysql_num_rows($check);
if ($num!=0) { show_confirm();
} else { //irrellivant code
Since this is a JavaScript function, you just place the function itself inside the header, and then in PHP, you output the call to the function in your if like this:
if ($num!=0) {
echo '<script type="text/javascript">show_confirm();</script>';
} else {
//irrelevant code
}
PHP is a server-side scripting language, while JavaScript is client-side. You can't call the JavaScript function directly from the server-side like you were trying to do. You can however output javascript to the page via PHP as I have done in my example.
Yes, you are trying to mix php (server side) and javascript (client side) in one process which won't work.
When you submit the form to check if they are already assigned you then need to redirect them to a confirm page, from there you would have yes/no buttons linking to the reassign and go back pages.
The best solution would actually be to handle this with AJAX but given the nature question I think its best to stick with non-ajax workflow.
Let me know if that makes sense, if not I will add some more detail
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;
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);
Is it possible to refresh only the part of the page? How?
the part:
if (checkExpiry($member->expires)==true) {
print timeLeft($leftts);
} else {
print "expired";
}
I have table which is showing name, email, time until membership ends and I need to refresh 'time until membership ends' every second.
You can check out AJAX, where Javascript calls a PHP application of yours an updates only a certain part of the site.
I presume you mean "refresh the page". The answer is not directly. PHP is executed on the server and "normal" HTTP doesn't do server side pushes. This means that once a page is sent to a client, it won't reload unless something or someone on the client asks for it again.
To implement this, you're going to have to, as Ólafur suggested, use some Javascript on the client side to check the timer and then reload the page (or part of it if you prefer) using an AJAX style call.
If you use Javascript, you can do like this:
<script src="jquery.js"></script>
<script>
$(document).ready(function()
{
//time_to_expire.php is called every second to get time from server
var refreshId = setInterval(function()
{
$('#expire').load('time_to_expire.php?userID=<? echo $userID; ?>);
}, 1000);
});
</script>
inside time_to_expire.php you'll put your code to provide the time remaining to expire the user account!
Note that in that example I'm sending a variable "userID" that will contain the user ID for properly retrieve data from the time_to_expire.php file...
Hope it helps or give's you an idea... :)
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 ;-)