0

My form details are below:

<form id="CreateAttachmentForm" method="post"  enctype="multipart/form-data"  action="../../uploadFile" >

My file is defined as below:

<input type="file" id="fileupload1" name="fileupload1" accept="image/*,application/pdf"    "/>

My custom button related code is below:

<contact:contactbutton
        id="printButton"
        style="position:relative; width:90px; top:27px; height:30px; left:160px;"
        textTop="7px"
        defaultButton="false"
        tabindex=""
        accesskey="C"
        onClickEx="createAttachmentRequest();"
        onfocus="if(event.altKey){click();}">
            <u>C</u>reate
</contact:contactbutton>

I have the following function which is called upon clicking a custom button:

function createAttachmentRequest(){
alert("ONE");
$("#CreateAttachmentForm").trigger("submit", function() {
var formData = new FormData($(this)[0]);
alert("TWO");

$.ajax({
url: 'http://HDDT0214:8080/pqawdTestWebApp/uploadFile',
    type: 'POST',
    data: formData,
    async: false,
    success: function (data) {
        alert("test");
        alert(data)
    },
            cache: false,
    contentType: false,
    processData: false
});

return false;

});

The above Jquery code is calling my rest service successfully and the response is also returned by the rest service. Surprisingly the success function is not getting invoked/called even there is response from rest service. Is there something wrong with my code?

Ashok.N
  • 1,327
  • 9
  • 29
  • 64
  • 2
    what is the status code being returned by the service? If it's not 200 (OK), then the "success" callback won't fire. Instead the "error" callback would fire, but you haven't defined one. – ADyson Apr 12 '17 at 14:51
  • Hope you will get solution here https://stackoverflow.com/questions/5150571/javascript-function-that-returns-ajax-call-data/5150650#5150650 – Erukulla Nithish Apr 12 '17 at 14:51
  • 1
    Why are you triggering a submit ? Why not just have the event that calls createAttachmentRequest be a submit button click and have `$("#CreateAttachmentForm").on("submit", function(e) { e.preventDefault(); ... ` and remove the return false? Also async:false makes this look like an X/Y problem – mplungjan Apr 12 '17 at 14:53
  • @ADyson, Thanks for the response. The response code is `201`. – Ashok.N Apr 12 '17 at 14:55
  • @Ashok.N this could be useful to you: http://stackoverflow.com/questions/12410051/how-to-handle-ajax-201 – Hulothe Apr 12 '17 at 15:00
  • As far as I understand it, when receiving a 201 status code jQuery expects content in the response. If there is no content (or of the wrong content type) returned with the 201, then the error callback is invoked. Does your request return any content? If so, what type (e.g. plain text, JSON, HTML)? – ADyson Apr 12 '17 at 15:00
  • @mplungjan, The piece of code that you suggested is not working. I don't know the reason, but I have already tried it. – Ashok.N Apr 12 '17 at 15:01
  • @Ashok.N it would be helpful to define "not working" in more detail. When you tried it, is the CreateAttachmentForm element loaded/created after the event handler code runs, by any chance? If so, you must either ensure the handler code runs _after_ the element is rendered, or if that's not possible, use delegated event handling. – ADyson Apr 12 '17 at 15:05
  • @ADyson, //Does your request return any content? // Yes, it just returns plain text some thing like `2016-01-09-12.44.19.19283O01`. CreateAttachmentForm element is loaded during the startup only. – Ashok.N Apr 12 '17 at 15:11
  • I have also added the error function now.But this function is also not getting called. `error: function (data) { alert("test"); alert(data) },` – Ashok.N Apr 12 '17 at 15:12
  • in that case there's no reason why mplugjan's suggestion shouldn't work, as long as the `$("#CreateAttachmentForm").on("submit", function(e) { e.preventDefault();` runs after the element is created - either in a `$(document.ready() { ... });` wrapper, or just by putting the JS code lower down the page than the HTML. – ADyson Apr 12 '17 at 15:12
  • @ADyson, Okay. But that's not my current problem. I can take a look at later point of time. My main concern is why the success/error functions are not called? – Ashok.N Apr 12 '17 at 15:14
  • if it's really true that neither error or success is being called, then something must be failing before it can reach that stage. An ajax call must trigger one or other of those callbacks, if it returns and the thread is still running. Is there any other error or warning message in your browser's console? P.S. You can remove "cache:false" from your options. As per the jQuery docs it has no effect for requests that are not GET or HEAD. "async:false" is also redundant because that's the default value anyway. – ADyson Apr 12 '17 at 15:15
  • @ADyson, I could see that the response is being displayed on the browser. But the weird thing is that success/ error function is not called. – Ashok.N Apr 12 '17 at 15:18
  • 1
    Do you see nothing on the page except the response? If so, that probably means your page is posting back, not doing an ajax call. (Or maybe it's doing both, but it refreshes before you can see the result of the ajax). So more than likely, the way you're triggering the submit _is_ the root of the problem – ADyson Apr 12 '17 at 15:19
  • Also, I've just been looking at http://api.jquery.com/trigger/. I don't think you can pass a function as the second parameter. It should be an object or array containing some extra options which are then passed to the event handler function (which should be declared elsewhere). So I strongly suspect your function never even runs. Putting a quick "alert" at the start of the function, before the ajax call, would confirm/deny this. – ADyson Apr 12 '17 at 15:25
  • @ADyson, Good observation. It appears that the ajax call is not made. The form is submitted just because I have defined the `action`. I am wondering why my ajax code is not working . Any clue? – Ashok.N Apr 12 '17 at 15:27
  • Just see my very last comment as to why. You need to adopt the method of declaring the submit handler as suggested by mplungjan earlier. – ADyson Apr 12 '17 at 15:28
  • I could see that my function `createAttachmentRequest()` is being called. But when I empty the `action` attribute of the form, the code ` $.ajax({ url:....` is not getting executed. Looks like something is wrong with my ajax call. Any clue now? – Ashok.N Apr 12 '17 at 15:32
  • I've already mentioned it above: As I wrote previously: "I've just been looking at https://api.jquery.com/trigger. I don't think you can pass a function as the second parameter. It should be an object or array containing some extra options which are then passed to the event handler function (which should be declared elsewhere). So I strongly suspect your function never even runs. Putting a quick "alert" at the start of the function, before the ajax call, would confirm/deny this." For clarity, I'm talking about the anonymous function which is the 2nd argument to your "trigger" call. – ADyson Apr 12 '17 at 15:32
  • @ADyson, I have edited the question by adding more code. Please take a look. The first alert `alert("ONE");` is executed. But the second alert `alert("TWO");` is never reached. Now tell me what changes i have to make? – Ashok.N Apr 12 '17 at 15:42

1 Answers1

1

Looking at https://api.jquery.com/trigger, I don't think you can pass a function as the second parameter to the "trigger" method. That argument should be an object or array containing some extra options which are then passed to the event handler function (which should be declared elsewhere). The anonymous function you've defined there runs. Therefore, the normal postback behaviour of the form carries on regardless, and there's no ajax call. That's why you appear to see a response, but don't get the "success" or "error" callbacks triggered - there's never an ajax call in the first place.

What you've done is not the correct way to define an event on an element. The "trigger" method is intended to trigger an event which has already been defined previously. It can't be used to define the event handler itself.

This should work - it creates an event handler for the "submit" event of the form, which suppresses the default postback behaviour and runs the ajax call instead:

$(document).ready(function() {
  $("#CreateAttachmentForm").submit(function(event) {
    event.preventDefault(); //stop default postback behaviour.
    $.ajax({
      url: 'http://HDDT0214:8080/pqawdTestWebApp/uploadFile',
      type: 'POST',
      data: formData,
      success: function (data) {
        alert("test");
        alert(JSON.stringify(data));
      },
      error: function(jqXHR, errorThrown, textStatus) {
        alert("Ajax error: " + jqXHR.status + " - " + jqXHR.statusText);
        console.log(jqXHR.responseText);
      },
      contentType: false,
      processData: false
    });
  });
});

You can then remove the createAttachmentRequest() function and all references to it.

N.B. This will work as long as whatever <contact:contactbutton is renders an <input type="submit"... or <button type="submit"... style button to the page, within the form. If not, you need to amend this to output the correct element, otherwise it will not trigger the form's native submit event.

ADyson
  • 57,178
  • 14
  • 51
  • 63
  • Thanks for the explanation. I am getting "formData is undefined" error after making the changes as you suggested. So, I have added `var formData = new FormData($(this)[0]);` .Now I am getting "FormData is undefined".BTW, I am using IE11 browser. – Ashok.N Apr 13 '17 at 11:10
  • 1
    It should be supported in IE10 or above,https://developer.mozilla.org/en-US/docs/Web/API/FormData#Browser_compatibility, Are you on a corporate PC? Check the page isn't running in compatibility mode for an older version. Meanwhile if you want to test your actual code, you can just use another supported browser such as Chrome or Firefox – ADyson Apr 14 '17 at 04:29
  • @Ashok.N Did it work ok in another browser? If the answer has helped you, please consider upvoting/marking as accepted answer - thanks :-) – ADyson Apr 18 '17 at 09:59
  • Sorry for late reply as I was on vacation. You are correct. My IE is running in compatibility mode for IE7. I have opened a new thread on accomplishing the same file upload task using Ajax for IE7. http://stackoverflow.com/questions/43472559/how-to-send-form-data-fields-using-ajax-request-for-ie7 Could you please check once? – Ashok.N Apr 18 '17 at 12:46
  • 1
    Thanks for your support. Plus one for your helping nature. – Ashok.N Apr 18 '17 at 12:47