1

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 the 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.

2
  • I've updated my question to be more clear.
    – Catfish
    May 25, 2011 at 22:14
  • Slight nitpick. Passing the address data via the url is not the "codeigniter way". May 31, 2011 at 17:45

10 Answers 10

4
+50

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.

2
  • IMO _GET would've been better, but this does the trick nicely. May 31, 2011 at 17:54
  • I was already using post for the input so I just used post on page 2 in the javascript. I can't believe I was not thinking of this solution.
    – Catfish
    Jun 1, 2011 at 22:17
3

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.

5
  • 2
    I'd rather not use query strings if possible since codeigniter makes my url's pretty.
    – Catfish
    May 25, 2011 at 21:46
  • 1
    Doesn't matter, you just do string matching on your chosen URL structure May 25, 2011 at 21:49
  • 1
    codeignigter can handle running both query strings and your pretty urls, makes it decent for data that is very variable (like this case)
    – lsl
    May 31, 2011 at 1:16
  • I don't have a ton of experience with codeignighter but you can rewrite your urls so that a "pretty" url is displayed to the end user but the url with query strings is actually sent to the server.
    – Adrian
    May 31, 2011 at 17:34
  • @Catfish you don't want user input to appear in your "pretty urls". May 31, 2011 at 17:54
3

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:

  1. 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);
  2. In the second page controller (let's pretend the function is called get_map and it is in the maps controller you get the data in this way

    function get_map($address = null)
    
  3. Now you have the input address. Pass it to the view that should contain the map.

3

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 :)

3
  1. 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>
2
  • Shouldn't rely on a javascript solution. May 31, 2011 at 17:46
  • 1
    That code may not work for addresses with apostrophes in them (e.g., 47 O'Hara Street). One solution would be to use htmlspecialchars() and pass it the ENT_QUOTES flag so it escapes single quotes. Another possibility is to (before the code above) use PHP to regexp match the address against a set of known acceptable chars (letters, numbers, space, certain punctuation, and probably little or nothing else) that does not include apostrophes and strip out anything that isn't in that regexp (so 41 O'Hara Street becomes 41 OHara Street). The OP will probably want to do a regexp validation anyway.
    – Trott
    Jun 1, 2011 at 13:50
2

@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;
?>
0

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..

4
  • Don't use sessions if you can just use the $_GET global. May 31, 2011 at 17:56
  • 1
    @SkippyChalmers i think you misanderstood the code above, we don't use php sessions at all. Catfish initially ask for a full javascript solution, this is a FULL JAVASCRIPT solution it use browser sessionStorage or window.name property so there's no $_GET at all. Please read and underestand the code before leaving unjustified and inapropriate bad comment.
    – malko
    Jun 1, 2011 at 0:33
  • Why on earth do you need to use any kind of local storage at all. The OP's problem is simple, and he is clearly showing a lack of understanding of his own problem - which you as an answerer have a duty to point out and attempt to correct. You haven't at all, instead you've provided a JS only solution relying on a hack - instead of at the very least, using javascript to pull the necessary query parameters from the url. For that, your answer definitely deserves a -1. Jun 1, 2011 at 7:53
  • 1
    We all argued without any reason, on a stupid, trivial question. Let's extinguish the fire, shall we ?
    – tXK
    Jun 12, 2011 at 7:19
0

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/

3
  • It's a bad idea to rely on JS here because.. ?? Please, do explain.
    – tXK
    May 31, 2011 at 20:45
  • Because this site will not always run on a browser that has javascript support. Even if the feature is designed to be a google map, a static image or otherwise html driven solution should still be available, thus a JS-only solution isn't a good idea. Jun 1, 2011 at 7:55
  • 1
    using google maps API automatically implied using javascript. so please, DO tell me, how is your argument relevant.
    – tXK
    Jun 1, 2011 at 22:01
-1

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...

-2

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>
1
  • Please if u reckon that its not a good idea then share your good one...!
    – saint
    Jun 18, 2011 at 10:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.