Declare global variable that can be used on other function

Taking into account your comments to your question, what you should do is:

  • Your AJAX function should return the attachment ID to the client
  • The frontend script should catch that response and store the attachment ID somewhere, or just populate a hidden input field in your form
  • When you submit the entire form – add the attachment ID to the POST. If you have populated a hidden input field – the attachment ID will be automatically added to POST.

Don’t forget to do some security checks when submitting the form – is the current user an author of the post with ‘attachment ID’ ID?