subbu royal subbu royal - 5 months ago 11
Ajax Question

how to get ajax response to trigger click

I have two forms for

buy now
and for
pincode
when I click
buynow
button sending request through
ajax
and same thing is done for
pincode
form also.

HTML


<form method="POST" action="/cart/add" id="myForm">
.....
....
<input type="button" class="buyNowBtn" id="btnBuyNow"/>
</form>

<form action="#">
<input type="text" id="pinCheck" class="pinCheck" placeholder="enter pin code" />
<button class="btn btn-info" id="pinCheckTest"> Check</button>
</form>


In the same
buynow
click event I need to
trigger
a
pincode
submit button, so I did this

(document).on('click', '#btnBuyNow', function (e) {
....
....
$("#pinCheckTest").trigger('click');
....

});


the above
trigger
event is successfully calling
pincode
click event

$('#pinCheckTest').click(function () {
$.ajax({
type: 'GET',
url: url,
success: function (output) {
if (output == 'true') {
}
else{
}
}
});


but I need to get
ajax
response back to
trigger
event so that I can do some operation is it possible?

something like

(document).on('click', '#btnBuyNow', function (e) {
....
....
$var output=$("#pinCheckTest").trigger('click');//I need to get ajax response back to this click
if(output=='true'){
......
}else{
.....
}
....

});

Answer

You can define a variable outside of both click handlers, when .trigger() is called, assign $.ajax() to variable, use .then() within first click handler to process results of $.ajax() call.

Note, included event.preventDefault() to prevent submission of <form>, as pointed out by @IsmailRBOUH

var dfd;
$(document).on('click', '#btnBuyNow', function (e) {
    e.preventDefault();
    ....
    ....
    $("#pinCheckTest").trigger('click');
    if (dfd) {
      dfd.then(function(output) {
        // do stuff with output
        console.log(output)
      })
    }
    ....

});

$('#pinCheckTest').click(function (e) {
  e.preventDefault();
  dfd = $.ajax({
    type: 'GET',
    url: url,
    success: function (output) {
      if (output == 'true') {}
      else{};
    }
  })

});

var dfd;

$("#first").click(function() {
  $("#second").trigger("click");
  if (dfd) {
    dfd.then(function(data) {
      alert(data)
    })
  }
})

$("#second").click(function() {
  // do ajax stuff
  dfd = $.when("second clicked")
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="first">first button</button>
<button id="second">second button</button>