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;
Related
Is there any way to do it without doing this:
send javaScript variable to php variable
OR can I do that, and "cover up" my url to the original one, without refreshing the page(still keep the php variables)?
I believe you are incorrect - you actually DO get the 'javascript' variable to PHP - using the jQuery code snippet below by #MikeD (jQuery is a javascript library containing many and many functions that you can then use in your code - making things little easier to do) above you can pass the javascript variable to PHP page.
On the php page you can assign this variable (originating on client side - browser) to PHP variable using something as simple as this:
$variable = $_REQUEST['javascriptVariable'];
A nice and easy way to do this is like this:
PHP
<div id="something" data-info="<?php echo $info ?>"></div>
Jquery
var info = $("#something").data("info");
EXPLANATION
Put the variable as a data attribute in some div using PHP, and then grab the data attribute from the DOM using JQuery.
There's two points that you can use PHP to create javascript vars, the first being when the "page" is created on the server, the second point is during the operation of the javascript application (once the page is loaded). The second point will require some sort of client side request (ajax, websocket, etc).
The best way to do it (in my experience) is using PHP's json extension which allows you to encode a PHP object/array into a json serialized string that can be unserialized/decoded within the browser into equivalent javascript types.
To do this during page generation can be done similarly as follows:
echo "jsvar = eval('('+".json_encode($phpvar)."+')')";
Note that the eval occurs on client side within browser and is common in every major js library.
Requesting an object during the normal operation of your javascript app will vary depending on how the data is requested, but each way will involve an asynchronous javascript request, a PHP script to handle the request (on the server side), and then a javascript side handler/callback that is called when data is received within javascript as a response to the request.
I typically use PHP to echo a json_encode()'ed string as plain text, then code the javascript side response callback to decode the response and fire an event. For a basic example:
PHP side:
<?php echo json_encode($responce_object); // DONE ?>
javascript side:
on_responce(responce)
{
var res_obj = eval('('+responce+')');
fire_event(res_obj);
}
The example above is very simple and generic to show how it works, but not much more is required for a fully functional solution. The real magic for a specific solution will happen within the "fire_event()" method - this is where the object can be handled via jquery or whatever.
You would want to wrap a lot of security around this code before putting it anywhere you care about, but it illustrates the principles without putting too much mud in the water:
<head>
<script>
function loadDiv(url)
{
$('#YourDivID').load(url);
}
</script>
<body>
<?php
$thisID = 1; //set here for demonstrative purposes. In the code this was stolen from, a MS SQL database provides the data
$thisGroup = "MyGroup";
$thisMembers = "TheMembers";
$thisName = "Just a example";
echo "<button onclick=loadDiv('http://siteonyourdomain.com/yourpage.php?ID=$thisID&group=$thisGroup&members=$thisMembers');>$thisName</button>";
//note this only works for sites on the same domain. You cannot load google.com into a div from yoursite.tv
//yourpage.php would have some code like this
// if(isset($_GET['thisID'])) {$myID = $_GET['thisID']} else {$myID = NULL}
?>
<div id="YourDivID">
Before
</div>
<?php
//I tested this code before posting, then replaced the domain and page name for security's sake
If you use $.ajax to make the submission to php you won't need to refresh the page. The code for the example on that page would look like this
var javascriptVariable = "John";
$.ajax({
url: '/myphpfile.php',
type: "GET",
dataType: "json",
data: {
name: javascriptVariable,
},
success: function( data ) {
// do success function here
},
error:function( xhr, ajaxOptions, thrownError ) {
// handle errors here
}
}, "json");
I want the value of JavaScript variable which i could access using PHP.
I am using the code below but it doesn't return value of that variable in PHP.
// set global variable in javascript
profile_viewer_uid = 1;
// php code
$profile_viewer_uid=$_POST['profile_viewer_uid'];
this gives me the following error :-
A PHP Error was encountered
Severity: Notice
Message: Undefined index: profile_viewer_uid
Another php code i used which give empty value
$profile_viewer_uid = "<script language=javascript>document.write(profile_viewer_uid);</script>
When I echo it shows nothing.
Add a cookie with the javascript variable you want to access.
document.cookie="profile_viewer_uid=1";
Then acces it in php via
$profile_viewer_uid = $_COOKIE['profile_viewer_uid'];
You will need to use JS to send the URL back with a variable in it such as:
http://www.site.com/index.php?uid=1
by using something like this in JS:
window.location.href=ā€¯index.php?uid=1";
Then in the PHP code use $_GET:
$somevar = $_GET["uid"]; //puts the uid varialbe into $somevar
Here is the Working example: Get javascript variable value on the same page.
<script>
var p1 = "success";
</script>
<?php
echo "<script>document.writeln(p1);</script>";
?>
You might want to start by learning what Javascript and php are. Javascript is a client side script language running in the browser of the machine of the client connected to the webserver on which php runs. These languages can not communicate directly.
Depending on your goal you'll need to issue an AJAX get or post request to the server and return a json/xml/html/whatever response you need and inject the result back in the DOM structure of the site. I suggest Jquery, BackboneJS or any other JS framework for this. See the Jquery documentation for examples.
If you have to pass php data to JS on the same site you can echo the data as JS and turn your php data using json_encode() into JS.
<script type="text/javascript>
var foo = <?php echo json_encode($somePhpVar); ?>
</script>
If you want to use a js variable in a php script you MUST pass it within a HTTP request.
There are basically two ways:
Submitting or reloading the page (as per Chris answer).
Using AJAX, which is made exactly for communicating between a web page (js) and the server(php) without reloading/changing the page.
A basic example can be:
var profile_viewer_uid = 1;
$.ajax({
url: "serverScript.php",
method: "POST",
data: { "profile_viewer_uid": profile_viewer_uid }
})
And in the serverScript.php file, you can do:
$profile_viewer_uid = $_POST['profile_viewer_uid'];
echo($profile_viewer_uid);
// prints 1
Note: in this example I used jQuery AJAX, which is quicker to implement. You can do it in pure js as well.
PHP runs on the server. It outputs some text. Then it stops running.
The text is sent to the client (a browser). The browser then interprets the text as HTML and JavaScript.
If you want to get data from JavaScript to PHP then you need to make a new HTTP request and run a new (or the same) PHP script.
You can make an HTTP request from JavaScript by using a form or Ajax.
These are two different languages, that run at different time - you cannot interact with them like that.
PHP is executed on the server while the page loads. Once loaded, the JavaScript will execute on the clients machine in the browser.
In your html form make a hidden field
<input type="hidden" id="scanCode" name="SCANCODE"></input>
Then in your javascript update the field value by adding;
document.getElementById("scanCode").setAttribute('value', scanCode);
This could be a little tricky thing but the secure way is to set a javascript cookie, then picking it up by php cookie variable.Then Assign this php variable to an php session that will hold the data more securely than cookie.Then delete the cookie using javascript and redirect the page to itself.
Given that you have added an php command to catch the variable, you will get it.
You need to add this value to the form data that is submitted to the server. You can use
<input type="hidden" value="1" name="profile_viewer_uid" id="profile_viewer_uid">
inside your form tag.
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);
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 ;-)