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)
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'm looking to create a page, which has a set of buttons. These buttons are each tied to different php functions (the things done by these functions have to be done server side). Basically, all the coding is done in php. The php has all the objects, the constants, all the information needed in the page. But all the actions need to be initiated by the user, by clicking the buttons.
But here comes the problem: how can I efficiently mix those php functions with my buttons? Right now I'm using ajax, javascript and jquery but the way I do it feels controversial, here's what I mean:
var continueFight;
$("#playerAttack").click(function() {
if (continueFight) {
AJAX actions here
}
one of the ajax actions is a $.post, directed to the following page:
<?php
//some fight calculations
if ($fightOver)
echo "<script>continueFight=false</script>";
?>
In the above, some php calculations are done to decide whether the fight is over, and if it is, it echoes some Javascript and returns it (through the AJAX request) to the main page, which will cause the button to stop running in the future.
This feels very messy. Is there a better way to mix PHP with buttons?
I don't see why echoing a script element. Just echo a value (e.g., 1 or nothing), and from the success callback act according to the response:
<?php
//some fight calculations
echo $fightOver;
?>
var continueFight;
$("#playerAttack").click(function() {
if (continueFight) {
$.post(url, {}, function(response) {
continueFight = !!response; // cast response to boolean
}
}
})
Your approach is exactly as you assumed. You have to treat your PHP as isolated events and not something that's keeping a constant record. Suppose you're making a game. You store the state of the game and any relevant data in a database common to the players, typically using a token passed back and forth.
Your entire game's interactions should be handled client side. By that I mean listeners that send requests to php via ajax. PHP should ONLY return state responses to interpret with js, it should NOT return html or anything goofy like that.
You can add provisions to your php to validate state server side to prevent js manipulation, but that's probably not a huge concern of yours at this point.
Looks like everyone else basically said the same thing but with code samples so I'll cut this here. If you have specific questions, feel free to ask and I may update.
EDIT
State responses would be something like an object, integer to represent a boolean, integer range, score, or anything else used as a simple response to trigger a more complex action in javascript.
So suppose you have an attack. Suppose you send the request to PHP to have it decide whether or not the attack was successful and if so, what kind of damage did it do. You might expect to get a response like this from PHP:
$response = array(
'success' => 1,
'damage' => 200,
'enemy_id' => 4
);
echo json_encode($response);
from javascript, assuming your jQuery ajax success was assigning the response to data you could evaluate the response like this:
//assume generically that this object represents the damagable players
var players = {
0: {
health: 200
},
1: {
health: 300
},
2: {
health: 30
},
3: {
health: 750
},
4: {
health: 10
}
};
// and assume this is in your success function in your ajax call
if(data.success == 1)
{
//successful attack. cause damage
players[data.enemy_id].health -= data.damage;
if(players[data.enemy_id].health <= 0)
{
// do something to kill enemy
}
}
Point is, you should return absolutely minimal data to the browser and let the client side handle all the game actions. PHP is just used to sync the game or fetch resources that aren't available to the client.
Don't echo chunks of JavaScript back to the page. Write the JavaScript in JavaScript, and pass a flag back from PHP to tell the S what to do:
JavaScript:
var continueFight;
$("#playerAttack").click(function() {
if (continueFight) {
$.post('scriptname.php', function(data) {
continueFight = data.continueFight;
});
}
});
PHP:
<?php
//some fight calculations
echo json_encode(array('continueFight' => !$fightOver));
That's as easy as it gets. Ajax requires a lot of typing, unfortunately.
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.
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?
I have a form in a PHP sending variables to a PHP file which duly inserts them into a MySQL table.
I currently have a div displaying the response from the PHP (which is anything that is printed by the PHP).
All works fine. The problem is I want to use variables that are created/updated during the PHP MySQL insert process. I.e. not only show what is printed in that PHP file, but USE those variables.
I have seen complicated use of the JSON Encoding to possibly cross this divide, but I'd love to know if that's the simplest approach. And if anyone has any good links or examples on the subject.
I assume that you want to be able to have multiple pieces of data sent back via AJAX to your page and manipulate those.
JSON is indeed the simplest way to do this. If you use PHP5, you can use json_encode() from the PHP side to send a complicated data type (such as an object or an array) back to the browser page. Then in the javascript, you use eval() on the data that is sent back (ex: var data = eval(response);) to parse it back into a usable complicated type in javascript.
There are tons of tutorials out there that will show you how to do this and explain it in further detail than a response here ever could.
Use PrototypeJS and do it like this:
Have some PHP like this
$jsonHeader = array();
if($_REQUEST['param1'])
{
echo '<p>You passed ' . $_REQUEST['param1'] . '</p>';
$jsonHeader['status'] = 'Success';
}else
{
$jsonHeader['status'] = 'Failed because the request was invalid';
}
if(is_array($jsonHeader) and sizeof($jsonHeader) > 0)
{
header('X-JSON: (' . json_encode($jsonHeader) . ')');
}
Then make your Ajax call like this
new Ajax.Request('dostuff.php', {
method: 'get',
parameters: {'param1': 'this is param 1'},
onSuccess: function(response, jsonHeader){
if(jsonHeader['status'] == 'Success'){
//Everything is OK, do stuff
}else{
alert(jsonHeader['status']);
}
},
onFailure: function(){
alert('Fail!');
}
});
Prototype grabs the X-JSON header returned by PHP and automatically sets the jsonHeader argument of the onSuccess function to a Javascript array of the values that were originally set in PHP.
The above scenario is good as long as the amount of data you're returning to Javascript fits in the HTTP header.
If you need to pass back lots of data, just have PHP output the JSON encoded result rather than making it part of the header. Then you can use the evalJSON() method of the response object in your Ajax call.
You do not have to just show what's 'printed in that PHP file', your PHP file could print JavaScript commends back to your page. You could then, upon receiving the response, execute those commands. I like to use the eval function for this, but many people here will discourage you from doing so :)
Just use the "echo" function to put put PHP variables to the standard output put.
echo $myVarName;
Or, I prefer the printf(), be sure to check for HTML in the input BEFORE you output to avoid XSS issues.
Use something like this:
printf("Your input was: %s", strip_tags(%myInputVar));
Also, remember to use the %d or %f formatters when outputting number for best security.