views:

72

answers:

3

I'm new to Javascript/Jquery and struggling with a certain issue.

In the process of adding a job to a database, the users have an option to update the contents of dropdown lists with new options. Adding the new options is handled through a greybox which posts data with PHP through to the database.

After adding the new option it does not display in the dropdown list. As such they need to be able to click a button to refresh the contents of the dropdown list. Has anyone accomplished this before, and can show me some sample source code? Or is there a more elegant solution fo this issue?

I've been researching pretty much non-stop and cannot find a solution, any help is appreciated. n.n

Edit:

<script type="text/javascript">  
function getbrands(){  
   new Ajax.Request('ajax/brand.php',{  
        method: 'get',  
        onSuccess: function(transport){  
            var response = transport.responseText;  
            $("brand").update(response);  
        }  
    });  
}  

It works... sometimes. Highly unstable. Also has a bad habit of conflicting with other scripts on the page. (mainly the greybox)

Any suggestions will be taken on board at this stage. :X

A: 

Use ajax to post the data to your php file, echo the html for the new dropdown back to the javascript, and then use jquery to put in the new contents. http://api.jquery.com/jQuery.ajax/

sgrif
A: 

no sample code but I guess it goes like this

  1. after the posting, create a callback that updates the DOM, particularly the options for the select box

maybe it goes something like this in code in jquery:

$.ajax({
  method: 'POST',
  data : $('#newjobfield').val(),
  dataType: 'text'
  success : function(data){
    $('#selectbox').append('<option value="' + data + '">' + data + '</option>')
  }
});

in php

function getNew()
{
 if ($_POST)
 {
    // update database 
    // then echo the record's 'name' (or whatever field you have in there)
    echo $newInsertedJobName;
  }
  die();
}

Now this code sucks, so just tell me if something does not work (I haven't tested it, cuz I made it a few minutes ago, while at work :P)

Ygam
A: 

Assuming your using jQuery, you could do the following..

//in a php file that your gonna use to fetch new dropdown values
<?php //pathToPhpFile.php
    header("Content-Type: application/json");

    //here you'd perform a database query 
    //heres a dummy dataset
    $data = array(  
        array( "id" => "dropdown1", "label" => "Dropdown #1"), 
        array( "id" => "dropdown2", "label" => "Dropdown #2"), 
    );

    echo json_encode( $data );
    exit;
?>

javascript code: sould be wrapped in $(document).ready( function(){ }); block to ensure the button is ready to accept events

//attach refresh event to button 
$("#refeshButtonId").click( function() {

    var dropdown = $('#idOfTheDropdown');

    //fetch the key/values pairs from the php script
    jQuery.getJSON( "pathToPhpFile.php", function( data ) {

        //empty out the existing options
        dropdown.empty();

        //append the values to the drop down
        jQuery.each( data, function(i, v) {
            dropdown.append( $('<option value="'+ data[i].id +'">'+data[i].label+'</option>');
        });
    });

});

refined code :)

<script type="text/javascript">  
    $(document).ready( function(){

        $("#refeshButtonId").click( function() {

            //fetch the key/values pairs from the php script
            jQuery.getJSON( "pathToPhpFile.php", function( data ) {

                 var dropdown = $('#idOfTheDropdown');

                //empty out the existing options
                dropdown.empty();

                //append the values to the drop down
                jQuery.each( data, function(i, v) {
                    dropdown.append( $('<option value="'+ i +'">'+ v +'</option>') );
                });
            });

        });    
    });
</script>
RueTheWhirled
That looks hot. :] I'm going to try that now. n.n
Linnay
RueTheWhirled
I'm a bit new to all this... but from what I understand I attach the #refreshButtonID() function to an onclick on the hyperlink?The SQL query in the php file returns an array like the following - Array([id] => brand [id] => brand ....etc )Desperately trying to come up to speed with Jquery, so your help is greatly appreciated!
Linnay
Also, the code inspector says that there is an error in the row ~ "dropdown.append(...etc). I can't track it down. I copied yours word for word.
Linnay
AHh yeah my bad, theres a missing ) near the end of the dropdown.append line so it should be dropdown.append( $('<option value="'+ data[i].id +'">'+data[i].label+'</option>') );
RueTheWhirled
Still no luck at this point. I'll continue debugging, if you have any pointers glad to receive!
Linnay
Hmm the $("#refeshButtonId").click link is attaching an onclick event to the element on the page with an id attribute of "refeshButtonId" (note the element id shouldnt have #). So you need to give the element that you want to perform the refresh each time its click an id of "refreshButtonId" eg <a id="refreshButtonId" href="#">Refresh</a>
RueTheWhirled
if your php array is returned in the form you stated you would need to use dropdown.append( $('<option value="'+ i +'">'+ v +'</option>') );
RueTheWhirled
I edited post to show a code block with script tags that you should be able to copy and paste in the head of the document:To things to note are the #refreshButtonId and #idOfTheDropdown these should be the id attributes of their respective elements, the refresh link and dropdown list
RueTheWhirled
This is looking really good. The only issue I'm experiencing now is that the options aren't being placed inside the existing dropdown list. Will update if I fix this myself. :)
Linnay
Have noted that dropdown.empty() is actually deleting the dropdown box. Giving the append nothing to apend to.
Linnay
empty() removes all child elements so its possible you have the id on an element wrapping around the select element?. should be <select id="idOfTheDropdown"><options>...</options></select>
RueTheWhirled
Yessssss. :DI am your number one fan. Thanks for making me infinitely smarter with jquery and webdev in general. I'll be able to make use of this knowledge in heaps of places. Thanks again!
Linnay
Hey no problem, least I can do to help out a fellow kiwi ;)
RueTheWhirled