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");
Related
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.
$('myBtn').on("click",function(){
var parent= $(this).parent();// will give you the Parent Object of the button, that has been clicked
});
I need to send var parent to php so it knows where to display the html data (in the correct are div/class, how would i do this.
The short answer is that "You can't".
Communication between the browser (where your JS is running) and the server (where the PHP is running) is handled via HTTP. If you want to send a JavaScript object then you have to serialise it to a string and deserialise it at the other end. There is no sane way to represent an HTMLElementNode (or a jQuery object that wraps on) in that process (not least because PHP doesn't usually represent HTML in a DOM and when it does it won't be the same DOM instance as the browser is using).
Usually in this type of situation, you would request some data from PHP (possibly using one of jQuery's ajax methods) and then use JavaScript to turn it into DOM elements and insert it into the document.
Try JSON and Ajax (XMLHttpRequest) as the "client to server" mechanism
JavaScript is evaluated on client-side, when PHP is server side. You don't have trivial way to do it.
If the html data is not already generated, you would have to make a new request to the server, preferrably by the jQuery $.get function, then pass the output (again via jQuery) to the parent element.
Please use Jquery and use $.ajax for this purpose
$.ajax({
type: "POST",
url: "yourPHPPage.php",
data: "parentvar="+parent,
//parent is a javascript variable
success: function(msg){
//Message received from server,
// if you would write some code in echo there, like echo "hello";
// you would get that in msg.
}
});
to access this variable on php, use $_POST["parentvar"];
You can also send multiple values by concatinating them with & operator.
Like data:"parentVar="+parent+"&name=atif&age=23"; etc
Please let me know if further help needed.
Further help on
http://api.jquery.com/jQuery.ajax/
As far as I know, you can't pass a DOM object directly to the server -- there's too much information stored for it to be practical. You could send the HTML of the object though.
Here's an example that sends the HTML to the server. You would process it, but we just echo it back.
http://jsfiddle.net/hLD4F/
Try clicking on any of the buttons, and it will send a request. In PHP you could access this information via $_POST['html'].
i have javascript as below
html="<th>"+<?php echo __(); ?>+"</th>";
I want to add another javascript variable inside to __() function like this
<?php echo __(<js varible>); ?>
I tried
var myvarible=200;
html="<th>"+<?php echo __("'"+myvarible+"'"); ?>+"</th>";
console.log(html);
not working for me
can any one help me please
regards
You have a misunderstanding on how server side and client side code work.
The only way that you could possibly achieve what you are trying to do (apply a PHP localization function to a Javascript variable) would be like this (this code assumes you are using JQuery but can be done without it too):
var myvariable = 'hello';
$.get('http://yoursite.com/localize.php?text='+myvariable, function(localizedText) {
html = "<th>"+localizedText+"</th>";
console.log(html);
});
And then localize.php should look like this:
<?php
include('you localization library');
echo __($_GET['text']);
?>
Explanation: while your client side code (Javascript) is been executed in the browser it will call a URL which will execute your server side code (your PHP __(); function) in the server and then return the value to the client side code.
var myvarible=200;
html="<th>"+<?php echo __("'"+myvarible+"'"); ?>+"</th>";
console.log(html);
This would try to put the PHP variable "myvariable" into the script tag, what you want is closer to:
var myvarible=200;
html="<th>"+"<?php echo __("'myvarible'"); ?>"+"</th>";
console.log(html);
However, in this case, why not just skip PHP completely?
var myvarible=200;
html="<th>" + myvarible + "</th>";
console.log(html);
Javascript runs on client side and php on server side.
So var myvarible=200;
will be executed only on client side .
but will be get executed on server side. at that time myvariable will not be valid.
PHP is executed on the server, JS on the client. You cannot expect PHP to parse JS, in fact PHP will never see the JS statements, because they will be processed only once the server has processed the PHP.
var myvariable='<?php echo __("200"); ?>';
html="<th>"+myvariable+"</th>";
console.log(html);
However for this to work the javascript would need to be in a .php file that is being interpreted.
The OP wants to include a JS variable in a PHP call, which is not possible, unless you use AJAX. And you'll agree with me that code like this is only meant to cause big headaches and should be avoided at all costs.
Well yes and no.. i wouldnt do it this way. I use a helper that lets me do things like this in a consistent way. In my view file i have something like:
<?php js_call('jslib.myFunction(?,?)', __($value), 'some other value'); ?>
js_call its similar to using sprintf or a prepared statement except for js. The params are run through json_encode so the quoting and what not are correct. All these are stored in an array and then in the layout, just before my </body> i call:
<?php include_js_calls(); ?>
which then takes all the calls ive made with a js_call and outputs the string values inside a script tag resulting in something like:
<script type="text/javascript">
jslib.myFunction('first value', 'some other value');
</script>
Borrowed this brilliance from Apostrophe Cms
To do localization in javascript (for whatever reason), echo __() can obviously not be called directly.
There are different possible strategies
Include a localization string table in javascript when the page loads. Do lookup against it when needed. This table could be generated on server-side using echo __() then cached.
Make ajax requests for server-localized data. Might not be suitable for frequent updates.
I'm trying to figure out the best way to do this...I am using JQuery to submit data to a PHP function, which sends back data from the DB as JSON, which is working. The thing is, on success, I want the JQuery to execute a PHP function...and I'd rather not have to make yet another AJAX call on top of the first AJAX success - especially since the php function is something I've already used elsewhere on my page. This is my code:
JQUERY:
$.ajax({
type: "POST",
url: post_url,
success: function(group) //we're calling the response json array 'tree'
{
//WANT TO CALL THE PHP FUNCTION HERE
} //end success
}); //end AJAX
PHP:
<?php
foreach($groups as $group){
echo '<option value="' . $group->id . '">' . $group->group_name . '</option>';
}
?>
In your php script that builds your response, just add an extra property to your object that is the html string you want to put into your page and then have javascript put it where it needs to go. You have no choice but to run php functions on the server.
If you want to call a php function from your javascript you will have to execute an AJAX request to the function, in its own file, on the server. This is because javascript executes client side and PHP executes server side. Therefore, javascript does not have direct access to PHP functions.
You can use your PHP to write JavaScript, or you can call a php file from a javascript via AJAX.
Can you replicate the functionality of the PHP function with a JavaScript function?
Would this, or something similar, work for you:
$.ajax({
type: "POST",
url: post_url,
success: function(groups) //we're calling the response json array 'tree'
{
for(group in groups){
document.writeln("<option value='"+groups[group].id+"'>"+groups[group].group_name+"</option>";
}
}
}); //end AJAX
Alternatives:
Change the PHP that backs the original AJAX call so that, instead of sending back JSON, it sends back HTML exactly as you want it.
Chain a second AJAX call "inside" the success of the first, so that a second round-trip to the server is done for the JSON->HTML conversion.
Accept that sometimes you need to "duplicate" presentation-rules when you are working with multiple languages, and use something like EJS to do the same <option> stuff that PHP does elsewhere.
You have to be aware that you're dealing with two paradigms here, the first one is server-side logic (PHP) and the second one is client-side logic (JavaScript).
Unfortunately there is no way to call PHP from JS from the client without performing an AJAX call and rendering the content you want to show. However, you could prepare the result and set the body of the AJAX response with your requested HTML string.
If this is not possible, I suggest to look at the diverse number of JS frameworks that will provide helpers to generate options for select fields.
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 ;-)