views:

140

answers:

3

Please look at this code:

$('ul#navigation li ul li>a').click(function(){
    var active = $(this).text();
    $('#artcontent p').empty();
    $.ajax({
        type: 'POST',
        url: 'homepage/readarticle',
        data: $(active).serialize(),
        success: function(databack){
           $('#loading').fadeOut('normal');
           $('#artcontent').append(databack);
        }
    })
});


function readarticle()
{
    $articlename = $this->input->post('active');
    $output = $this->articles->displayby_name($articlename);

    if($output){
        $data['article'] = $output;
    }
    $this->load->view('loadarticle',$data);
}

This is the function that is on the server.

I have a ul li a that are children of parent ul navigation and li. What I am trying to do is to load an article page. This works but it reads the database and loads all the articles in my database instead of the one identified by active. I would like to know what I am doing wrong or is there a better way to go about this?

OK, the 'homepage/readarticle' is the 'controller/method' in my CodeIgniter controller which loads the view that renders the article.

As for the serialize line, I actually put in active without the serialize and could catch the text of the link with Firebug using the usual console.log(). Like I said, it reads the articles all right, but it reads all the articles from my database instead of fetching the one whose title is equal to the name in the active variable (that would be the text of the link so, for example, <a href="#">see this</a>. See this is the text.)

OK, let me add the code that handles this also from the model which is the last piece in:

<?php
    function displayby_name($name) { $this->db->select("articletitle,articlebody,articleauthor");
    $this->db->from('articles'); $this->db->where('articletitle',$name);
    $Q = $this->db->get(); if($Q->num_rows() > 0){ $text = $Q->result_array(); }
    echo $this->db->last_query();
    return $text; }
?>

Any thoughts still?

+1  A: 

I'd start with installing Firebug extension for firefox, than debugging your's AJAX requests (Firebug let's you trace all the details like what data is actually sent, what was the response code & body, etc). I can't help you anymore since I don't know the structure of the HTML document... especially the part: var active = $(this).text(); ... data: $(active).serialize() I don't tkink the line data: $(active).serialize() is correct ... can you explain what you really wanted to do? also posting a link could help ... `

migajek
+1  A: 

$(active).serialize() will result in an empty string. You probably want remove the data: $(active).serialize(), line and do something like url: 'homepage/readarticle/' + encodeURIComponent(active),, depending on what your server-side application expects.

Edit:

Based on the server-side code you just added to your question, your code should work if you replace data: $(active).serialize(), with data: {active: active},.

Another Edit:

Well, I've taken the liberty to attempt to recreate your setup. And my code is working fine (as far as I've understood your intended behaviour).

The following is my CodeIgniter application. It might look like a lot of code but it's only ~120 lines in total, so bare with me. Read through it and try to run it if you can. If it doesn't help, add a comment and I can help you from there since I have the setup now.

+---controllers
|       homepage.php
|
+---models
|       articles.php
|
\---views
        homepage.php
        loadarticle.php
controllers\homepage.php:
<?php
class Homepage extends Controller {
  function Homepage()
  {
    parent::Controller();   
    $this->load->model('articles');
  }

  function index()
  {
    $output = $this->articles->display_all();

    $data['articles'] = $output;
    $this->load->view('homepage', $data);
  }

  function readarticle()
  {
    $articlename = $this->input->post('active');
    $output = $this->articles->displayby_name($articlename);

    if($output){
      $data['articles'] = $output;
    }
    $this->load->view('loadarticle', $data);
  }
}
models\articles.php
<?php
class Articles extends Model {
    function Articles()
    {
     parent::Model(); 
    }

  function display_all() {
    $this->db->select("articletitle"); 
    $this->db->from('articles');
    $Q = $this->db->get();
    $results = array();
    if ($Q->num_rows() > 0) {
      $results = $Q->result_array();
    } 
    return $results;
  }

  function displayby_name($name) {
    $this->db->select("articletitle, articlebody, articleauthor"); 
    $this->db->from('articles');
    $this->db->where('articletitle', $name); 
    $Q = $this->db->get();
    if ($Q->num_rows() > 0) {
      $text = $Q->result_array();
    } 
    return $text;
  }
}
views\homepage.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head>
    <title>Homepage</title>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"&gt;&lt;/script&gt;
    <style type="text/css" media="screen">
      #navigation { float: left; padding: 1em; }
      #loading { 
        display: block; position: absolute;
        top: 0; left: 50%; display: none; width: 8em; margin-left: -4em;
      }
      #artcontent { padding: 2em; }
    </style>
  </head>
  <body>
    <ul id="navigation">
      <li>
        <span>Articles:</span>
        <ul>
          <?php foreach ($articles as $article): ?>
          <li><a href="#"><?php echo $article['articletitle']; ?></a></li>
          <?php endforeach; ?>
        </ul>
      </li>
    </ul>
    <span id="loading">Loading...</span>
    <div id="artcontent"><p></p></div>
    <script>
      $('ul#navigation li ul li>a').click(function(){
        var active = $(this).text();
        $('#artcontent').empty();
        $('#loading').show();
        $.ajax({
          type: 'POST',
          url: 'homepage/readarticle',
          data: {active: active},
          success: function(databack){
            $('#loading').fadeOut('normal');
            $('#artcontent').append(databack);
          }  
        });
        return false;
      });
    </script>
  </body>
</html>
views\loadarticle.php
<?php foreach ($articles as $article): ?>
<h2><?php echo $article['articletitle']; ?></h2>
by <span><?php echo $article['articleauthor']; ?></span>
<p><?php echo $article['articlebody']; ?></p>
<?php endforeach; ?>
MySQL structure and sample data
CREATE TABLE IF NOT EXISTS `articles` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `articletitle` varchar(200) NOT NULL,
  `articlebody` text NOT NULL,
  `articleauthor` varchar(200) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;

INSERT INTO `articles` (`id`, `articletitle`, `articlebody`, `articleauthor`)
VALUES
(1, 'foo', 'body foo body', 'author foo author'),
(2, 'bar', 'body bar body', 'author bar author'),
(3, 'baz', 'body baz body', 'author baz author');
brianpeiris
I just did brian and WHat happens is this, it does draw the text for the article but it draws all the articles in the database and not the one whose title is the same as the text picked from the link.
Eagletrophy
So you're saying the change I suggested had no effect at all? Are you sure your `displayby_name` method is working correctly? Because the jQuery code looks fine to me.
brianpeiris
ok let me add the code that handles this also from the model which is the last piece in this chain(i think?)function displayby_name($name){ $this->db->select("articletitle,articlebody,articleauthor"); $this->db->from('articles'); $this->db->where('articletitle',$name); $Q = $this->db->get(); if($Q->num_rows() > 0){ $text = $Q->result_array(); } echo $this->db->last_query(); return $text; }
Eagletrophy
A: 

It would help if you also post the controller code in your app (the code that handles the request). Is it expecting a POST request with variables, or is it expecting a GET request to a url that includes the article id?

As a previous poster has mentioned, you are serialising a string; It is common, and more meaningful to serialise an associative array (dict, object, hash... choose your name). For example, one would expect to serialise something similar to {'articleid':1}.

Rob Cowie