views:

66

answers:

2

In menu.html, I have my menu items(a href links), let's call them, menu_1, menu_2, ....

In map.js displays the contents of a map, it calls an API to display some layers and maps. I have a lot of maps to show but i only want to call the api once.

Using AJAX, I was wondering if it's possible to have an if/then or select/case in my js, so that if menu_1 is clicked, then implement map_1 etc. without having the page to reload. The only way I thought I could do this is using Post/get .. so when you click on menu_1 it takes you to page.php?page_id=1 . JS will read that and display the map.

I'm new to JS and AJAX so please feel free to butcher me

+1  A: 

Yes, in fact if you are using jQuery you can just add click event handlers to each of these links:

jQuery("#my_menu_item").click( function(){ // Do something when the menu item is clicked... } );

You might then use jQuery.post or jQuery.get to retrieve the URL and update your page.

Justin Ethier
+1  A: 

DEMO: http://jsbin.com/ohaxa/4/edit

$(function() {
  $('#menu li > a').click(function(e) {
  e.preventDefault();

  var my_id = $(this).attr('id'); // li a #

$.ajax({
   type: "POST",
   url: "ajax_call.php",
   data: "action=do_something&my_id=" + my_id,
   success: function(data){

     my_function(my_id); //run your outside function...

    //OR use "data" from the php echo and append it to DOM 
    // $(#ajax_call_back).append(data); 

   },
  complete: function(data){
     //on complete do something..
   },
  error: function(data){
     //this here for demo pseudo ajax handle error instead!
     my_function(my_id);

   },
 }); 

});
});

function my_function(id) {
  alert(id);
  var map = '';

  switch(id)
{
case 1:
map = id;  //map_1
  break;
case 2:
map = id;  //map_2
  break;
case 3:
map = id;  //map_3
  break;
default:
map = id;  //map_0
}

 $('#application').text('map_' + map);  

};

     <ul id="menu">
           <li><a href="#" id="1">menu_1</a></li>
           <li><a href="#" id="2">menu_2</a></li>
           <li><a href="#" id="3">menu_3</a></li>
           <li><a href="#" id="4">menu_4</a></li>
           <li><a href="#" id="5">menu_5</a></li>
        </ul>

     <div id="application"></div>
  <div id="ajax_call_back"></div>
aSeptik