Forum Moderators: open

Message Too Old, No Replies

Sending data to server via ajax

         

dupalo

8:41 pm on May 18, 2016 (gmt 0)

10+ Year Member



Hi guys, I have a form which contains a file upload input field. When I select a file, mainly text files, the actual content of the file is displayed in a textarea field below. Now, what I need to do is to send that information - the data contained in the file and displayed in the textarea - as a string to the server using ajax. One of the reasons for doing it that way, rather than sending the actual file, is that users must be able to edit the file information (even copying and pasting into the text displayed in the textarea).
Now, admittedly, I'm not really good with ajax I'm afraid, as I only used it a few times, so I'm trying to get this done but I'm having some difficulty and in fact I don't even know if I managed to do it or not.
Here is the current javascript code as i described above, without the ajax part (the javascript is part of a spring application that's why it's all inside quotes):
This is the popup with the relevant info and the button that attach it to the body tag, pretty simple stuff:

JavaScript.getCurrent().execute(""
+"var $HTMLpopup = $('<div class=\"popupContainer\">"
+"<span class=\"cancelBtn big\"></span>"
+"<div class=\"wrapper\">"
+"<form action=\"\" id=\"fileForm\">"
+"<div class=\"mask\">"
+"<input type=\"file\" title=\" \"name=\"uploadFile\" class=\"uploadFile\">/*filters files to upload*/"
+"<span class=\"pseudoBtn\">Browse</span>"
+"<input type=\"text\" name=\"displayFile\" class=\"displayFile\" placeholder=\"no file loaded\">"
+"<span class=\"cancelBtn small\"></span>"
+"</div>"
+"<textarea class=\"fileResult\"></textarea>"
+"<button type=\"submit\" class=\"submitBtn\">Upload</button>"
+"<div class=\"clear\"></div>"
+"</form>"
+"</div>"
+"</div>');"
+"$('.popupTriggerBtn').click(function(){"
+"/*console.log('button clicked!');*/"
+"var $body = $('body');"
+"$HTMLpopup.appendTo($body);"
+"});"

You'd probably noticed that the form action tag is empty: I don't have any PHP file to handle that because there will be some libraries that I'll use to validate the actual string sent to the server and, like I said, since this is an application I can't even post to the page itself, as I wouldn't have a clue how to do that, so the action is an empty string.
Also, it might be worth noticing that the actual file upload is hidden with opacity 0 as I needed to display a customized button and an input field where the file names is displayed, again pretty simple stuff done all with CSS.
Then with the javascript API I add the file as pkain text to the textarea (not shown here as it isn't relevant).
Here is the code to prevent the submission, trigger some error code functions (they just display an error clientside if you try to submit the form without file attached) and deal with the ajax request:
+"/*ON CLICK SUBMISSION BUTTON*/"
+"var $submitBtn = $HTMLpopup.find('.submitBtn');"
+"$submitBtn.click(function(e){"
+"e.preventDefault();/*prevent submission*/"
+"if(isFileUploadEmpty()){/*IF FIELD EMPTY*/"
+"/*alert('submit clicked');*/"
+"removeError();"
+"showError('empty');"
+"/*return false;*/"
+ "}"
+"else{/*IF NOT EMPTY*/"
+"/*AJAX OPS*/"
+"if (window.XMLHttpRequest){/*XMLHttpRequest SUPPORT?*/"
+"console.log('XMLHttpRequest supported!');"
+"var postData = 'text';"
+"/*var action = $HTMLpopup.find('form#fileForm').attr('action');*/"
+"$.ajax({"
+"type:'post',"
+"url:'url',"
+"dara:'postData',"
+"contentType: 'application/x-www-form-urlencoded',"
+"success: function(responseData, textStatus, jqXHR){"
+"alert('data saved');"
+ "},"
+"error: function(jqXHR, textStatus, errorThrown){"
+ "console.log(errorThrown);"
+ "}"
+ "});"
+ "}"
+"}"
+ "});"

So, here, providing you select a file, when you click submit (again note I'm preventing the submission of the form with e.preventDefault()) I reckon I'm sending something to the server because then I get the alert, but have I managed to send the string contained in the textarea? How do I find out?

Fotiman

9:40 pm on May 18, 2016 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month




have I managed to send the string contained in the textarea?

Nope. I see 3 problems upon quick inspection:

+"$.ajax({"
+"type:'post',"
+"url:'url',"
+"dara:'postData',"

Stripping out the quotes so we can view this as the actual code:

$.ajax({
type:'post',
url:'url',
dara:'postData',

Problem 1: You are passing the string 'url' as the url instead of the actual URL. Not sure if that was intentional for this post, or if you were trying to pass a variable containing the URL.
Problem 2: You have a typo. dara should be data
Problem 3: You are passing the string 'postData' as the data instead of the actual postData.

One way you can verify what you're sending is to use your browser Developer Tools. I'm partial to Chrome as it has the best Developer Tools in my opinion. Press F12 to open the developer tools, click on the Network tab. Make your AJAX request, and then you can click on the request to see what data was sent.

dupalo

7:37 pm on May 19, 2016 (gmt 0)

10+ Year Member



Hi fotiman,
thanks for looking at the code and apologies for the typo, that was very slack of me, I will check my code more carefully next time before posting.
Right, so the URL as a string was intentional as mine isn't a webpage but a maven application and its URL is [localhost:8080...]
In any case, I've changed the ajax bit to this:

+"$submitBtn.click(function(e){"
+"e.preventDefault();/*prevent submission*/"
+"if(isFileUploadEmpty()){/*IF EMPTY*/"
+"/*alert('submit clicked');*/"
+"removeError();"
+"showError('empty');"
+ "}"
+"else{/*IF NOT EMPTY*/"
+"/*AJAX OPS*/"
+"if (window.XMLHttpRequest){/*XMLHttpRequest SUPPORT?*/"
+"console.log('XMLHttpRequest supported!');"
+"var postData = returnFileAsString();/*returns the file as a string*/;"
+"console.log('here is the file as a string ' + postData);"
+"$.ajax({"
+"type:'post',"
+"url:'http://localhost:8080/myapp/',"
+"data:postData,"
+"contentType: 'application/x-www-form-urlencoded',"
+"success: function(responseData, textStatus, jqXHR){"
+"alert('data saved');"
+"console.log('responseData is ' + responseData);"
+"console.log('text status is ' + textStatus);"
+"},"
+"error: function(jqXHR, textStatus, errorThrown){"
+"console.log(errorThrown);"
+"alert('an error has occurred!');"
+"}"
+"});"
+"}"
+"}"
+"});"


So, on click I stop the submission and if the file box is empty I throw an error if not I go ahead with the ajax submission. It seems like it worked as when I check the console as you suggested I can see the info that has been posted to the server, see a screenshot here [s32.postimg.org...]
SO I think that's it then, it's done :-), thanks for your help.
One more thing though. The form hasn't really been submitted as I used e.preventDefault(); but it has reached the server, is that OK? I mean in a way I've submitted it, haven't I?
My next task is to use some proprietary libraries to validate that the info passed to the server with the ajax call is valid, and I was wondering, based on your experience, is there some kind of general principle to do that? I need to have a look at these libraries first of course, but if there is any suggestion you can give me, I'd obviously appreciate it :-)!
thanks