Results 1 to 12 of 12
  1. #1
    Wasp is offline Member
    Join Date
    Nov 2016
    Posts
    32
    Rep Power
    0

    Default Servlet Jsp + Ajax + Json onsubmit event send data.

    First what i am trying. I have 1 form 2 servlet. In form i have 1 input file element. When user input file onchange method sending json data image my UploadFile servlet. I am getting this data uploading with apache file upload libarary. And i am returning json string my filepath for ajax success function. And i writing this path to my hidden input element. There is no problem here. But when i want to get form data with onsubmit event i have to problem. Request coming null. I need get for text with my hidden file path send with ajax my Controller servlet. Then i can save band and band image path. Then i can use this object. But i cant send form with ajax :( What i am doing wrong in my form or my saveEntity() function? (Sorry for terrible english)

    XML Code:
    <form action="AddBand" method="POST" onSubmit="saveEntity(this)">
    	<div class="form-group">
    		<label  for="bandName">GRUP ADI</label>
    		<input type="text" id="bandName" class="form-control" name="bandName">
    	</div>
    	<div class="form-group">
    		
    		<div class="row">
    		<div class="col-md-4">
    			<label  for="member">GRUP ÜYESİ</label>
    			<input type="text" id="member" class="form-control" name="member">
    			<input type="button" class="btn btn-success" style="float: right;" onClick="addMember();" value="Ekle">
    		</div>
    		<div class="col-md-8">
    			<label  for="bandName">EKLENEN ÜYELER</label>
    			<select class="form-control" name="memberList" id="memberList"></select>
    			<input type="button" class="btn btn-success" style="float: right;" onClick="deleteMember();" value="Çıkar">
    		</div>
    		</div>
    	</div>
    	<div class="from-group">
    		<label  for="bandPicture">GRUP RESMİ</label>
    		<input type="file" accept="image/x-png,image/gif,image/jpeg" id="bandPicture" onchange="uploadImage(this)" class="form-control" name="bandPicture">
    		<label id="uploadResult"></label>
    		<input type="hidden" id="fileName" name="fileName" />
    	</div>
    	<div class="form-group">
    		<label >
    			<input type="checkbox" name="standartBand">Haftalık Grup
    		</label>
    	</div>
    	<div class="form-group">
    		<label for="bandInfo">GRUP HAKKINDA</label></br>
    		<textarea  class="form-control" id="editor" rows="6" name="bandInfo"></textarea>
    	</div>
    	<div class="form-group">
    		<input type="submit" class="btn-success" value="GRUBU EKLE">
    	</div>
    </form>
    My costum.js file;

    Java Code:
    /**
     * 
     */
    
    /* UPLOAD IMAGE */
    
    function uploadImage(File) {
    	  var file_data = $(File).prop('files')[0];
    	  var form_data = new FormData();
    	  form_data.append("File", file_data);
    	$.ajax({
    		  type: 'Post',
    		  url: 'UploadImage',
    		  enctype: 'multipart/form-data',
    		  datatype: 'json',
    		  cache: false,
    		  contentType: false,
    		  processData: false,
    		  data: form_data,
    		  success: function (result) { 
    			  var data = $.parseJSON(result);
    			 if (data.result) {
    				  $('#fileName').val(data.fileName);
    			}
    			 $('#uploadResult').html(data.resultMsg);
    		  }
    	});
    
    }
    
    function saveEntity() {
    	console.log("method started");
    	  var file_data = $(this).prop('files')[0];
    	  var form_data = new FormData();
    	  form_data.append(this, file_data);
    	$.ajax({
    		type: $(this).attr('method'),
    		url: $(this).attr('action'),
    		datatype : 'json',
    		data: form_data,
    		success: function (result) {
    			var data = $.parseJSON(result);
    			alert(data.resultMsg);
    		}
    	});
    	return true;
    }
    My UploadFile Servlet

    Java Code:
    public class UploadImageController extends HttpServlet {
    	
    	/**
    	 * 
    	 */
    	private static final long serialVersionUID = 6737157694478413704L;
    	
    	// Yüklenecek dizin
    	private static final String UPLOAD_DIRECTORY = File.separator + "assets" + File.separator + "images" + File.separator + "upload";
    
    	// Upload ayarları
    	private static final int MEMORY_THRESHOLD 	= 1024 * 1024 * 3; 	// 3MB
    	private static final int MAX_FILE_SIZE 		= 1024 * 1024 * 40; // 40MB
    	private static final int MAX_REQUEST_SIZE	= 1024 * 1024 * 50; // 50MB
    	private static final String UPLOAD_SUCCESS = "Dosya Yüklendi";
    	private static final String UPLOAD_FAIL = "Dosya Yüklenemedi";
    	private static final String NO_FILE = "Lütfen Resim Seçin";
    
    	@Override
    	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    		resp.setContentType("text/plain");
    		resp.setCharacterEncoding("UTF-8");
    		PrintWriter out = resp.getWriter();
    		JSONObject jsonObject = new JSONObject();
    		if(!ServletFileUpload.isMultipartContent(req)) {
    			out.print("enctype = multipart/form-data olmalıdır.");
    			out.flush();
    			return;
    		}
    		
    		DiskFileItemFactory factory = new DiskFileItemFactory();
    		factory.setSizeThreshold(MEMORY_THRESHOLD);
    		File repository = new File(System.getProperty("java.io.tmpdir"));
    		System.out.println(repository.getAbsolutePath());
    		factory.setRepository(repository);
    		ServletFileUpload upload = new ServletFileUpload(factory);
    		upload.setFileSizeMax(MAX_FILE_SIZE);
    		upload.setSizeMax(MAX_REQUEST_SIZE);
    		//Dosya yükeleneceği dizin
    		String uploadPath =  getServletContext().getRealPath(UPLOAD_DIRECTORY);
    		File uploadDir = new File(uploadPath);
    		if (!uploadDir.exists()) {
    			uploadDir.mkdirs();
    		}
    		System.out.println(uploadPath);
    		
    		try {
    			List<FileItem> images = upload.parseRequest(req);
    			if (images != null && images.size() > 0) {
    				for (FileItem image : images) {
    					if (!image.isFormField()) {
    						String fileName = image.getName();
    						if (fileName != null) {
    						    fileName = FilenameUtils.getName(fileName);
    						}
                            fileName = fileName.substring(0, fileName.indexOf(".")) + System.currentTimeMillis() + fileName.substring(fileName.indexOf("."));
                            String filePath = uploadPath + File.separator + fileName;
                            //Dosya yolu
                            File storeFile = new File(filePath);
                            //Dosyayı Kaydet
                            image.write(storeFile);
                            jsonObject.put("result", true);
                            jsonObject.put("resultMsg", UPLOAD_SUCCESS);
                            jsonObject.put("fileName", fileName);
                            out.print(jsonObject);
                        }
    				}
    			} else out.print(NO_FILE);
    		} catch (Exception e) {
    			jsonObject.put("result", false);
    			jsonObject.put("resultMsg", UPLOAD_FAIL);
    			out.print(jsonObject);
    			e.printStackTrace();
    		}
    		out.close();
    	}
    	
    }
    My Form Servlet, For save entity

    Java Code:
    package manhattan.controller;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.Arrays;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.hibernate.HibernateException;
    import org.json.JSONObject;
    
    import manhattan.domain.impl.Admin;
    import manhattan.domain.impl.Band;
    import manhattan.domain.impl.Picture;
    import manhattan.service.AdminService;
    import manhattan.service.BandService;
    import manhattan.service.impl.AdminServiceImpl;
    import manhattan.service.impl.BandServiceImpl;
    
    public class AdminController extends HttpServlet {
    	
    	/**
    	 * 
    	 */
    	private static final long serialVersionUID = 1L;
    	
    	private final static String ADD_BAND_SUCCESS = "Grup Eklendi!";
    	private final static String ADD_BAND_FAIL = "Hata: Grup Eklenmedi!";
    	private final AdminService adminService;
    	private final BandService bandService;
    
    	public AdminController() {
    		this.adminService = new AdminServiceImpl();
    		this.bandService = new BandServiceImpl();
    	}
    
    	@Override
    	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    		String path = req.getServletPath();
    		switch (path) {
    		case "/AdminPanel":
    			req.getRequestDispatcher("WEB-INF/pages/admin/Admin.jsp").forward(req, resp);
    			break;
    			
    		case "/AddBand":
    			req.getRequestDispatcher("WEB-INF/pages/admin/AddBand.jsp").forward(req, resp);
    			break;
    
    		default:
    			break;
    		}
    		
    	}
    	
    	@Override
    	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    		String path = req.getServletPath();
    		PrintWriter out = resp.getWriter();
    		JSONObject jsonObject = new JSONObject();
    		switch (path) {
    		case "/AddBand":
    			String bandName = req.getParameter("bandName");
    			String[] members = req.getParameterValues("memberList");
    			String bandInfo = req.getParameter("bandInfo");
    			String getPicture = req.getParameter("fileName");
    			boolean standartBand = req.getParameter( "standartBand" ) != null;
    			Band entity = new Band();
    			entity.setBandName(bandName);
    			entity.setBandMembers(Arrays.asList(members));
    			entity.setBandInfo(bandInfo);
    			entity.setStandartBand(standartBand);
    			Picture picture = new Picture();
    			picture.setLink(getPicture);
    			entity.setPicture(picture);
    			System.out.println(entity);
    			try {
    				bandService.save(entity);
    				jsonObject.put("result", true);
    				jsonObject.put("resultMsg", ADD_BAND_SUCCESS);
    				out.print(jsonObject);
    			} catch (HibernateException e) {
    				jsonObject.put("result", false);
    				jsonObject.put("resultMsg", ADD_BAND_FAIL);
    				out.print(jsonObject);
    			}
    			break;
    			
    		case "/DeleteBand":
    			
    			break;
    			
    		case "/UpdateBand":
    			
    			break;
    
    		default:
    			break;
    		}
    		out.close();
    	}
    }
    Last edited by Wasp; 06-25-2017 at 05:36 PM.

  2. #2
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,532
    Rep Power
    24

    Default Re: Servlet Jsp + Ajax + Json onsubmit event send data.

    I still don't quite understand why the image upload is separate from the main form submit.
    Indeed, have you checked that the form submit isn't sending it all again?

    Anyway, so the ajax call that sends the image works, and the fileName field gets populated correctly on the page?

    I don't see the code that does the second call when submit is clicked.
    Indeed, since you want this to be an Ajax call I wouldn't have the button as a Submit button. Just have a normal button (or link) that has an onClick method associated with it. That method will do the call.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  3. #3
    Wasp is offline Member
    Join Date
    Nov 2016
    Posts
    32
    Rep Power
    0

    Default Re: Servlet Jsp + Ajax + Json onsubmit event send data.

    I have submit button for form. Input file onchange action work well. fileName coming correct. Now i can add band. But not with ajax. Like normal post. My ajax saveEntity fucntion doesnt work? I have console log and i cant see my log on chrome(console).
    [HTML]div class="form-grou
    <input type="submit" class="btn-success" value="GRUBU EKLE">
    </div>[/HTServlet Jsp + Ajax + Json onsubmit event send data.-sevlet.jpgML]
    Last edited by Wasp; 06-26-2017 at 01:34 PM.

  4. #4
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,532
    Rep Power
    24

    Default Re: Servlet Jsp + Ajax + Json onsubmit event send data.

    Because it is a submit button.
    Don't use a Submit button if you want to use Ajax.
    Just have a button with the onClick set to the saveEntity method.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  5. #5
    Wasp is offline Member
    Join Date
    Nov 2016
    Posts
    32
    Rep Power
    0

    Default Re: Servlet Jsp + Ajax + Json onsubmit event send data.

    Changed submit to button. Now i got another problem.

    XML Code:
    <button type="button" onClick="saveEntity(this.form)">Grubu Ekle</button>
    Uncaught RangeError: Maximum call stack size exceeded
    at Ab (jquery-3.2.1.min.js:4)
    at Ab (jquery-3.2.1.min.js:4)
    at Ab (jquery-3.2.1.min.js:4)
    at Ab (jquery-3.2.1.min.js:4)
    at Ab (jquery-3.2.1.min.js:4)
    at Ab (jquery-3.2.1.min.js:4)
    at Ab (jquery-3.2.1.min.js:4)
    at Ab (jquery-3.2.1.min.js:4)
    at Ab (jquery-3.2.1.min.js:4)
    at Ab (jquery-3.2.1.min.js:4)

    Java Code:
    function saveEntity(entityForm) {
    	console.log(entityForm.id);
    	$.ajax({
    		type: $(entityForm).attr('method'),
    		url: $(entityForm).attr('action'),
    		datatype : 'json',
    		data: entityForm,
    		success: function (result) {
    			var data = $.parseJSON(result);
    			$('#formResult').html(data.resultMsg)
    		}
    	});
    }

  6. #6
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,532
    Rep Power
    24

    Default Re: Servlet Jsp + Ajax + Json onsubmit event send data.

    You might need to debug it.
    Put a breakpoint inside the 'success' function and see where it goes from there.

    One thing, what is the value of 'entityForm' at that point?
    Normally you would see the form data built up as a json string.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  7. #7
    Wasp is offline Member
    Join Date
    Nov 2016
    Posts
    32
    Rep Power
    0

    Default Re: Servlet Jsp + Ajax + Json onsubmit event send data.

    I put breakpoint line 9 and line 10. But console didnt come my break points. Uncaught RangeError: Maximum call stack size exceeded. I search thi error google, i find some bootsrap issue. But i couldnt find solve.

  8. #8
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,532
    Rep Power
    24

    Default Re: Servlet Jsp + Ajax + Json onsubmit event send data.

    And my second question?
    What's the value of entityForm?
    Can you print it out when it comes into the method?
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  9. #9
    Wasp is offline Member
    Join Date
    Nov 2016
    Posts
    32
    Rep Power
    0

    Default Re: Servlet Jsp + Ajax + Json onsubmit event send data.

    Coming like this entityForm = form#addBand. entityForm.id = addBand

    console.log(entityForm) result;

    XML Code:
    <form action="AddBand" method="POST" id="addBand">
    						<div class="form-group">
    							<label for="bandName">GRUP ADI</label>
    							<input type="text" id="bandName" class="form-control" name="bandName">
    						</div>
    						<div class="form-group">
    							
    							<div class="row">
    							<div class="col-md-4">
    								<label for="member">GRUP ÜYESİ</label>
    								<input type="text" id="member" class="form-control" name="member">
    								<input type="button" class="btn btn-success" style="float: right;" onclick="addMember();" value="Ekle">
    							</div>
    							<div class="col-md-8">
    								<label for="bandName">EKLENEN ÜYELER</label>
    								<select class="form-control" name="memberList" id="memberList"></select>
    								<input type="button" class="btn btn-success" style="float: right;" onclick="deleteMember();" value="Çıkar">
    							</div>
    							</div>
    						</div>
    						<div class="from-group">
    							<label for="bandPicture">GRUP RESMİ</label>
    							<input type="file" accept="image/x-png,image/gif,image/jpeg" id="bandPicture" onchange="uploadImage(this)" class="form-control" name="bandPicture">
    							<label id="uploadResult"></label>
    							<input type="hidden" id="fileName" name="fileName">
    						</div>
    						<div class="form-group">
    							<label>
    								<input type="checkbox" name="standartBand">Haftalık Grup
    							</label>
    						</div>
    						<div class="form-group">
    							<label for="bandInfo">GRUP HAKKINDA</label><br>
    							<textarea class="form-control" id="editor" rows="6" name="bandInfo"></textarea>
    						</div>
    						<div class="form-group">
    							<button type="button" onclick="saveEntity(this.form)" class="btn-success">Grubu Ekle</button>
    							<label id="formResult"></label>
    						</div>
    					</form>
    Last edited by Wasp; 06-27-2017 at 01:01 PM.

  10. #10
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,532
    Rep Power
    24

    Default Re: Servlet Jsp + Ajax + Json onsubmit event send data.

    Which, I think, will confuse any JSON parser.
    That could be the issue.

    Normally the data would be something like:
    Java Code:
    data: { name: "John", location: "Boston" },
    (pinched from the JQuery.ajax page)

    Or defined as a variable beforehand;
    Java Code:
    var data = { name: "John", location: "Boston" };
    $.ajax({
    ...
    data: data,
    ...
    });
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  11. #11
    Wasp is offline Member
    Join Date
    Nov 2016
    Posts
    32
    Rep Power
    0

    Default Re: Servlet Jsp + Ajax + Json onsubmit event send data.

    I need parse form data to json somewhere?

  12. #12
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,532
    Rep Power
    24

    Default Re: Servlet Jsp + Ajax + Json onsubmit event send data.

    Yes.
    What you are attempting to send at the moment is just html, which isn't going to work.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

Similar Threads

  1. Replies: 1
    Last Post: 08-23-2016, 10:24 AM
  2. Replies: 5
    Last Post: 07-14-2014, 08:50 AM
  3. How to send data from servlet to JSP
    By dalu in forum Java Servlet
    Replies: 2
    Last Post: 10-21-2011, 10:39 AM
  4. flush data from servlet to jsp with ajax
    By Laerion in forum Advanced Java
    Replies: 1
    Last Post: 04-10-2011, 09:00 AM
  5. Replies: 1
    Last Post: 01-28-2008, 11:49 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •