I have the following code:

 <?php


 if ($x == 1){

 ?>
   <b>Some html...</b>
   <?php
             }
    else if ($x==2){ ?>

<b> Other html...</b>
<?php
}
?>

Now I would like to have two links below (a href) and somehow pass the variable $x (so Link1 passes x=1 and Link2 passes x=2) in order to load the relevant bit of code from if statement. I know I can pass $x using form and then test its value and load required bit of code, but I would like to do it smoothly, without reloading the page. I think that JQuery could help it, but I have no idea how to do it. Any ideas greatly appreciated.

share|improve this question

Is the content of the ‘some’/‘other’ HTML actually dependent on client-side actions at all? If you just want to switch between one and the other you can wrap each in a div and show/hide each div to switch between the two. – bobince Apr 14 '10 at 22:44
feedback

2 Answers

up vote 1 down vote accepted

Forgetting about PHP for the moment, you're looking for jQuery's .load():

<div id="container"></div>
<a href="javascript:void(0);" onclick="loadContent(1);">Load 1</a>
<a href="javascript:void(0);" onclick="loadContent(2);">Load 2</a>

<script type="text/javascript">
loadContent = function(content){
   $('#container').load(content + '.html');
}
</script>

The above code (not tested, but it's at least close) will insert the contents of 1.html, or 2.html (on the server) into the div with id="container".

There are plenty of tutorials, like the one linked in pygorex1' answer, that cover various ways of doing this.

share|improve this answer
That's quite nice. What if I would like to load Javascript as well (not to the container, but entire document)? Should it be something like document.load(content + '.js');? – Vafello Apr 14 '10 at 22:21
In that case you'd want: api.jquery.com/jQuery.getScript – timdev Apr 14 '10 at 22:44
OK,thanks a lot. One more thing - the code you provided doesnt load the file actually. When I change content + '.html' to "1.html" it does. Maybe a syntax error? – Vafello Apr 14 '10 at 22:49
Not entirely sure why that would be. I'm sure you'll figure it out. – timdev Apr 14 '10 at 23:01
Yes, missing '' in loadContent('1'). – Vafello Apr 14 '10 at 23:10
feedback

What you're looking for is AJAX - the ability to load server content using background HTTP requests in Javascript. Here's a tutorial I've found useful for implementing AJAX using JQuery:

http://articles.sitepoint.com/article/ajax-jquery

share|improve this answer
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

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