How to pass data from input form to js on another page
I have a page where a user enters an address and clicks search. The user should be taken to the next page which should contain a google map with the address the user specified. How should I pass the address from the form on page 1, to js on page 2 where I can manipulate it with the google maps api? I'm using codeigniter btw.
EDIT: My ideal solution would be to use flash data or pass th开发者_运维问答e address in the url the codeigniter way. My problem is i'm not sure how I would retrieve the data if I used either of these methods.
In the CodeIgniter view for page 1:
<form method="POST" action="getMap">
<input type="text" name="address" value="" />
<input type="submit" value="Map It!" />
</form>
In the CodeIgniter view loaded by getMap() method of the controller (in other words, in page 2):
<script>
address = "<?php echo htmlspecialchars($this->input->post['address']); ?>";
// create the map with the address here
</script>
You'll want to take care to do some validation on the user input.
Use url variables to accomplish this. An example might look like this:
http://www.testurl.com/mappage.html?address=someaddress&city=somecity&state=ca&zip=12345
You can pick up the values of these url variables in javascript and pass it to the google map.
Do you want the user to be able to save the url?
If you don't, just use POST in the input field and retrieve the data in the second page this way (inside the javascript):
var address = '<?=$this->input->post('address')?>'
Otherwise:
- In javascript, in the first page, prevent the default action on form submit and instead redirect the user to [url of the second page]/[stuff written in the form] (I can give you a jquery example if you want);
In the second page controller (let's pretend the function is called
get_map
and it is in themaps
controller you get the data in this wayfunction get_map($address = null)
Now you have the input address. Pass it to the view that should contain the map.
Why don't you simply print the POSTed information via PHP on the destination page using Javascript literals syntax? As an example, if your form POSTs the following (both GET or POST query):
firstname=aaron&lastname=pink
you can print in a destination PHP page:
<html>
<head>
<script type="text/javascript">
var fname = "<?php echo addslashes($_POST['firstname']); ?>";
var lname = "<?php echo addslashes($_POST['lastname']); ?>";
</script>
</head>
<body>
...
<button onclick="alert(fname);">Say First Name!</button>
</body>
</html>
Then, you can simply use fname and lname Javascript vars as you wish, just as my sample button does on click!
I hope it was helpful, even if very simple :)
- If you are using jquery, you can use the $.cookie plugin to transfer informations between PHP and Javascript.
or 2. Send data from 1. page per $_GET or $_POST and catch the data in 2. page
<script>
var myData = '<?php=htmlspecialchars($_POST['data_from_page1']);?>';
</script>
@Catfish you're getting all confused. The objective of making your urls "pretty" and having them resemble paths / files rather than query strings is for SEO & user friendliness. You shouldn't really be including any form input in as a "pretty" url. Either send your address data via the $_POSTS global or send it as a query string. CI uses the [QSA] flag in its mod_rewrite definitions in the htaccess file so you're totally fine to stick on a (IMO) semantically correct query string on the end.
Anyway, to the code.
On form.php:
<form action="map.php" method="get">
<input type="text" name="addr" />
</form>
On map.php:
<?php
$addr = $this->input->get('addr');
// or $addr = $_GET['addr'];
echo $addr;
?>
You can use sessionStorage on modern browsers to stock your datas between pages inside the same browsing session. For older browser you can use an hacky solution that allow you to stock datas inside the window.name
if( typeof sessionStorage !== 'undefined' ){
myStorage = sessionStorage;
}else{
myStorage = {
setItem:function(key,val){
this.removeItem(key);
window.top.name+=(window.top.name.length?'&':'')+escape(key)+'='+escape(val);
}
,getItem:function(key){
var r = window.top.name.match(new RegExp('(^|&)'+escape(key)+'=([^&=]*)($|&)'));
return r?unescape(r[2]):null;
}
,removeItem:function(key){
window.top.name = window.top.name.replace(new RegExp('(^|&)'+escape(key)+'=([^=&]*)(?=$|&)'),'');
}
};
}
Now you can use myStorage.setItem('key',value)
with each of the form fields you want to keep and retrieve them on the next page with myStorage.getItem('key')
It's not more complicated than using cookies, and have the benefits to not transfer the cookie datas in each request header.
Hope this help..
Why not do it entirely in JavaScript, using the Google Maps API ?
Let's say that your Map is initialized with the variable var Map
and the Geocoder in the var Geocoder
and that you have an <form id="searchForm">Address:<input /> <br /> <input type="submit" /></form>
.
I'm also assuming you have jQuery loaded, so:
<script type="text/javascript">
$('#searchForm').submit( function(e) {
e.preventDefault();
var searchString = $(this).find('input:first').val(); // get the address
Geocoder.geocode( { 'address': searchString}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
Map.setCenter(results[0].geometry.location);
} else {
alert("Geocode error: " + status + "\n" + "Try another address");
}
});
});
</script>
Demo here: http://jsfiddle.net/toxik/Xjy3S/embedded/result/
Codeigniter sessions would be the easiest to work with.
Once you get the address submitted, set some userdata like so.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Mycontroller extends CI_Controller {
function __construct()
{
parent::__construct();
}
function index()
{
if($_SERVER['REQUEST_METHOD'] == "POST")
{
//do something from post
$this->session->set_userdata('street', $this->input->post('street'));
$this->session->set_userdata('city', $this->input->post('city'));
$this->session->set_userdata('state', $this->input->post('state'));
$this->session->set_userdata('zip', $this->input->post('zip'));
//then redirect to the next page
redirect('mycontroller/map');
}
else
{
//load the form
$this->load->view('address_form');
}
}
function map()
{
$data = array(
"street" => $this->session->userdata('street'),
"city" => $this->session->userdata('city'),
"state" => $this->session->userdata('state'),
"zip" => $this->session->userdata('zip')
);
$this->load->view('map' $data);
}
}
Set the values in a hidden input. Just have javascript grab the value of that inputs ID...
check this
// JavaScript function function abc(pram1, pram2) { alert(pram1 + pram2); } // end of JS function
now call this function on your search form. pass all parameters you want to move other page like
<a name="search" href="javascript:void(0)" onclick="abc('param1','param2')> search </a>
精彩评论