user6549711 user6549711 - 5 months ago 20
jQuery Question

jQuery : How can I call $.ajax when a particular condition is met in the nested ajax calls scenario?

Updated Question with Code

I have a situation where I am calling two nested ajax calls one after another. The first ajax call submits a form without the attachment. The result of the first ajax call will create a

requestId
and using second ajax call I have to attach multiple attachments to the created
requestId
.

The result of below code, both first and second ajax calls are being called
N
times of attachment. For ex:- If there are 3 attachments,
createRequestId
ajax call(first ajax call) called 3 times which creates 3
requestId
s. My issue is,
createRequestId
ajax call needs to be called only one time (first time) and during rest of the loop, only the second ajax call should be called. How can I achieve this in the below code?


Current situation


RequestId 1,Attachment 1
RequestId 2,Attachment 2
RequestId 3, Attachment 3



Expected output

RequestId 1, Attachment 1, Attachment 2, Attachment 3


//loop through number of attachments in the form
$("#myDiv").find("input[type=file]").each(function(index,obj) {
var fObj = $(obj),
fName = fObj.attr("name"),
fileDetail = document.getElementById(fName).files[0];
//FileSize Validation
if(fileDetail !=undefined && fileDetail !=null)
{
if(fileDetail.size > 5*Math.pow(1024,2))

{
alert("Please upload the attachment which is less than 5 MB");
return false
}
}

$.ajax({ //First Ajax Call
url: 'http://..../createRequestId'
type:'POST'
data: stringify(formData)
success: function(resObj){
$("#showResponseArea span").removeClass("hide");
$("#showResponseArea span").removeClass("alert-success");
var requestId = resObj.requestId;

if(requestId>1 && fileDetail !=undefined && fileDetail !=null) {
$.ajax({ //Second Ajax Call
url: 'http://..../doAttach?fileName=' + fileDetail.name +
'&requestId=' +requestId,
type:'POST',
data: fileDetail,
success: function(resObj){
alert("Attachment Successful");

}
error : function(data) {
alert("Failed with the attachment");
}
});
}
},
error: funciton(resObj) {
alert("Some Error Occured");
}
});
});

Answer

I think your loop is simply in the wrong place. As it is, you're iterating files and making both AJAX calls once. Edit: I now show the appropriate place to do extra validations before the first AJAX call. The actual validation was not part of the question and is not included, but you can refer to javascript file upload size validation.

var fileSizesValid = true;
$("#myDiv").find("input[type=file]").each(function(index, obj) {
  // First loop checks file size, and if any file is > 5MB, set fileSizesValid to false
});

if (fileSizesValid) {
  $.ajax({ //First Ajax Call
    url: 'http://..../createRequestId',
    type: 'POST',
    data: stringify(formData),
    success: function(resObj) {
      var fObj = $(obj),
        fName = fObj.attr("name"),
        fileDetail = document.getElementById(fName).files[0];
      //loop through number of attachments in the form
      $("#myDiv").find("input[type=file]").each(function(index, obj) {

        $("#showResponseArea span").removeClass("hide");
        $("#showResponseArea span").removeClass("alert-success");
        var requestId = resObj.requestId;

        if (requestId > 1 && fileDetail != undefined && fileDetail != null) {
          $.ajax({ //Second Ajax Call
            url: 'http://..../doAttach?fileName=' + fileDetail.name +
              '&requestId=' + requestId,
            type: 'POST',
            data: fileDetail,
            success: function(resObj) {
              alert("Attachment Successful");
            },
            error: function(data) {
              alert("Failed with the attachment");
            }
          });
        }
      })
    },
    error: function(resObj) {
      alert("Some Error Occured");
    }
  });
}

As a side note, take care where you place your braces. In JavaScript your braces should always be at the end of the line, not the start. This is not a style preference thing as it is most languages, but an actual requirement thanks to semicolon insertion.