cnapsys
09-22-2008, 02:49 PM
Hey all,
I'm trying to pass a variable from javascript to php.
I know js works on the client and php on the server. I know that ajax is the way to go, I have no clue on how to do it :)
Basicly here's what I'm trying to do:
I have the following 3 vars in php
$var1 $var2 $var3
I have a form that has 3 radio buttons.
based on the option chosen by the user I need to update $var1 or $var2 or $var3 before I submit the form.
The thing is that i need to update $var not just display it. I can display it just fine with a <div> but I need to actually change the value of $var
How can it be done?
mod_webhosting
09-23-2008, 06:51 AM
Once the page is sent from the server to the browser, all memory taken by the PHP variables is released. So, $var1, $var2 and $var3 does not exist anymore after that.
What you could do is to define 3 session variables, var1, var2 and var3, and using AJAX you could update those three variables instead, and use them in PHP script.
Is there really a need to update those three variables before the form is submitted? What is the reason why you can't update them after the form is submitted? AJAX is a nice technology, but you could try redesigning your application logic because AJAX is basically used in situations when two way communication needs to be established (client to the server and server to the client) and reading your post I see only one way communication (client to the server and no vice versa communication).
cnapsys
09-24-2008, 12:03 PM
hey Akkai,
thx for your quick reply,
the reason I would like to have the 3 vars changed is because I need to let the user select a package/price and update that price before I submit the form. Otherwise I would have to create an intermediate page and submit everything from that one, which complicates things a bit more.
mod_webhosting
09-25-2008, 04:11 AM
OK, if you're sure that is the way to go, here are a few tips.
Create file on server that looks something like this:
<?php
session_start();
if ($_GET["var1"] && $_GET["var2"] && $_GET["var3"]) {
// make sure you validate $_GET["var1"], $_GET["var2"] and $_GET["var3"]!
$_SESSION["var1"] = $_GET["var1"];
$_SESSION["var2"] = $_GET["var2"];
$_SESSION["var3"] = $_GET["var3"];
echo "This text will be returned back to the browser and you can use it for whatever you want.";
}
?>
On your page you'll need to make AJAX request to the script above, something like ajax.php?var1=value1&var2=value2&var3=value3.
The example I provided is a very simple one and is not suitable for production environment. Before putting it online you should validate all the data you receive. You could put "else" clause in the code above so you can report error if not all required data is received. There are lots of fine tuning you need to do if you want to have a quality code.
I suggest you read an AJAX tutorial. Explaining in details the whole procedure is not convenient to do in a forum post.