Dynamic jquery AJAX upload form with text and file fields - javascript

I am trying to make a dynamic form wherein a single item has a file, text and select html input types and number of items can be dynamic. The problem is when doing AJAX using jquery, the Form wont serialize for the file input type. Please suggest any technique to do it. My code is below:
<form id="Form1" enctype="multipart/form-data">
<div id="divMain"></div>
<div>
<button id="Upload" type="button" value="Upload"><span>Upload</span></button>
<input id="Add" type="button" value="Add" />
</div>
</form>
<div id="status"></div>
<script type="text/javascript">
var counter = 0;
AddElements(); //add first element
$("#Add").click(function () {
AddElements();
});
function AddElements() {
counter++;
$("#divMain").append("<div><input id='Browse" + counter + "' name='Browse[]' type='file' value='Browse' data-target='#Name" + counter + "' />" +
"<input id='Name" + counter + "' name='Name[]' type='text'/>" +
"<select id='Type" + counter + "' name='Type[]'>" +
"<option>Option1</option>" +
"<option>Option2</option>" +
"</select></div>");
$("#Browse" + counter + "").change(function () {
var filename = $(this).val();
var textbox = $($(this).attr("data-target"));
var lastIndex = filename.lastIndexOf("\\");
var b = filename.lastIndexOf(".");
if ((b == -1) | (b < lastIndex))
filename = filename.substring(lastIndex + 1);
else
filename = filename.substring(lastIndex + 1, b - lastIndex - 1);
textbox.val(filename);
});
}
$("#Upload").click(function (e) {
e.preventDefault();
$("#status").html('Uploading....');
var ajaxData = $("#Form1").serialize();
$.ajax({
url: "AjaxPostDemo.aspx",
type: "POST",
data: ajaxData,
cache: false,
processData: false,
success: function (data) {
$("#status").html("success: " + data);
},
error: function (result) {
$("#status").html("error: " + result);
}
});
});
</script>

Change Your To script It Will Definately Work. :-)
<script type="text/javascript">
var counter = 0;
$(document).ready(function () {
AddElements(); //add first element
$("#Add").click(function () {
AddElements();
});
function AddElements() {
counter++;
$("#divMain").append("<div><input id='Browse" + counter + "' name='Browse[]' type='file' value='Browse' data-target='#Name" + counter + "' />" +
"<input id='Name" + counter + "' name='Name[]' type='text'/>" +
"<select id='Type" + counter + "' name='Type[]'>" +
"<option>Option1</option>" +
"<option>Option2</option>" +
"</select></div>");
$("#Browse" + counter + "").change(function () {
var filename = $(this).val();
var textbox = $($(this).attr("data-target"));
var lastIndex = filename.lastIndexOf("\\");
var b = filename.lastIndexOf(".");
if ((b == -1) | (b < lastIndex))
filename = filename.substring(lastIndex + 1);
else
filename = filename.substring(lastIndex + 1, b - lastIndex - 1);
textbox.val(filename);
});
}
});
$(document).ready(function () {
$("#Upload").click(function (e) {
e.preventDefault();
$("#status").html('Uploading....');
var ajaxData = $("#Form1").serialize();
$.ajax({
url: "AjaxPostDemo.aspx",
type: "POST",
data: ajaxData,
cache: false,
processData: false,
success: function (data) {
$("#status").html("success: " + data);
},
error: function (result) {
$("#status").html("error: " + result);
}
});
});
});
</script>
Second Option
http://www.uploadify.com/documentation/uploadify/multi/
Prefer This It will Uploaded Multifiles on one time with great UI. :-)

Related

Uncaught ReferenceError: Error not defined

I have this jqgrid code below and I have a picture inside it and at the same time its function that I am using. But clicking the button inside my jqgrid it says Uncaught ReferenceError: clickmeapproved is not defined. Is there anything wrong with my code or the way that I am using them?. Same error with the disapproved button.
afterInsertRow: function (rowid) {
var obj = jQuery("#FiTATimeCorrectionV2List").getRowData(rowid);
var FADTLSID = obj.FitaAssignDtlID;
if (FADTLSID !== undefined) {
if (FADTLSID !== "") {
var btnApprove = "<input type = 'image' img alt='' src='../../Content/Images/newimages/check.png' style='height:20px;width:20px;' style ='width: 90px' id='btnApproved" + rowid + "' onclick='clickmeapproved(" + rowid + " )' />"
var btnDisApprove = "<input type = 'image' img alt='' src='../../Content/Images/newimages/delete.png' style='height:20px;width:20px;' style ='width: 90px' id='btnDisApproved" + rowid + "' onclick='clickmedisapproved(" + rowid + " )' />"
jQuery("#FiTATimeCorrectionV2List").setRowData(rowid, { FitaCorForApproval: btnApprove });
jQuery("#FiTATimeCorrectionV2List").setRowData(rowid, { FitaCorForDisApproval: btnDisApprove });
var temp = obj.FitaStatus;
if (temp == "Approved") {
$("#btnApproved" + rowid).hide();
$("#btnDisApproved" + rowid).hide();
}
else if (temp == "Disapproved") {
$("#btnApproved" + rowid).hide();
$("#btnDisApproved" + rowid).hide();
} else {
$("#btnApproved" + rowid).show();
$("#btnDisApproved" + rowid).show();
}
}
}
},
function clickmeapproved(rowid) {
var ans = confirm("Are you sure you want to approve the request of "+ globalFitaCorName +"?");
if (ans) {
$.ajax({
type: "POST",
url: '../Request/SaveFitaApproval?FAID=' + rowid,
dataType: 'json',
success: function (response) {
alert("Successfully approve!");
$("#FiTATimeCorrectionV2List").trigger("reloadGrid");
FiTATimeCorrectionV2(0);
globalFitaCorName = "";
$("#loader").hide();
},
error: function (reponse) {
$("#FiTATimeCorrectionV2List").trigger("reloadGrid");
FiTATimeCorrectionV2(0);
globalFitaCorName = "";
$("#loader").hide();
}
});
}
}
Your "clickmeapproved" function does not have global scope. Check by typing "window.clickmeapproved" in the web inspector.
Here is the code that I use to solve my issue.
var btnApprove = "<input type = 'image' img alt='' src='../../Content/Images/newimages/check.png' style='height:20px;width:20px;' style ='width: 90px' id='btnApproved" + rowid + "' />"
var btnDisApprove = "<input type = 'image' img alt='' src='../../Content/Images/newimages/delete.png' style='height:20px;width:20px;' style ='width: 90px' id='btnDisApproved" + rowid + "' />"
I exclude the button click from it.
$("#btnApproved" + rowid + "").click(function(){
clickmeapproved(rowid);
});
$("#btnDisApproved" + rowid + "").click(function(){
clickmedisapproved(rowid);
});

External resources not reaching inside of function scope

I'm trying to make an inventory picker for my trading website, but I'm having some trouble calling external resources.
When originally calling the external function, all goes correctly, but whenever I try to call the external function INSIDE of a function in the html, it errors, saying
Uncaught TypeError: $(...).imagepicker is not a function
This is my relevant code.
<script src="~/Scripts/image-picker.js"></script>
<script>
var name = "HomeguardDev";
var inventory = [];
var selectedItems = [];
$.ajax({
async: false,
type: 'GET',
url: "/Home/getInventory/?username=" + name + "&page=1",
success: function (data) {
var parsed = JSON.parse(data);
for (var i = 0; i < parsed.length; i++) {
var text = parsed[i].Name;
inventory[i] = parsed[i];
if (parsed[i].SerialNumber !== "---") {
text = text + " [#" + parsed[i].SerialNumber + " / " + parsed[i].SerialNumberTotal + "]";
}
$("#sendingItems").append('<option data-img-label="<small>' + text + '</small>" data-img-src="' + parsed[i].ImageLink + '" value="' + i + '">' + text + '</option>');
}
}
});
$("#sendingItems").imagepicker({
show_label: true
});
function addItem() {
if (selectedItems.length < 4) {
var obj = (inventory[$("#sendingItems").val()]);
if (!containsObject(obj, selectedItems)) {
$('#sendingItems option[value="' + ($("#sendingItems").val()) + '"]').remove();
selectedItems.push(obj);
$("#sendingItems").imagepicker({
show_label: true
});
}
}
}
</script>
<p><a><input type="button" id="addItemButton" onclick="addItem()" value="Add item" /></a></p>
<p><a><input type="button" id="sendTradeButton" onclick="sendTrade()" value="Send Trade" /></a></p>
The error occurs inside of the function addItem() when calling imagepicker, but in the main block it calls and functions correctly. What am I doing incorrectly?

Javascript error with sort

i have this code as shown below,
i got this from a developer who went afk because he has family troubles
basically this code below should grab the json results and form them into a table after sorting the price and then placing it in the table.
heres the code
//first define a function
var sortTable = function () {
$("#tableid tbody tr").detach().sort(function (a, b) {
//substring was added to omit currency sign, you can remove it if data-price attribute does not contain it.
return parseFloat($(a).data('price').substring(1)) - parseFloat($(b).data('price').substring(1));
})
.appendTo('#tableid tbody');
};
//include two files where rows are loaded
//1.js
$.ajax({
type: 'GET',
crossDomain: true,
dataType: 'json',
url: 'api link here',
success: function (json) {
//var json = $.parseJSON(data);
for (var i = 0; i < json.results.length; i++) {
var section = json.results[i].section;
var no = json.results[i].avalible;
var price = json.results[i].price;
var button = "<button class='redirect-button' data-url='LINK'>Compare</button>";
$("#tableid tbody").append("<tr data-price='" + price + "'><td>" + section + "</td><td>" + no + "</td><td>" + price + "</td><td>" + button + "</td></tr>");
$("#tableid").find(".redirect-button").click(function () {
location.href = $(this).attr("data-url");
});
}
sortTable();
},
error: function (error) {
console.log(error);
}
});
//and here is the 2nd js file
$.ajax({
type: 'GET',
crossDomain: true,
dataType: 'json',
url: '2nd api',
success: function (json) {
//var json = $.parseJSON(data);
for (var i = 0; i < json.results.length; i++) {
var section = json.results[i].section;
var no = json.results[i].avalible;
var price = json.results[i].amount;
var button = "<button class='redirect-button' data-url='LINK'>Click Here</button>";
$("#tableid tbody").append("<tr data-price='" + price + "'><td>" + section + "</td><td>" + no + "</td><td>" + price + "</td><td>" + button + "</td></tr>");
$("#tableid").find(".redirect-button").click(function () {
location.href = $(this).attr("data-url");
});
}
sortTable();
},
error: function (error) {
console.log(error);
}
});
Accessing the DOM, to get data that needs to be sorted, is a bad practice IMO. Even worse when you had the results in raw JSON form in the first place (in the success callback of the ajax call). Your success function should do something like this
success: function (json) {
//first sort the results - or better store these results somewhere
//and use that as a data store that is responsible for what is rendered in the DOM
json.results.sort(function(a,b) {
//using substring and parseFloat just like it was done in sortTable
//assuming price field has prices as strings with currency symbol in the first place
return parseFloat(a.substring(1)) - parseFloat(b.substring(1))
});
for (var i = 0; i < json.results.length; i++) {
var section = json.results[i].section;
var no = json.results[i].avalible;
var price = json.results[i].amount;
var button = "<button class='redirect-button' data-url='LINK'>Click Here</button>";
$("#tableid tbody").append("<tr data-price='" + price + "'><td>" + section + "</td><td>" + no + "</td><td>" + price + "</td><td>" + button + "</td></tr>");
$("#tableid").find(".redirect-button").click(function () {
location.href = $(this).attr("data-url");
});
}
}

Incrementally load a webpage: Where can I put: $("#LoadingImage").Hide();

I am not very experienced with JavaScript. Please see the code below:
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.1.min.js"></script>
<script type = "text/javascript">
function GetSQLTable() {
//alert($("#<%=fieldGroupReferences.ClientID%>")[0].value)
var str = $("#<%=fieldGroupReferences.ClientID%>")[0].value
var res = str.split(",");
for (var i = 0; i < res.length; i++) {
$("#LoadingImage").show();
var div = document.createElement('div');
div.id = "div" + i
document.body.appendChild(div);
//alert(res[i]);
$.ajax({
type: "POST",
url: "Default3.aspx/GetSQLTable",
data: '{username: "' + $("#<%=fieldUserName.ClientID%>")[0].value + '", terminalname: "' + $("#<%=fieldTerminalName.ClientID%>")[0].value + '", terminalip: "' + $("#<%=fieldTerminalIP.ClientID%>")[0].value + '", mappingid: "' + res[i] + '", usergroup: "' + $("#<%=fieldUserGroup.ClientID%>")[0].value + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess(i,res.length),
failure: function (response) {
//alert(response.d);
alert('there was an error loading the webpage')
}
});
}
function OnSuccess(i,totalrows) {
return function (response) {
if (response.d != "") {
document.getElementById('div' + i).innerHTML = document.getElementById('div' + i).innerHTML + '<br>' + '<br>' + response.d;
}
}
}
}
window.onload = GetSQLTable
</script>
The code incrementally builds a webpage i.e. x number of HTML tables are obtained and displayed to the webpage as and when they become ready. This works.
The problem is I don't know how to remove the LoadingImage once the webpage is complete i.e. $("#LoadingImage").hide();. OnSuccess is called x number of times depending on how many tables are returned so I cannot put it in there.
One way would be to count the number of successful onSuccess() calls, and hide your loading image when they are all complete:
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.1.min.js"></script>
<script type = "text/javascript">
function GetSQLTable() {
//alert($("#<%=fieldGroupReferences.ClientID%>")[0].value)
var str = $("#<%=fieldGroupReferences.ClientID%>")[0].value
var res = str.split(",");
var numSucceeded = 0;
for (var i = 0; i < res.length; i++) {
$("#LoadingImage").show();
var div = document.createElement('div');
div.id = "div" + i
document.body.appendChild(div);
//alert(res[i]);
$.ajax({
type: "POST",
url: "Default3.aspx/GetSQLTable",
data: '{username: "' + $("#<%=fieldUserName.ClientID%>")[0].value + '", terminalname: "' + $("#<%=fieldTerminalName.ClientID%>")[0].value + '", terminalip: "' + $("#<%=fieldTerminalIP.ClientID%>")[0].value + '", mappingid: "' + res[i] + '", usergroup: "' + $("#<%=fieldUserGroup.ClientID%>")[0].value + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess(i,res.length),
failure: function (response) {
//alert(response.d);
alert('there was an error loading the webpage')
}
});
}
function OnSuccess(i,totalrows) {
return function (response) {
if (response.d != "") {
document.getElementById('div' + i).innerHTML = document.getElementById('div' + i).innerHTML + '<br>' + '<br>' + response.d;
numSucceeded++;
if (numSucceeded === totalrows) {
$("#LoadingImage").hide();
}
}
}
}
}
window.onload = GetSQLTable
</script>
Try using .when with an array of your ajax calls. Something like this (simplified to remove the irrelevant bits):
function GetSQLTable() {
//...
var calls = [];
for (var i = 0; i < res.length; i++) {
//..
calls.push($.ajax({
type: "POST",
//..
}));
}
$.when(calls).then(function(d) {
// all done!!!
});

problem ajax load with autocomplete.?

i created a jquery autocomplete it work true, but loading LOADING... it after removed value by Backspace don't work true. it not hide and Still is show.
how can after removed value by Backspace, hide LOADING... ?
EXAMPLE: Please click on link and see problem
my full code:
$(document).ready(function () {
/// LOADING... ///////////////////////////////////////////////////////////////////////////////////////
$('#loadingDiv')
.hide() // hide it initially
.ajaxStart(function() {
$(this).show();
})
.ajaxStop(function() {
$(this).hide();
});
/// autocomplete /////////////////////////////////////////////////////////////////////////////////////////
$('.auto_complete').keyup(function () {
var specific = '.' + $(this).closest('div.auto_box').find('b').attr('class');
var cl_list = '.' + $(this).closest('div.auto_box').find('ul').attr('class');
var id = '#' + this.id;
var url = $(id).attr('class');
var dataObj = $(this).closest('form').serialize();
$.ajax({
type: "POST",
dataType: 'json',
url: url,
data: dataObj,
cache: false,
success: function (data) {
//alert(url)
var cl_list = '.' + $('.auto_box '+ specific +' ul').attr('class');
var id_name = $(cl_list).attr('id');
$(cl_list).show().html('');
if (data == 0) {
$(cl_list).show().html('<p><b>There is no</b></p>');
}
else {
$.each(data, function (a, b) {
//alert(b.name)
$('<p id="' + b.name + '">' + b.name + '</p>').appendTo(cl_list);
});
$(cl_list + ' p').click(function (e) {
e.preventDefault();
var ac = $(this).attr('id');
$('<b>' + ac + '، <input type="text" name="'+id_name+'[]" value="' + ac + '" style="border: none; display: none;" /></b>').appendTo($('.auto_box ' + specific + ' span'));
$(this).remove();
return false;
});
$('.auto_box span b').live('click', function (e) {
e.preventDefault();
$(this).remove();
return false;
});
}
if ($(specific + ' input').val() == '') {
$(cl_list + " p").hide().remove();
$(cl_list).css('display','none');
$(".list_name").show().html('');
};
$('body').click(function () {
$(cl_list + " p").hide().remove();
$('.auto_complete').val('');
$(cl_list).show().html('');
$(cl_list).css('display','none')
});
},
"error": function (x, y, z) {
// callback to run if an error occurs
alert("An error has occured:\n" + x + "\n" + y + "\n" + z);
}
});
});
});
I recommend you to use jsfiddle next time you post code examples in a link.
Nevermind. The "loading" message keeps there because there's no fallback to empty values on results.
A quick fix could be just by test that there's a value in the input before making any post like if(this.value == ""){
$(cl_list).css('display', 'none');
return false;
}
Here's how it works with it

Categories

Resources