1

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.

0

2 Answers 2

1

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() {
        // ...
    }); 

});
Sign up to request clarification or add additional context in comments.

Comments

1

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') } );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.