quarta-feira, novembro 30, 2005

Using Javascript OnChange() with php.

I'm sure that all php developers who writes more than "Hello World" code, have found themselves needing to feed a combo box when the user select something in another combo box. Like when you select your state, the page fill the cities combo box with all the cities from that state.

Again, my best friend Google helped me and I found an easy solution.

The solution was found in the Zazzybob.com website, and here's the PDF and the HTML with the solution for this problem.

As I'm bored, I'll give you a preview of the code that is in the pdf, see below:

Here is the javascript code, as you can see, you can post the form to one page with the onchange() and can post the page to another page when you click in the submit button, so here we go:

Javascript functions:

function resubmit() {
document.form_name.action="some_page.php";
document.form_name.submit();
}
function process() {
document.form_name.action="another_page.php";
document.form_name.submit();
}

Remember that you have to change the form_name to whatever you name your form.

And now the html stuff:
<select name="state" onchange="resubmit();">

<input type="submit" name="sub_form" value="Submit!" onclick="process();">

Now you are asking, where the hell is the php on it?

In this example, you just need to query your database or use any other method to populate the cities combo box, something like this:

<?
if($_POST['state']) {
$id = $_POST['state'];
$sql = "SELECT city_id, city_name FROM cities WHERE state='$id'";
...
}
?>

Remember that this is just an example, don't try using this code, you will regret it :)

For a more detailed explanation, please read the PDF.

3 comentários:

Hot Chand Sukhramdas disse...

nice hint for on change functionality.

Barton disse...

Hi,
will this method refresh/resubmit the webpage?
I just want to retrieve a value from a MySQL DB and update the total cost value.
Thanks,
Barton

Anônimo disse...

It's not working dude