0

I am recently working with adobe InDesign extension's and in that I want to upload an xml file to my server using jquery ajax POST call, so for that, I have to read the XML file from the file system store it into a variable and then pass that variable as body into the post request here is my code

function uploadDocument( onSuccess, onError, onComplete) {
  var token = localStorage.getItem("token");
  writeLogs("uploadDocument function \n " + token );

  var result = window.cep.fs.readFile("/Users/mac41589/Downloads/test-xmls/post.xml");
  var xmlStr = "";

  if(result.err == 0){
    writeLogs("file read complete " + ' ' + result.data)
    xmlStr = result.data;
    alert("type of xmlStr new" + ' ' + typeof(xmlStr));

    $.ajax({
      url : "https://xyz.abc.com/capi-demo/article?customerNumber=888",
      method: "POST",
      data: xmlStr,
      beforeSend : function(xhr) {
        xhr.setRequestHeader("Authorization", "Bearer " + token);
        xhr.setRequestHeader("Content-Type", "application/xml");
      },
      complete: function(xhr) {
          alert("on complete with code" + ' ' + xhr.status + ' ' + xhr.statusText );
          //onComplete();
      },
      success : function(response) { 
          alert("file upload success with response : " + ' ' +response);
      },
      error : function(jqXHR, textStatus, errorThrown) {
          alert('file upload fail with error -- ' + jqXHR.status + ' textStatus: ' + textStatus + ' errorThrown: ' + errorThrown);
      }
    });
  }
}

and here exact is the XML file I want to send :

<document xmlns="http://pubpress.com/document">
   <properties>
       <magazineNumber>95100</magazineNumber>
   </properties>
   <article>
       <pam:message xmlns:pam="http://xax.org/namespaces/pam/2.0/" xmlns:ppc="http://axa.com/content" xml:base="/article/content/39992.xml">
   <pam:article>
       <head xmlns="http://www.w3.org/1999/xhtml">
           <dc:identifier xmlns:dc="http://purl.org/dc/elements/1.1/">888-create.xml</dc:identifier>
           <pam:status/>

       </head>
       <body xmlns="http://www.w3.org/1999/xhtml"><p>Sample body text</p></body>
   </pam:article>
</pam:message>
   </article>
</document>

so whenever I execute this POST call it returns 404 error Not Found but when I send the wrong(undesired to server) XML file then it shows 400 bad request. the wrong xml (undesired to server) is as follows :

<?xml version="1.0" encoding="UTF-8"?>
<variable type="NameValuePair[]">
   <item type="NameValuePair">
      <name type="String"><![CDATA[No Data Found]]></name>
      <value type="String"><![CDATA[95990070]]></value>
   </item>
</variable>

i am not able to find why this POST call is returning 404 from ajax call where the same call with same parameters runs well in PostMan. thank you in advance.. Any help on this will be highly appreciated.

RobC
  • 22,977
  • 20
  • 73
  • 80

1 Answers1

0

Aside from making sure the url accepts xml posted, you should add the ajax option for contentType: "text/xml", to your configuration.

Here I get stuff out of the global scope with myApp (not part of question but to me it is better in practice to do so). I refactored to the promise form of .ajax() again because I like it better and I could then replace the functions there with some name spaced error handler for all my ajax for example.(is that what those passed things are, callbacks?)

I also saw a couple of bugs like typeof() in there. This assumes ES6.

// create a namespace object
var myApp = myApp || {
  url: "https://xyz.abc.com/capi-demo/article?customerNumber=888"
};
// borrow some code from https://stackoverflow.com/a/23861977/125981
myApp.isXHR = function(maybe) {
  if (!maybe) {
    return false;
  }
  if (!('readyState' in maybe)) {
    return false;
  }
  if (!('responseText' in maybe)) {
    return false;
  }
  if (!('status' in maybe)) {
    return false;
  }
  if (!('statusText' in maybe)) {
    return false;
  }
  return true;
};

myApp.writeLogs = function(logmessage) {
  // just to act as placeholder for the answer
};

myApp.processMessage = function(message, silent = true) {
  if (silent) {
    alert(message);
  } else { // or
    console.log(message);
    // or something else like send to server via ajax to log or some such
  }
};

myApp.getDocumentContent = function() {

  let result = window.cep.fs.readFile("/Users/mac41589/Downloads/test-xmls/post.xml");
  //var xmlStr = "";
  let getResult = {
    xmlStr: "",
    hasContent: false,
    error: result.err
  };
  if (result.err == 0) {
    myApp.writeLogs("file read complete " + ' ' + result.data)
    myApp.processMessage("type of xmlStr new" + ' ' + (typeof result.data));
    getResult.xmlStr = result.data;
    getResult.hasContent = true;
  }
  return getResult;
};

myApp.sendContent = function(contentObj) {
  let token = localStorage.getItem("token");
  myApp.writeLogs("uploadDocument function \n " + token);
  myApp.writeLogs("file read complete " + contentObj.xmlStr);
  myApp.processMessage("type of xmlStr new " + (typeof contentObj.xmlStr));

  $.ajax({
      url: myApp.url,
      method: "POST",
      data: contentObj.xmlStr,
      contentType: "text/xml",
      beforeSend: function(xhr, settings) {
        xhr.setRequestHeader("Authorization", "Bearer " + token);
        xhr.setRequestHeader("Content-Type", "application/xml");
      }
    })
    .always(function(dataOrJqXHR, textStatus, jqXHROrErrorThrown) {
      // determine which parameter is which when the .always() is called
      let my_jqXHR = null;
      let data = null;
      let errorThrown = null;
      if (myApp.isXHR(dataOrJqXHR)) {
        my_jqXHR = dataOrJqXHR;
        errorThrown = jqXHROrErrorThrown;
      }
      if (myApp.isXHR(jqXHROrErrorThrown)) {
        my_jqXHR = jqXHROrErrorThrown;
        data = dataOrJqXHR;
      }
      let status = my_jqXHR.status;
      // do something with status
      myApp.processMessage("on complete with code" + ' ' + status + ' ' + errorThrown);
    })
    .done(function(data, textStatus, jqXHR) {
      myApp.processMessage("file upload success with response : " + ' ' + textStatus + ' ' + data);
    })
    .fail(function(jqXHR, textStatus, errorThrown) {
      myApp.processMessage('file upload fail with error -- ' + jqXHR.status + ' textStatus: ' + textStatus + ' errorThrown: ' + errorThrown);
    })
    .then(function(data, textStatus, jqXHR) {
      myApp.processMessage("file upload success with response : " + ' ' + textStatus + ' ' + data);
    }, function(jqXHR, textStatus, errorThrown) {
      myApp.processMessage('file upload fail with error -- ' + jqXHR.status + ' textStatus: ' + textStatus + ' errorThrown: ' + errorThrown);
    });
};

myApp.uploadDocument = function(onSuccess, onError, onComplete) {
  let contentObj = myApp.getDocumentContent();

  if (contentObj.hasContent && contentObj.err == 0) {
    myApp.sendContent(contentObj);
  } else {
    myApp.processMessage("No Content" + contentObj.err);
  }
};
// call it, not sure what these passed thing are, and seem unused
myApp.uploadDocument(onSuccess, onError, onComplete);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100