Nick Green
Nick Green

Reputation: 428

PHP MySQL Dynamic Select with Ajax Call

Not sure I have worded the title correctly, so apologies if it's confusing!

Here is my problem

I have a dynamic select that is populated via data on an ajax call. I have a function that runs with a "change" of the first select. This works perfectly fine if the user manually selects the first dropdown items, however I am stuck on how to get this to run properly when they are editing.

This is what I want to achieve:

  1. Load the page based on the ProdID and populate other form fields (this is happening now, so don't need help with that ;-))
  2. Check what's pulled in from getData.php
  3. Populate the CatID select and the mark the current selection as "selected".
  4. If the user changes either of the select boxes, the function runs as it does currently.

Here is my function:

$(function() {  
  $("#topcatid").change(function() {
    $("#catid").load("getData.php?choice=" + $("#topcatid").val());
  });
});

Here is my html:

<select name="topid" id="topid" data-placeholder="Choose a category...">
  <option value="" <?php if (!(strcmp( "", ($rsProd->getColumnVal("topcatid"))))) {echo "selected=\"selected\"";} ?>>Select</option>
  <?php while(!$rsCat->atEnd()) {?>
  <option value="<?php echo($rsCats->getColumnVal(" topcatid ")); ?>"<?php if (!(strcmp($rsCat->getColumnVal("topid"), ($rsProd->getColumnVal("topid"))))) {echo "selected=\"selected\"";} ?>>
    <?php echo($rsCat->getColumnVal("catName")); ?>
  </option>
  <?php $rsCat->moveNext(); } $rsCat->moveFirst(); ?>
</select>

<select name="catid" required class="chzn-select" id="catid" style="width:350px" tabindex="2" data-placeholder="Choose a sub-category...">
  <option value="">Select from above...</option>
</select>

If the user manually changes the TopID select, the function runs, goes and gets the data and populates "catid". However this is on a page that is an edit/update page so I need the function to run as per my ideal scenario above.

Your comments and code edits would be very much appreciated.

Thanks Nick

Upvotes: 0

Views: 438

Answers (1)

Orden
Orden

Reputation: 611

For me you should do this in a calback function that will be executed just after the load.

$("#topcatid").change(function() {
    $("#catid").load("getData.php?choice=" + $("#topcatid").val(), function() {
        // Manage the old and the new catid
    });
});

You can also use the jquery.ajax function that will give you more options for functions before and after the query:

$.ajax({
  url: ""getData.php?choice=" + $("#topcatid").val()",
  beforeSend: function( xhr ) {
    // Do something
  }
})
  .done(function( data ) {
    // Do something with data
  });

Upvotes: 2

Related Questions