ajaxSubmit / function(data) call happening twice - ajax

I am trying to upload a large file and having issues of submit happening twice.
But not for small file sizes.
The $("#fileform").ajaxSubmit({ call seems to be happening twice or multiple times instead of once. Or the submit 'success : function(data) {' .
Not sure. I am able to see the details in 'commands_cvs_grpupload.jsp' twice.
HTML:
<form id="fileform" method="post" align="left">
<input id="importFile" name="importFile" type="file" onkeydown="return false"
onpaste="return false" ondragenter="return false"/>
<input id= "errorRecords" name = "errorRecords" type="hidden"/>
<input id= "type" name = "type" value="BULK_UPLOAD" type="hidden"/>
<input name="import" type="button" onClick="importCSV();" value="Import CSV"/>
Script for importCSV():
function importCSV(){
if(checkFileIsNull()){
$("#requiredFile").css("color","#000000");
$("#requiredFileType").css("color","#000000");
$("#gridWrapper").hide("slow");
configDisplayMessage("displayMessage","White");
$("#displayMessage").html("");
$("#ui-progressbar-value").html("");
$("#statusmessage").html("");
$( "#progressbar" ).progressbar({
value: 0
});
$("#processDiv").show();
$("#progressbar").show();
$("#statusmessage").show();
$("#ui-progressbar-value").show();
$("#progressbar").html("Waiting...");
// submit file to SBS; command is callaSBSImport
submitFileToSBS();
// get status for SBS ; command is callSBSStatus
getStatusFromSBS();
startProcess = setInterval("getStatusFromSBS()",3000);
}else{
$("#gridWrapper").hide("slow");
$("processDiv").hide();
$("#progressbar").hide();
$("#statusmessage").hide();
$("#ui-progressbar-value").hide();
}
}
Script for submitFileToSBS()
function submitFileToSBS(){
$("#fileform").ajaxSubmit({
type : "post",
url : "framework/commands_cvs_grpupload.jsp",
dataType:"json",
data : "Command=callSBSGroup&Service=ComplianceValidation&Method=uploadGroupings",
success : function(data) {
setProcessBar(100,"Process is done.");
clearInterval(startProcess);
errorRecords = Array();
var list = "";
var stringBuilder = "";
/*MY CODE*/
},
error : function (XMLHttpRequest, textStatus, errorThrown) {
/*MY CODE*/
}
});
}

Related

my ajax not giving result in codeigniter

i am registering users via ajax, user is inserted into the database but my loader continue to show loading and is no hiding furthermore i put an alert to view the result but it is also not shown
so where i am doing wrong please help me.
here is my view
<tr>
<td style="width: 25%;"><p>Name</p>
<input type="text" name="name" id="name_r"
placeholder="Enter name" required=""/>
</td>
<td style="width: 25%;"><p>username</p>
<input type="text" name="username" id="uname"
placeholder="Enter username" required=""/>
</td>
</tr>
my script is
$(document).ready(function(){
$("#register_staff").click(function(){
var name = $("#name_r").val();
var username = $("#uname").val();
if (name && username) {
$('#loader_register').show();
$.ajax(
{
type: "POST",
url:"<?php echo
base_url('register_management_staff')?
>",
data:{name:name,username:username},
success: function(result){
alert(result);
$('#loader_register').hide();
$('#name_r').val("");
$('#result_register').html(result);
}
}
);
}
else{
document.getElementById
('result_register').innerHTML='<font color=red>
Please fill all fields.</font>';
}
});
});
my controller is
public function register_management_staff()
{
$post['name']= $_REQUEST['name'];
$post['username']= $_REQUEST['username'];
$result = $this->managementmodel
->register_management_staff($post);
if($result == 1){
echo '<font color=green>Congrats! Successfully
Register.</font>';
}
else{
echo '<font color=red>Please enter correct data
and check availability.</font>';
}
}
my model is
public function register_management_staff($post)
{
$this->db->insert('management_login',$post);
return 1;
}
If you have a button by the id of register_staff then >
Edit Your Script and Use This
$(document).ready(function(){
$("#register_staff").on('click',function(){
var name = $("#name_r").val();
var username = $("#uname").val();
if (name && username) {
$('#loader_register').show();
$.ajax({
type: "POST",
url:"<?php echo base_url('register_management_staff'); ?>",
data:{name:name,username:username},
success: function(result){
alert(result);
$('#loader_register').hide();
$('#name_r').val("");
$('#result_register').html(result);
}
});
}
else{
$('#result_register').html("<font color='red'>Please fill all fields.</font>");
}
});
});
In your ajax code provide correct path in url
$.ajax(
{
type: "POST",
url:"<?php echo
site_url('register_management_staff')?
>",
data:{name:name,username:username},
success: function(result){
alert(result);
$('#loader_register').hide();
$('#name_r').val("");
$('#result_register').html(result);
}
}
);
Here in ajax url must be like
url:"<?php echo site_url('controller_name/method');?>"
Make changes are try

Spring Thymealef Ajax update fragmenet

I'm using spring boot MVC, and have a part that I make an ajax request to update a collection of products for merchandise shipment, but when I post it is displaying json on the screen instead of updating the fragment:
<th:block th:if="${expedicao.tipoRegistro eq 'A' or expedicao.tipoRegistro eq 'X'}">
<form action="#" th:action="#{/expedicao/buscaprod}" method="post"
name="formBusca">
<input type="hidden" th:name="${_csrf.parameterName}"
th:value="${_csrf.token}" /> <label th:text="Ean13">Ean13</label>
<input type="radio" name="tipoCod" id="tipoCod" value="ean13" /> <label
th:text="Dun14">Dun14</label> <input type="radio" name="tipoCod"
id="tipoCod" value="dun14" /> <input type="text"
name="FieldCodigo" class="form-control" placeholder="Codigo Barras"
id="FieldCodigo" value="" autofocus="autofocus" required="required" />
<input type="hidden" name="id_expedicao" id="id_expedicao"
th:value="${expedicao.id}" />
<button type="submit" value="Buscar">Buscar</button>
</form>
</th:block>
<div th:fragment="info-success" xmlns:th="http://www.thymeleaf.org" th:remove="tag">
<div class="modal-body row" id="coleta">
<div th:replace="expedicao/coleta::coleta"></div>
</div>
</div>
</div>
this is my ajax
<th:block layout:fragment="scripts">
<script th:inline="javascript">
/*<![CDATA[*/
$(function() {
$.ajaxSetup({
headers : {
'X-CSRF-Token' : $('meta[name=_token]').attr('content')
}
});
$('form#formBusca').submit(
function(e) {
e.preventDefault();
$.ajax({
type : "POST",
contentType : "application/json",
url : 'expedicao/buscaprod',
data : $('form#formBusca').serialize(),
dataType : 'json',
success : function(result) {
if(result.status == "Done"){
carregarColeta(result.data.id);
if (result.data.situacao == 'B'
|| result.data.situacao == 'C') {
$('form#formBusca').remove();
}
},
error : function(jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log("AJAX error:" + textStatus + ' : '
+ errorThrown);
}
});
$('input[name=FieldCodigo]').val('');
});
});
function carregarColeta(idexpedicao) {
$.ajax({
method : 'POST',
url : 'expedicao/detalhe',
data : {
'id_expedicao' : idexpedicao
},
success : function(retorno) {
$('#coleta').empty().html(retorno);
},
error : function(jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log("AJAX error:" + textStatus + ' : '
+ errorThrown);
}
});
}
when a execute the post method it go to my controller execute the logic and return the json of the object updated, and instead of update the fragment calling the JS function carregaExpedicao.. its dislpay the json on the screen, and change the url
this is my controller
#Controller
public class ExpedicaoController {
#RequestMapping(value = "/expedicao/buscaprod", method = RequestMethod.POST)
#ResponseBody
public Response updateProdutoColetado(
#RequestParam(name = "id_expedicao") String id_expedicao,
#RequestParam(name = "FieldCodigo") String FieldCodigo,
Model model, HttpSession session) {
//Minhas regras
model.addAttribute("expedicao", expedAndamento);
return new Response("Done", expedAndamento);
}
#RequestMapping(value = "/expedicao/detalhe")
public String detalhe(#RequestParam(name = "id_expedicao") String id_expedicao, Model model, HttpSession session) {
model.addAttribute("expedicao", expedAndamento);
return "expedicao/coleta";
}
}
Fixed:
error 1 => id on the form
error 2 => missing csrf param on ajax

Sending file to Servlet from Ajax [duplicate]

I'm creating a JSP/Servlet web application and I'd like to upload a file to a servlet via Ajax. How would I go about doing this? I'm using jQuery.
I've done so far:
<form class="upload-box">
<input type="file" id="file" name="file1" />
<span id="upload-error" class="error" />
<input type="submit" id="upload-button" value="upload" />
</form>
With this jQuery:
$(document).on("#upload-button", "click", function() {
$.ajax({
type: "POST",
url: "/Upload",
async: true,
data: $(".upload-box").serialize(),
contentType: "multipart/form-data",
processData: false,
success: function(msg) {
alert("File has been uploaded successfully");
},
error:function(msg) {
$("#upload-error").html("Couldn't upload file");
}
});
});
However, it doesn't appear to send the file contents.
To the point, as of the current XMLHttpRequest version 1 as used by jQuery, it is not possible to upload files using JavaScript through XMLHttpRequest. The common workaround is to let JavaScript create a hidden <iframe> and submit the form to it instead so that the impression is created that it happens asynchronously. That's also exactly what the majority of the jQuery file upload plugins are doing, such as the jQuery Form plugin (an example).
Assuming that your JSP with the HTML form is rewritten in such way so that it's not broken when the client has JavaScript disabled (as you have now...), like below:
<form id="upload-form" class="upload-box" action="/Upload" method="post" enctype="multipart/form-data">
<input type="file" id="file" name="file1" />
<span id="upload-error" class="error">${uploadError}</span>
<input type="submit" id="upload-button" value="upload" />
</form>
Then it's, with the help of the jQuery Form plugin, just a matter of
<script src="jquery.js"></script>
<script src="jquery.form.js"></script>
<script>
$(function() {
$('#upload-form').ajaxForm({
success: function(msg) {
alert("File has been uploaded successfully");
},
error: function(msg) {
$("#upload-error").text("Couldn't upload file");
}
});
});
</script>
As to the servlet side, no special stuff needs to be done here. Just implement it exactly the same way as you would do when not using Ajax: How can I upload files to a server using JSP/Servlet?
You'll only need an additional check in the servlet if the X-Requested-With header equals XMLHttpRequest or not, so that you know how what kind of response to return for the case that the client has JavaScript disabled (as of now, it is mostly the older mobile browsers which have JavaScript disabled).
if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
// Return an Ajax response (e.g. write JSON or XML).
} else {
// Return a regular response (e.g. forward to JSP).
}
Note that the relatively new XMLHttpRequest version 2 is capable of sending a selected file using the new File and FormData APIs. See also HTML5 drag and drop file upload to Java Servlet and Send a file as multipart through XMLHttpRequest.
Monsif's code works well if the form has only file type inputs. If there are some other inputs other than the file type, then they get lost. So, instead of copying each form data and appending them to FormData object, the original form itself can be given to the constructor.
<script type="text/javascript">
var files = null; // when files input changes this will be initialised.
$(function() {
$('#form2Submit').on('submit', uploadFile);
});
function uploadFile(event) {
event.stopPropagation();
event.preventDefault();
//var files = files;
var form = document.getElementById('form2Submit');
var data = new FormData(form);
postFilesData(data);
}
function postFilesData(data) {
$.ajax({
url : 'yourUrl',
type : 'POST',
data : data,
cache : false,
dataType : 'json',
processData : false,
contentType : false,
success : function(data, textStatus, jqXHR) {
alert(data);
},
error : function(jqXHR, textStatus, errorThrown) {
alert('ERRORS: ' + textStatus);
}
});
}
</script>
The HTML code can be something like following:
<form id ="form2Submit" action="yourUrl">
First name:<br>
<input type="text" name="firstname" value="Mickey">
<br>
Last name:<br>
<input type="text" name="lastname" value="Mouse">
<br>
<input id="fileSelect" name="fileSelect[]" type="file" multiple accept=".xml,txt">
<br>
<input type="submit" value="Submit">
</form>
$('#fileUploader').on('change', uploadFile);
function uploadFile(event)
{
event.stopPropagation();
event.preventDefault();
var files = event.target.files;
var data = new FormData();
$.each(files, function(key, value)
{
data.append(key, value);
});
postFilesData(data);
}
function postFilesData(data)
{
$.ajax({
url: 'yourUrl',
type: 'POST',
data: data,
cache: false,
dataType: 'json',
processData: false,
contentType: false,
success: function(data, textStatus, jqXHR)
{
//success
},
error: function(jqXHR, textStatus, errorThrown)
{
console.log('ERRORS: ' + textStatus);
}
});
}
<form method="POST" enctype="multipart/form-data">
<input type="file" name="file" id="fileUploader"/>
</form>
This code works for me.
I used Commons IO's io.jar, Commons file upload.jar, and the jQuery form plugin:
<script>
$(function() {
$('#upload-form').ajaxForm({
success: function(msg) {
alert("File has been uploaded successfully");
},
error: function(msg) {
$("#upload-error").text("Couldn't upload file");
}
});
});
</script>
<form id="upload-form" class="upload-box" action="upload" method="POST" enctype="multipart/form-data">
<input type="file" id="file" name="file1" />
<span id="upload-error" class="error">${uploadError}</span>
<input type="submit" id="upload-button" value="upload" />
</form>
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
try {
// Parse the request
List items = upload.parseRequest(request);
Iterator iterator = items.iterator();
while (iterator.hasNext()) {
FileItem item = (FileItem) iterator.next();
if (!item.isFormField()) {
String fileName = item.getName();
String root = getServletContext().getRealPath("/");
File path = new File(root + "../../web/Images/uploads");
if (!path.exists()) {
boolean status = path.mkdirs();
}
File uploadedFile = new File(path + "/" + fileName);
System.out.println(uploadedFile.getAbsolutePath());
item.write(uploadedFile);
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}

input(file) and input (text) send with one ajax

html
<body>
<form method="post" action="" id="dataForm" enctype="multipart/form-data">
<input type="text" id="textSelector"/>
<input type="file" id="fileSelector"/>
<button name="sub-comfirm" class="btn-selection-content" type="submit" id="sub-comfirm">Send</button>
</form>
</body>
js/ajax
var fileVar = null;// global var to store file info
$(document).ready(function(){
$('#dataForm').on('submit', function(e) {
e.preventDefault();
SendData();
});
$('#fileSelector').on('change',function(ev){
fileVar = null;
fileVar = new FormData();
$.each(ev.target.files, function(key, value)
{
fileVar.append(key, value);
});
});
});
function SendData(){
var formData = new FormData($("#dataForm")[0]);
// should i add the filerVar like this ?
// formData.append("Image", fileVar);
$.ajax({
type: "POST",
url: "checkinput.php",//you need to add this '?files part' to URL
data: formData,// use fileVar here now
cache: false,
processData: false,
// contentType: false,
success:function(data)
{
console.log(data);
console.log("success");
},
error: function(jqXHR, textStatus, errorThrown)
{
console.log("failure");
}
});
}
php
print_r($_POST);
print_r($_FILES);
my intention is to send input(file) and input(text) in one ajax , i can get the input file value if i add ajax data with fileVar , but i cant get my input text value i have no idea why , can anyone tell me what i did wrong ?
var formData = new FormData($("#dataForm")[0]) is the way to get both to one ajax but i cant get any input text value.
anyone can teach me how to make this work ?
I think you need to specify input name attributes:
<body>
<form method="post" action="" id="dataForm" enctype="multipart/form-data">
<input type="text" id="textSelector" name="textSelector"/>
<input type="file" id="fileSelector" name="fileSelector"/>
<button name="sub-comfirm" class="btn-selection-content" type="submit" id="sub-comfirm">Send</button>
</form>
</body>
Hope that helps.

How to insert into database after processing data through ajax formdata

My goal is to upload a file and insert data into a database table with ajax using formdata. I can do both separately. Or at least, I can use formdata to upload a file and I can use ajax to insert data into a database, but putting it together has proven difficult. The tutorial for this code seemed to indicate it would do it, and based on what I understand, the ajax is processing the entire form, but it's only uploading the file. I'm not having any issue with that and unfortunately, that's what most of the questions and tutorials I'm finding seem to be directed towards.
I think the issue is with my php insert code. Should I be inserting differently because of how the data is passed through ajax? Or am I more lost than that and just think I'm passing it all through ajax? I feel like I'm so close now, but I can't figure out what I'm doing wrong.
Thank you for any help.
The form and ajax:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<form name="multiform" id="multiform" action="upload.php" method="POST" enctype="multipart/form-data">
Name: <input type="text" name="dname" /> <br/>
Age :<input type="text" name="age" /> <br/>
Image :<input type="file" name="photo" /><br/>
<input type="submit" value="Ajax File Upload" />
</form>
<script>
//Callback handler for form submit event
jQuery(document).ready(function() {
$("#multiform").submit(function(e)
{
var formObj = $(this);
var formURL = formObj.attr("action");
var formData = new FormData($(this)[0]);
$.ajax({
url: formURL,
type: 'POST',
data: formData,
mimeType:"multipart/form-data",
contentType: false,
cache: false,
processData:false,
success: function(data, textStatus, jqXHR)
{ alert(data)
},
error: function(jqXHR, textStatus, errorThrown)
{
}
});
e.preventDefault(); //Prevent Default action.
});
$("#multiform").submit(); //Submit the form
});
</script>
The php:
<?php
$username="...";
$password="...";
$database="...";
$target = "...";
$target = $target . time() . '_' . basename( $_FILES['photo']['name']);
$File = time() . '_' . basename($_FILES['photo']['name']);
$name = $_POST['dname'];
$age = $_POST['age'];
mysql_connect(localhost,$username,$password);
#mysql_select_db($database) or die( "Death");
print_r($_POST);
print_r($_FILES);
mysql_query("INSERT INTO wp_demo('name','age','File')VALUES('$name','$age','$File')");
if(isset($_FILES["photo"]))
{
//Filter the file types , if you want.
if ($_FILES["photo"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else
{
//move the uploaded file to uploads folder;
move_uploaded_file($_FILES["photo"]["tmp_name"],$target);
echo $_FILES['photo']['name'] . " is now available";
}
}
?>
EDIT: Nevermind. I still don't know what's wrong here, but it ultimately just needs to work in wordpress. I got it to work there with this:
global $wpdb;
if($wpdb->insert('wp_demo',array(
'name' => $name,
'age' => $age,
'File' => $File
))===FALSE) {
echo "error";
}
else {
echo "success";
}
Now I just need to figure out why it submits on page load...

Resources