PHP Javascript variable help - php

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);

Related

using javascript and php together to validate

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;

Echoing mysql statement inside of javascript

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.

Populate PHP variable with AJAX?

Im not sure if this is possible, but at the moment I have a form on my page where users can insert their interests, beneath that form are 3 PHP variables (Which dont currently show at first as there is no value assigned to them).
When a user enters an interest and clicks submit, my AJAX takes over, populates the table and then reloads the page so the Variable now shows as it has a value.
Is it possible to not have to refresh the page, so I can say "if success $var = 'value';"?
I hope this doesnt sound too confusing, thanks
Since you're already using AJAX, why don't you just do the logic using Javascript? If you're using jQuery, have a success callback function execute the code you want.
The problem with sending data from AJAX to PHP is that PHP is a server side language, while AJAX is a client side one. By the time your browser sees the page, the PHP has been entirely executed and returned to you as HTML / CSS / Javascript etc.
No, you can't. By the time the HTML has rendered/displayed in the browser, PHP will most likely have long since finished generating the HTML in the first place. You could round-trip the values through an AJAX handler and then populate the places in your page where the values are displayed, but when why bother round-tripping? Just have the AJAX call fill in the values right then and there.
It is absolutely possible, and quite easy to do. Just make another php script and call it from your form page's javascript (I'm going to assume you're using jQuery):
$('#mysubmit').click(function() {
$.getJSON(
'form_ajax.php', // This is the php file that will be called
{ formVar1: $('#form-var-1').val() }, // Add all your form data here
function(data) {
// This is the function that is called after the php script is
// done executing. The 'data' variable will contain the $data
// array you see in the following php file.
}
);
});
I prefer to use JSON, but other approaches are just as good. Check out the documentation for getJSON() and ajax(). Your php file would look something like this:
<?php
$data = array();
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$data['formVar1'] = $_POST['formVar1'];
}
echo json_encode($data);
?>
Of course, yours would probably do a lot more with the form data. Also, theres plenty of other approaches so go explore for the one the best suits your needs.

How do I assign a javascript variable to a PHP variable?

I have a javascript variable which holds some information and I want that to assign in a PHP variable. Here is what I am using:
<script type="text/javascript">
function redirectToFacebook()
{
var facebookMessage = encodeURI(document.getElementById('txt_msg').value);
}
</script>
<?php
$_SESSION['sess_facebook_message'] = facebookMessage;
?>
Any help is really appriciable.
Thanks in advance
Because PHP runs on the server, and JavaScript in the client, there is no way to set a PHP session variable after JavaScript works with it, as PHP has done executing before the page was even sent.
However...
If you use JavaScript to make a request (AJAX, imagehack or otherwise) to a PHP script that sets the variable, you can.
For example...
JavaScript:
function something() {
// do something with somevar
somevar = 'content';
// make an AJAX request to setvar.php?value=content
}
PHP:
$_SESSION['somevar'] = $_GET['somevar'];
Make sure you take security issues of client-generated data into account, though.
If you want to pass variables from the browser (javascript) to your backend server (PHP), you need to either:
1) Load a new page with Javascript parameters encoded either as POST or GET
2) Asynchronously call a PHP script (AJAX call) encoding the parameters as POST or GET
A simple example using a GET request (you simply append your parameters to the URL):
<script>
window.location = '/some-url?' + document.getElementById('text_msg').value;
</script>
You probably want to assign this piece of code to a button or something...
what you are trying to achieve is not possible due to API limitation.It does not provide that.
may be you can try to redirect with javascript and pass variables form php to js. They way yout tru it, it can't work.
may be, im realy not shure
try this.
<?php
function redirectToFacebook() {
var facebookMessage = ?>
<script>
document.write(encodeURI(document.getElementById('txt_msg').value));
</script>
<?php
}
?>
or using cookies.

Calling JavaScript with PHP

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 ;-)

Categories