user1648449
user1648449

Reputation: 97

jquery and ajax to load php content

I have a <div class="container"> which will display content from separate php files located in a content folder, that are linked to individual <a> tags presented in a <ul>. Once a link from the list is clicked a loading graphic(processing...)class="process" will display in the container and the php file called upon will display.

HTML(watered down):

<div class="container"></div>

<ul id="yourIdeas">
  <li><a href="one">one</a></li> <!--content/one.php-->
  <li><a href="two">two</a></li>
  <li><a href="three">three</a></li>
  <li><a href="four">four</a></li>
</ul>

the container/loading graphic, styling etc... is all fine.

JQUERY:

(function() {
  var typ = {
  loading: $('<div />', { class: 'process' }),
  area: $('.container')
  }

  var file = $('ul#yourIdeas li a').attr('href');
  var thePage = $('content/' + file + '.php');

  $('ul#yourIdeas li a').on('click', function() {
    $.ajax({
        url: 'thePage',
        beforeSend: function() {
            typ.area.append(typ.loading);
        },
        success: function(data) {
            typ.area.html(data);
        }
    });
  });
});

I cannot get the Jquery/Ajax to perform this task; When a ul#yourIdeas li a is clicked, it grabs the href and associates it to the designated php file, which then loads the 'processing...' in the container, followed by displaying the content of the chosen php file in the container.

I can get it to work if i specifically ask for each link separately;

CODE:

var typ = {
  loading: $('<div />', { class: 'process' }),
  area: $('.container')
}

$('ul#yourIdeas li a#two').on('click', function() {
  $.ajax({
    url: 'content/two.php',
    beforeSend: function() {
        typ.area.append(typ.loading);
    },
    success: function(data) {
        typ.area.html(data);
    }
  });
});

But i would like to have the one script to encompass all links and files, if possible.

Thanks in advance for any help.

Upvotes: 0

Views: 3609

Answers (1)

user1823761
user1823761

Reputation:

You must move file and thePage variables inside your click function:

(function() {
  var typ = {
    loading: $('<div />', { class: 'process' }),
    area: $('.container')
  };

  $('ul#yourIdeas li a').on('click', function(e) {
    e.preventDefault();
    var file = $(this).attr('href');
    var thePage = 'content/' + file + '.php';

    $.ajax({
        url: thePage,
        beforeSend: function() {
            typ.area.append(typ.loading);
        },
        success: function(data) {
            typ.area.html(data);
        }
    });
  });
});

Upvotes: 3

Related Questions