A Leonard
A Leonard

Reputation: 33

Passing a variable from within a while loop to a jquery

I have a web page that lists a number of companies from a MYSQL database, the listing just shows the name of the company. When user clicks on the company name a jquery accordion slider shows the rest of the information about that company.

When company name is clicked it also sends a request to a php script to log that a person has viewed that company's details.

My Problem

I want to send the ID for each record to the php script.

I have achieved this by including the accordion jquery code within the while loop that reads the output of the mysql query, but it generates a lot of unnecessary source code (i.e. for each company listed).

I need to include the jquery accordion code outside of the while statement.

How do I pass the id of each database record (i.e. company name) to the $.post in the jquery code, when it is outside of the while loop?

Accordion Jquery code

$(document).ready(function() {    $('div.listing> div').hide();     $('div.listing> h4').click(function() {


 $.post("/record.php", { id: "<?php echo $LM_row02[id]; ?>" } ) 

    var $nextDiv = $(this).next();
    var $visibleSiblings = $nextDiv.siblings('div:visible');

    if ($visibleSiblings.length ) {
      $visibleSiblings.slideUp('fast', function() {
        $nextDiv.slideToggle('fast');
      });
    } else {
       $nextDiv.slideToggle('fast');
    }   }); });

Any idea most welcome.

Upvotes: 1

Views: 2038

Answers (2)

Prasenjit Kumar Nag
Prasenjit Kumar Nag

Reputation: 13461

When you create the h4 element in html add a html5 data attribute like

<h4 data-companyid="<?php echo $LM_row02[id]; ?>">Company Name</h4>

Then use that companyid in your ajax call like

$.post("/record.php", { id: $(this).data('companyid') } );

Upvotes: 1

Felix Kling
Felix Kling

Reputation: 816462

When you create the HTML (I assume you do that in the loop as well), add a data-* attribute with the ID as value to the element and read that value with jQuery when the element is clicked on.

E.g. your resulting HTML will look like:

<h4 data-id="123">Some title</h4>

and your JavaScript:

$('div.listing > h4').click(function() {

    $.post("/record.php", { id: $(this).attr('data-id') }, function() {
        // ...
    }); 

});

Upvotes: 1

Related Questions