tags:

views:

53

answers:

3

I have a select which allows the user to select multiple option. Also on the same page is a form that will allow the user to add new keywords which will appear in the select.

My javascript sends an ajax request to a php script which either returns a success or error message which then gets added to the dom.

The ajax part of the script looks like this

$.post(
        metadataAction,
        {
            dateOfUpdate:dateOfUpdateVal,
            metadataStandardName:metadataStandardNameVal,
            metadataLanguage:metadataLanguageVal
        },
        function(responseText) {
            $('body').append(responseText);
        },
        "html"
);

I only want to repopulate the options when a new keyword has been successfully added.

Does anyone have any suggestions on the best way to achieve this?

Thanks for any help.

A: 
$.post(
        metadataAction,
        {
            dateOfUpdate:dateOfUpdateVal,
            metadataStandardName:metadataStandardNameVal,
            metadataLanguage:metadataLanguageVal
        },
        function(responseText) {
            $('body').append(responseText);
            $('#select_id').append('<option>'+responseText+'</option>');
        },
        "html"
);
Alexander.Plutov
A: 

looks a bit strange that you are appending the message to the body, but anyhow..

return a JSON string representing an object with two properties:success[bool],message[string]
don't have experience with php, but if the response will be of type JSON, then jQuery(1.4.2) will parse it as an object and then in your success function:

function(data)
{
  if(data.success)
  {
    //append the item
  }
  //show the message
  $(msgCont).text(data.message)
}

note that you will always get to the success function if the response status code is 200(or any other 2XX)

Avi Pinto
Thanks for your suggestion. The response that gets appended is a fixed positon div which then get's faded out after a few seconds so appending it to the body makes sense. I like the idea of returning a json object. I could then also include the updated options to update the select. Thanks
if a user appends a lot of items, you can have the fixed positioned div already hidden on page, and just change it's text and hide it away after each operation. this is a more clean way to handle your case since you don't want to return a json string that also contains raw html tags(+ more bytes to transfer.. but this is really beeing picky ;-))
Avi Pinto
A: 

To solve this I have the php script output a json object.

If the addition was successful the json has three properties.

Success, message and newSelect. I check for the occurrence of success in my ajax response. If it is present I use the jquery method replaceWith() to update the select currently in the form with the one returned.

Thanks for the help.