**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");
              }
           });
        });

```