Will using beforSend prevent multiple ajax calls?

By using this method multiple ajax calls can be prevented or there are any best solution?

$("#sbt").click(function (e) {
		e.preventDefault();

		var url = $(this).attr("data-url");

		var msg = $("#msg").val();

		var ser = $("#ser").val();

		$.ajax({
			url: url,
			type: "post",
			data: {
				message: msg,
				numbers: ser
			},
			cache: false,

			beforeSend: function () {
				$("#sbt").html('sending...');
				$('#sbt').attr('disabled', true);
			},
			success: function (response) {
				swal(response);
				$("#sbt").html('send');
				$('#sbt').attr('disabled', false);
			}
		});
	});

Yes that would work, although you might disable the submit button right away in the click handler… AIUI the beforeSend callback should be used for modifying (or even cancelling) the actual request.

BTW you’re performing a lot of unnecessary DOM requests here; it would be much more efficient to store the jQuery objects in a variable once and then refer to those. Also note that you can chain jQuery methods:

$('#sbt').click(function (e) {
  e.preventDefault()

  var $this = $(this)
  var url = $this.attr('data-url')
  var msg = $('#msg').val()
  var ser = $('#ser').val()

  $this
    .html('sending...')
    .attr('disabled', true)

  $.ajax({
    url: url,
    type: 'post',
    data: {
      message: msg,
      numbers: ser
    },
    cache: false,
    success: function (response) {
      swal(response)

      $this
        .html('send')
        .attr('disabled', false)
    }
  })
})
1 Like

Thats really helpful

1 Like

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