CodeIgniter Forums
CodeIgniter and AJAX - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived General Discussion (https://forum.codeigniter.com/forumdisplay.php?fid=21)
+--- Thread: CodeIgniter and AJAX (/showthread.php?tid=57157)



CodeIgniter and AJAX - El Forum - 02-21-2013

[eluser]julian0008[/eluser]
Hi guys. im just new in CodeIgniter but quite knowledgeable in Web Development. Im just having trouble on how I can change the contents of a certain <div> using jQuery depending on what I click on my horizontal menu wihout refreshing the whole page.

For example, if I click the Home tab in my horizontal menu, the div below will change. And when i click another option on the menu, it would again change into another without reloading the page. Below is my jQuery code but it doesnt work. #changer is the dynamic div and v-menu is the menu bar.

Code:
$(document).ready(function()
{
$('#changer').html("&lt;?php $this->load->view('tutorial-contents/page1'); ?&gt;");

$('ul#v-menu li a').click(function()
{
  var page = $(this).attr('href')
  $('#changer').html("&lt;?php $this->load->view('tutorial-contents/" + page + "'); ?&gt;");
  return false;
});
});


I really need help on this. Any reply would be gladly appreciated and sorry for my poor english.


CodeIgniter and AJAX - El Forum - 02-21-2013

[eluser]John Murowaniecki[/eluser]
First you need to know that PHP doesn't executes directly from javascript, so your
Code:
$('#changer').html("&lt;?php $this->load->view('tutorial-contents/page1'); ?&gt;");
will only work if this javascript block is on some .php file BUT you need understand that if your view use <tags>, "some 'quotes' or double-quotes" or other not so special chars your script will not work.

I recomend you learn first how PHP works, then MVC, and then CodeIgniter and, before you start to build your Ajax site, build a structure without Ajax. After you finish your Ajax-less site you'll need to learn how jQuery handles events (so you'll learn about events.preventDefault() and other methods to stop propagation, etc, and this will enable you to perform server queries from your anchors - links - without reloads) can change it to operate as you wish.

If you need an exemple of Ajax querying

Code:
$('a.ajax').click(function (e) {
    e.preventDefault();
    $.ajax({
        url: $(this).attr('href')
    }).done(function (data) {
        $('body').html(data);
    });
});

I hope it helps you.


CodeIgniter and AJAX - El Forum - 02-21-2013

[eluser]julian0008[/eluser]
Thank you sir John. I'll definitely learn it first. Sorry for the wrong code, its just my first time to try it though and just proved to myself that Im a real newbie in CI. Thanks again. Smile