$.post is sending data erratically

Hi
I am curious as to why when I post to php backend, it sends the data several times. I have done a screen grab to show the problem and would appreciate some help as to where I am going wrong. Many thanks.

$(function() {
  validate();
  $('#adr1, #adr2, #town, #postcode').on('keyup blur', validate);
});
  
function validate() {
  if ($('#adr1').val().length > 0 && $('#adr2').val().length > 0 &&
    $('#town').val().length > 0 && $('#postcode').val().length > 0) {
    var addr1 = $('#adr1').val();
    var addr2 = $('#adr2').val();
    var addr3 = $('#adr3').val();
    var town = $('#town').val();
    var postcode = $('#postcode').val();
    var qString = 'addr1=' + addr1 + '&addr2=' + addr2 + '&addr3=' + addr3 + '&town=' + town +
      '&postcode=' + postcode;
    $('.altFieldError').html('');
    $('.altFieldError').html(
        'All marked fields correct. Please leave this form open until you have returned your box.')
      .css('color', 'green');
    $(".boxdest").prop("disabled", false);
    $('.permaddr').show();
    $("#permaddr").on('click', function() {
      $.post('/lsorg/users/Loadpermaddr.php', qString, function(data) {
        $(".fieldError").html(data);
      });
    });
  }
}

You define the AJAX call each time the validation runs. I.e. if the validation runs four times, you define four separate click handlers and when the click triggers, four handlers are called and hence four requests are made.

Thanks for reply. Could I please ask, what is the correct way to amend my code. Thanks

omit the click handler and run the AJAX call immediately when you validate. or–the other way round–only validate when that special button is pressed.

Note: it might not be the best idea to have an ID and class of the same name, confusion is easily achieved then.

I would have actually suggested a couple of different options:
1: Move the bind into the document.ready function above.
2: Abort validate() if the button is already enabled. This actually is probably the better solution, because validate() should have an else to that if that disables the button and hides it again.

Dormilich I cannot omit the handler because the user may not want to add the address to the database. Thanks

m_hutley I have tried various options based on your post but keep getting the same result. Would it be possible you can give me an example in code that I can follow. Many thanks

Then only validate if there is a value.

ok thanks

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.