tags:

views:

159

answers:

1

I have to encode a domain name (IDNA) for a particular registrar using accents.

I have a simple input field :

<input type="text" id="idndomain" name="sld[0]" size="40" />

My jQuery function

$(document).ready(function() { 
 $('#domainform').submit(function(){
  $.getJSON("includes/idna/idna.php", {
   domain: $("input#idndomain").val()
  }, function(data){
   $("div#result").html($('<b>' + data.encoded + '</b>'));
   $('#idndomain').val(data.encoded);
  });
  return true;
 });
});

So i'm sending a query to idna.php which encodes the domain name and returns a json array :

{"encoded":"xn--caf-dma.ch"}

Problem is that the form is being submited with the 'original' value, not the value returned by the json query.

Question is : how to 'wait' for json result first, replace the input field with the encoded string and them submit ?

+2  A: 

Try binding to the submit button instead of the form, and explicitly invoke the form's submit handler within the json call's success callback:

    $(document).ready(function() { 
            $('#submitButton').click(function(){

                    // maybe disable the submit button once clicked?
                    $(this).attr('disabled', true); 
                    $.getJSON("includes/idna/idna.php", {
                            domain: $("input#idndomain").val()
                    }, function(data){
                            $("div#result").html($('<b>' + data.encoded + '</b>'));
                            $('#idndomain').val(data.encoded);
                            // now submit the form
                            $('#domainform').submit();
                    });
                    return false;
            });
    });
karim79
Be sure to allow for more than just a click, some people might submit a form with return or tab>space/tab>return.
dylanfm
why not bind with the $("selector").live("click", function(){}); ?Always found it better just in case :)
Sam
I don't think there's enough context to recommend using `live`, it's really only needed if the submit button gets replaced (which I can't see happening based on the question)
karim79
Did not understand the 'live' thing, but the first answer just worked fine. Many thanks to all.
Disco