简体   繁体   中英

AJAX returns data only after first click

I have this ajax request script:

    function SendData(){
$( "#Submit" ).click(function() {
     $('#Submit').attr("disabled", true);
    $.ajax({
        type:"POST",
        url:"assets/process.php",
        data: {
            Years : $('#Years').val()
        },
        success: function(Response){
            if (Response.Status == 'Error') {                
                swal("Ups!", "Nemo' zebavaš", "error");
            } else if (Response.Status == 'Error0') {
                  swal("Ups!", "Servis 'Misterije' mogu koristiti samo rođene osobe!", "error");
            }
            else if (Response.Status == 'Error120') {
                  swal("Ups!", "Žao nam je! Niste podobni za korišćenje WEB Servisa 'Misterije'!", "error");
            } 
            else if (Response.Status == 'Success') {
                   swal("USPEŠNO!", 'Rođeni ste: '+Response.Calculated+' godine!', "success");
            }
            $('#Submit').attr("disabled", false);
        }
    });
});
}

When I load page in browser, add data to input and click on button nothing happens, but on second and all clicks after until I refresh page all working OK. How I can slove this problem?

Presumably you're calling this SendData() function when you click the button?

This function isn't doing what you think it's doing. It's not invoking the AJAX request. All this function does is attach the click handler to the button. Nothing more. Then the next time you click the button, that handler will execute.

(Not to mention that it would also again attach another click handler. So the third click would invoke the handler twice. And so on...)

There's no need to wrap all of this in a function. Instead of this:

function SendData(){
  $( "#Submit" ).click(function() {
    // your code
  });
}

just do this:

$( "#Submit" ).click(function() {
  // your code
});

This will attach the click handler, not invoke it. Any time afterward when you click the button the handler will be invoked.

At worst, you'd have to do this if the button doesn't exist yet when this code executes:

$(function () {
  $( "#Submit" ).click(function() {
    // your code
  });
});

This would wait until the document.ready event and then attach the handler.

(Note: You'll also want to remove any reference to SendData() once you've removed that function. I'm assuming you're calling it in-line from the button. But you don't need to do that when you're attaching a click handler with jQuery.)

Don't call the function

Put your code in $(document).ready function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM