I have the following jquery code:
while (count < 31) {
window['cday_' + count] = <?php echo $day_1 ?>;
window['tday_' + count] = (window['cday_' + count] * formfig) / formfig2;
count++;
}
But I need $day_1 in the php echo statement to reflect the variable "count", so in theory it should be something like "echo $day_count". Is it possible to pass the var to php?
php & jquery coding:
$i=0;
while ($i < $num) {
${"day_$i"}=mysql_result($result,$i,"datavalue");
$i++;
}
?>
<script type="text/javascript">
var chart1;
var count=1;
var formfig=17;
var formfig2=2;
function chartdraw(){
while (count < 31) {
window['cday_' + count] = <?php echo $day_1 ?>;
window['tday_' + count] = (window['cday_' + count] * formfig) / formfig2;
count++;
}
The short answer here is no.
To understand what's possible, you need a deep understanding of what's going on. Your PHP code is building an HTML document (with embedded JavaScript) and sending it on to the web browser. Once the web browser (which is, of course, running on the user's machine, not your server) renders that page, it will execute the javascript. This is when the javascript variables begin to actually mean something. Until then, they are just text getting sent across the network. This point is long after the PHP code has finished running. Your server has already closed down that php instance as it sent the code to the user.
Keeping that in mind, you can send the value of a javascript variable (or any number of other things) back to your server with something called an ajax request. Essentially, this will send some information (the variable's value, and the name of the page you want) back to your server, which will in turn cause your server to build a new web page, which can have PHP code in it. That web page's content will get returned to another bit of javascript you can provide -- called a 'callback' -- which can take the page created by the second php script and make use of it. This is, of course, fairly resource intensive.
Unless you plan to do something that ONLY PHP can do, I would recommend finding a way to do as much of your logic as possible in javascript. This alleviates all these complex problems and keeps all the hard work on the user's machine.
If you can structure your code so your php code provides all the data the javascript code needs before the php finishes running, you can get away without doing anything fancy with ajax. Here's an example:
<script type="text/javascript">
var days = {};
<? for($day = 0; $day < 30; $day++) { ?>
days.<? echo $day ?> = "<? echo get_day_info($day) ?>";
<? } ?>
</script>
What this will do is create a javascript object called days. Then it will fill in days.i for i from 0 to 30. It assumes you have a function called get_day_info($day) which takes a day and returns the info for that day. I'm assuming here that you're dealing with strings -- if not, you will need to remove the quotes, and possibly do other things to wrap the data depending on what format it takes.
I belive the only way is using ajax. http://api.jquery.com/jQuery.ajax/
Not without changing your approach significantly.
The problem is that PHP exists entirely on your server, where javascript exists in the browser. PHP does really know anything about javascript. PHP will completely render your page before any javascript has been run at all. So there is no way to get this value back in easily.
You can use ajax in order to run javascript which can load data or hit URLs on your server, but you cant simply substitute javascript variables in PHP. The reason you can do it with PHP variables is because the PHP actually is generating the javascript.
Have javascript store the value in a hidden field and pick up the value with PHP that way?
Related
I have a function called $function. I want my code to add 1 to $function every second, and in "live".
$function = 100;
$add = $function + 1;
echo $add;
How do I run/execute $add every second? I would like to see the number getting bigger in "live" (without having to refresh the page every time I want to see the result).
PHP is a server-side language which can only actually do anything on your server. If you want things to update dynamically on the client (i.e. your browser) you need a client-side language, like JavaScript. Generally server-side languages like PHP generate client-side code which is then transferred over a network to your browser.
For example, you could get your PHP server to output the following HTML:
<html>
<body>
<div id="number">1</div>
<script>
var text = document.getElementById("number");
var number = 1;
window.setInterval(function() {
// code in here will repeat every 1000ms
number = number + 1;
text.innerText = number;
}, 1000);
</script>
</body>
</html>
If you're just learning to program, you might enjoy learning HTML and JavaScript more, without worrying about the server for now, as you can get to see the results of your program more dynamically. A good resource might be Codecademy or direct from Mozilla
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 have a function in my Javascript script that needs to talk with the PHP to get the data in my database. But I'm having a small problem because I start the PHP in the for loop in Javascript, and then inside that for loop I get the data in my database. But the pointer in the for loop inside the PHP code is not working.. I guess the problem is in escaping? Or maybe it's not possible at all.
Here's my code:
(function() {
var data = [];
for(var i = 0; i < 25; i++) {
data[i] = {
data1: "<a href='<?= $latest[?>i<?=]->file; ?>'><?= $latest[?>i<?=]->title; ?></a>", // The problems
data2: ....
};
};
});
I think you are confused, you are trying to use a variable of javascript in php.
You cannot do this:
<?= $latest[?>i<?=]->file; ?>'
Which expands to:
<?php
$latest[
?>
i
<?php
]->file;
?>
how can you possibly know the value of i, if i is a variable generated in the client side?, do not mix the ideas, i is defined in the browser and the php code is on the server.
You may want to consider using PHP to output the JavaScript file, that way the PHP variables will be available wherever you want them.
The following links better explain this.
http://www.givegoodweb.com/post/71/javascript-php
http://www.dynamicdrive.com/forums/showthread.php?t=21617
1.Pass the javascript variable to the URL to another php page.
window.open("<yourPhpScript>.php?jsvariable="+yourJSVariable);
2.Then you can use this variable using $_GET in the php script.
$jsVaribleInPhp=$GET['jsvariable'];
//do some operation
$yourPhpResult;
3.Perform any server side operation in the Php and pass this result.
header("Location:<your starting page>?result=".$yourPhpResult);
4.Redirect back to the page you started from thus passing the result of PHP.
Php and Javascript have different roles in web development.
This task can also be performed if there's a php script and js in the same page. But that I leave for the readers to work it out.
Hope this helps!!
I'm trying to do something that goes far over my current skills yet I believe I can do it, I would be imensely thankfull if you point me to an already developed script for this matter.
My question comes from what runs first? Javascript or php? because I need to asynchronosly include a php file into the page.
My idea is this, if user has a screen width wider then 1024, draw an extra fixed position div, if not, don't draw it. That div is supposed to take in a flash object with a clickable link.
My idea would be to:
Get resolution with javascript.
Use jQuery to send ajax json var into .php file that stores res vars into a session cookie.
Read the cookie with php, decide to include the extra .php file or not. That file should then eco the extra div with flash object.
Is this possible? Is there an easier way? Since this is to include in a Zencart personal store of mine, does it conflicts with the zencart cookie session or can a user have more then 1 type of session cookie per website? it can right?
Best Regards, any help appreciated,
Joricam
Yes, it's possible - but now in the way you're describing. PHP runs server side and Javascript runs client side, i.e. PHP is executed before any Javascripts. However, nothing says you cannot do this only with Javascript - and it would actually be trivial to solve with jQuery (as you tagged the question with it). Just let your Ajax called PHP-page return the inline HTML, and print it with jQuery instead. No need for cookies, either.
PHP runs first because the page hasn't loaded yet and javascript is run user-side, but once the page is loaded, ajax allows you to make calls to a php script and recieve a result that you can then add to the page via javascript.... so yes it's doable:)
Sessions can contain as many keys as you need them to, just name them something specific
<script language="javascript">
if (window.location.search == "") {
window.location.href = window.location + "?width=" + screen.width + "&height=" + screen.height;
}
</script>
This will redirect the page you try to access to the same page but sending parameters to the page.
Then you would be able to:
<?php
$width = $_get['width'];
$height = $_get['height'];
?>
I'm working on a JavaScript based page that returns the cost of delivery, depending on what the user selects(Region, service(pre 12, etc) and weight). I have muddled my way through as I just don't know JS.
My questions are:
Can I pass the variable between functions - as detailed in the script below?
Once the above has been achieved, I need to process the variables to display the result, now I could do a massive ifelse, don't really want to because there will be some 30 odd possibilities. All required info is in a SQL DB so this would be my preferred choice but I'm not sure how to do this with JS, the whole Browser side, Server side issue. Would I need to pass the variables(as above) to PHP (once all 3 are set) to grab the data from the SQL DB? If so, I'm not sure how to do this.
If I do use PHP then the page will have to be reloaded, is it possible to get this to be seamless to the user, i.e., all their selections are still displayed?
function flag(nation, area) {
this.nation = nation;
var el = document.getElementById("desc");
el.innerHTML = 'The region you have selected is <b>' + area + '</b>';
document.getElementById("flag").innerHTML = '<img src="images/flags/' + nation + '.jpg">';
}
function output(service) {
this.service = service;
var el = document.getElementById("service-desc");
el.innerHTML = 'You have selected a <b>' + service + '</b> service.';
document.getElementById("clock").innerHTML = '<img src="images/clock-' + service + '.png">';
}
function result() {
//get varibles(nation & serive) from functions above ~ not sure how to do this!
//process varibles
if (nation == "UK" && service == "Standard next day") {
document.getElementById("result").innerHTML = '£9.99';
} else if (nation == "UK" && service == "Before 12pm") {
document.getElementById("result").innerHTML = '£14.99';
}
// etc,etc,etc....
else {
document.getElementById("a1").innerHTML = "";
}
}
There are basically three alternatives:
Have the PHP script put all the data on the page as JavaScript arrays and handle everything in JavaScript. If the total amount of data is not too much, this is an OK solution
Reload the entire page when the user makes a selection and handle everything in PHP (including keeping existing selections) - this is the only way to make it work without JavaScript, but has only disadvantages otherwise.
Use AJAX when the user makes a selection, i.e. JavaScript calls the server in the background and a special PHP script returns only the relevant data (typically using JSON format) which the JavaScript then uses to update the page. This is how it's typically done nowadays.
In javascript if you declare a variable outside a function you can use it from any function, this is a global variable. E.g.
var x, y;
function flag(nation,area)
{
x = nation;
y = area;
}
function output(service)
{}
function result() {
//In here you can do whatever you want with x and y
}
You would be best creating a PHP script that gets your data from the database and returns it to your javascript. The best way to do this would be an AJAX call, this would allow you to seemlessly get the data from the database that you want and only update specific parts of the page rather than the whole page.
I would recommend having a look at jQuery as it has some very easy to use AJAX methods. It is just a library that wraps javascript and has lots of easy to use functionality, good introduction vids here
Here is a tutorial on how to use jQuery to call a PHP script which gets data from a database.
You want AJAX - write a server-side data feed in PHP and browser-side mini-application in JS that talks to the server feed and updates the webpage accordingly. This is achieved using Javascript's XMLHttpRequest object. I highly recommend you learn to use it and then rely on a JS library that wraps around it and provides higher level services (like jQuery)