Read CSV file with Jquery - javascript

I need to read then contents of a CSV file from the local server. In my CSV file I have three fields, those are:
Region,
Acct_Name,
State.
while getting the values in Acct_Name values are in the format of comma. In my CSV file reader it is separating comma and that value is going to state.
So how can I solve that issue?
My code is:
$(document).ready(function() {
// AJAX in the data file
$.ajax({
type: "GET",
url: "data.csv",
dataType: "text",
success: function(data) {processData(data);}
});
// Let's process the data from the data file
function processData(data) {
var table = $("<table />");
var rows = data.split(/\r\n|\n/);
for (var i = 1; i < rows.length-1; i++) {
var row = $("<tr />");
var cells = rows[i].split(",");
for (var j = 0; j < rows.length; j++) {
var cell = $("<td />");
cell.html(cells[j]);
row.append(cell);
}
var usedNames = {};
$("select[name='company1'] > option").each(function () {
if(usedNames[this.text]) {
$(this).remove();
} else {
usedNames[this.text] = this.value;
}
});
$("select[name='company2'] > option").each(function () {
if(usedNames[this.text]) {
$(this).remove();
} else {
usedNames[this.text] = this.value;
}
});
$("select[name='company3'] > option").each(function () {
if(usedNames[this.text]) {
$(this).remove();
} else {
usedNames[this.text] = this.value;
}
});
$("#region").append("<option value =1> " + cells[0] + " </option>");
$("#state").append("<option value =1> " + cells[1] + "</option>");
$("#accname").append("<option value =1>" + cells[2] + "</option>");
table.append(row);
}
}
});

Related

Javascript for loop index starting from the max number

I need a solution on how to get this solved. javascript loop function not working well in AJAX return function.
var selectedColor = '';
var selectedSize = '';
var selectedQuantity = '';
var productID = '';
var indexCount;
$('.up-cart').on('click', function() {
var cartRows = $('.cartRows').length;
for (indexCount = 0; indexCount <= cartRows; indexCount++) {
$('.myOrderSettings [name="selectedColor' + indexCount + '"]').each(function() {
if ($(this).prop("checked")) {
if (selectedColor == "") {
selectedColor += $(this).val();
} else {
selectedColor += ',' + $(this).val();
}
}
});
$('.myOrderSettings [name="selectedSize' + indexCount + '"]').each(function() {
if ($(this).prop("checked")) {
if (selectedSize == "") {
selectedSize += $(this).val();
} else {
selectedSize += ',' + $(this).val();
}
}
});
$('.myOrderSettings [name="selectedQuantity' + indexCount + '"]').each(function() {
if ($(this).val() < 1) {
selectedQuantity = '1';
alertMe("Your order quantity has been set to 1", 5000);
}
if (parseInt($(this).val()) > parseInt($(this).attr('max'))) {
selectedQuantity = $(this).attr('max');
alertMe("We have " + $(this).attr('max') + " of this product. Your order quantity has been set to " + $(this).attr('max'), 5000);
} else {
selectedQuantity = $(this).val();
}
});
productID = $('.myOrderSettings [name="productID' + indexCount + '"]').val();
$.ajax({
url: "<?php echo base_url() ?>cart/updateCart",
type: "post",
dataType: "json",
data: {
selectedColor: selectedColor,
selectedSize: selectedSize,
selectedQuantity: selectedQuantity,
productID: productID
},
success: function(data) {
console.log(indexCount);
$('.myOrderSettings .t-total' + indexCount).html(formatMoney(parseInt(data.cart_amount)));
}
});
calculateTotalAmount();
selectedColor = "";
selectedSize = "";
selectedQuantity = "";
productID = "";
}
});
The result on the console I get in console is 6 meanwhile I have a total of 5 rows. This is hindering me from returning the result to the objects respectively. Check the result in the console
I just got it solved, I noticed async wasn't set to false so here's my solution. but other solutions would be welcomed.
var selectedColor = '';
var selectedSize = '';
var selectedQuantity = '';
var productID = '';
var indexCount;
$('.up-cart').on('click', function() {
var cartRows = $('.cartRows').length;
for (indexCount = 0; indexCount <= cartRows; indexCount++) {
$('.myOrderSettings [name="selectedColor' + indexCount + '"]').each(function() {
if ($(this).prop("checked")) {
if (selectedColor == "") {
selectedColor += $(this).val();
} else {
selectedColor += ',' + $(this).val();
}
}
});
$('.myOrderSettings [name="selectedSize' + indexCount + '"]').each(function() {
if ($(this).prop("checked")) {
if (selectedSize == "") {
selectedSize += $(this).val();
} else {
selectedSize += ',' + $(this).val();
}
}
});
$('.myOrderSettings [name="selectedQuantity' + indexCount + '"]').each(function() {
if ($(this).val() < 1) {
selectedQuantity = '1';
alertMe("Your order quantity has been set to 1", 5000);
}
if (parseInt($(this).val()) > parseInt($(this).attr('max'))) {
selectedQuantity = $(this).attr('max');
alertMe("We have " + $(this).attr('max') + " of this product. Your order quantity has been set to " + $(this).attr('max'), 5000);
} else {
selectedQuantity = $(this).val();
}
});
productID = $('.myOrderSettings [name="productID' + indexCount + '"]').val();
$.ajax({
url: "<?php echo base_url() ?>cart/updateCart",
type: "post",
dataType: "json",
async: false,
data: {
selectedColor: selectedColor,
selectedSize: selectedSize,
selectedQuantity: selectedQuantity,
productID: productID
},
success: function(data) {
console.log(indexCount);
$('.myOrderSettings .t-total' + indexCount).html(formatMoney(parseInt(data.cart_amount)));
}
});
calculateTotalAmount();
selectedColor = "";
selectedSize = "";
selectedQuantity = "";
productID = "";
}
});
This is happening because you are iterating from 0 to cartRows. It needs to be 0 to one less than cartRows.
....
for (indexCount = 0; indexCount < cartRows; indexCount++) {
//Your code
}
cartRows storing length of $('.cartRows'). In Javascript .length returns number of elements present in an array. When you iterate your for loop should iterate for $('.cartRows').lenght number of times.
As you are starting index from 0 to <= $('.cartRows').length, your for loop will iterate length + 1 number of times (because of <=)

FormData content length Limitation in Jquery, Ajax When sending Large Image Files In Using Array with FormData

I have 3 Image or Multiple Images Array whose total size is approx. 29mb or above. I am try to post it on server Side using Ajax with Form data. But It shows error when i try to post large data using FormData in MVC is there any solution. when i try to post data it shows error on client side means go into the request.fail section
This is My Jquery Code
var filess = new Array();
var num = 4;
var IsAlready = false;
$(document).ready(function() {
document.getElementById('pro-image').addEventListener('change', readImage, false);
$( ".preview-images-zone" ).sortable();
$(document).on('click', '.image-cancel', function() {
debugger;
let no = $(this).data('no');
let Id = this.id;
$(".preview-image.preview-show-"+no).remove();
for (var i = 0; i < filess.length; i++) {
debugger;
filess = $.grep(filess, function(value) {
return value.name != Id;
});
}
});
});
function readImage() {
if (window.File && window.FileList && window.FileReader) {
var files = event.target.files;
var output = $(".preview-images-zone");
for (var i = 0; i < files.length; i++) {
$.grep(filess, function (n) {
if (n.name == files[i].name) {
IsAlready = true;
}
})
if (IsAlready)
{
alert("Same Name File Exist");
$("#pro-image").val('');
IsAlready = false;
return false;
}
}
var anyWindow = window.URL || window.webkitURL;
for (var i = 0; i < files.length; i++) {
filess.push(files[i]);
var file = null;
file = files[i];
if (!file.type.match('image')) continue;
var objectUrl = anyWindow.createObjectURL(files[i]);
var html = '<div class="preview-image preview-show-' + num + '" >' +
'<div class="image-cancel" data-no="' + num + '" id="' + files[i].name + '">x</div>' +
'<div class="image-zone"><img id="pro-img-' + num + '" src="' + objectUrl + '"></div>' +
'</div>';
output.append(html);
num = num + 1;
window.URL.revokeObjectURL(files[i]);
}
$("#pro-image").val('');
}
else {
console.log('Browser not support');
}
}
$("#submit").click(function () {
event.preventDefault();
debugger;
var url = "/Administration/CreateAlbum";
var albumName = $("#AlbumName").val();
var albumDescription = $("#AlbumDescription").val();
var IsActive = $("#IsActive").val();
var filess = new Array();
var data = new FormData();
data.append('albumName', albumName);
data.append('albumDescription', albumDescription);
data.append('IsActive', IsActive);
$("#submit").prop("disabled", true);
for (var i = 0; i < filess.length; i++) {
data.append('image', filess[i] );
}
var request = $.ajax({
url: url,
enctype: 'multipart/form-data',
type: 'POST',
processData: false,
contentType: false,
cache: false,
timeout: 600000,
data: data
});
request.done(function (response) {
$("#resultCode").html(response.ResultCode);
$("#resultMessage").html(response.ResultMessage);
$('#reasonCode').val("");
$('#quantity').val("");
$('#inventoryCode').val("");
$('#unitCost').val("");
});
request.fail(function (jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
});
As discussed, you need to set the maxAllowedContentLength in the web.config
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="YOUR SIZE" />
</requestFiltering>
</security>
</system.webServer>
thanks
For large file upload.
ini_set('upload_max_filesize', '10M'); ini_set('post_max_size', '10M');
your files array is blank and no need to specify enctype. Here in Ajax
var files = array();
if you have multiple files,then append like
data.append('image[]', filess[i] );
var filess = new Array();
var num = 4;
var IsAlready = false;
$(document).ready(function() {
document.getElementById('pro-image').addEventListener('change', readImage, false);
$( ".preview-images-zone" ).sortable();
$(document).on('click', '.image-cancel', function() {
debugger;
let no = $(this).data('no');
let Id = this.id;
$(".preview-image.preview-show-"+no).remove();
for (var i = 0; i < filess.length; i++) {
debugger;
filess = $.grep(filess, function(value) {
return value.name != Id;
});
}
});
});
function readImage() {
if (window.File && window.FileList && window.FileReader) {
var files = event.target.files;
var output = $(".preview-images-zone");
for (var i = 0; i < files.length; i++) {
$.grep(filess, function (n) {
if (n.name == files[i].name) {
IsAlready = true;
}
})
if (IsAlready)
{
alert("Same Name File Exist");
$("#pro-image").val('');
IsAlready = false;
return false;
}
}
var anyWindow = window.URL || window.webkitURL;
for (var i = 0; i < files.length; i++) {
filess.push(files[i]);
var file = null;
file = files[i];
if (!file.type.match('image')) continue;
var objectUrl = anyWindow.createObjectURL(files[i]);
var html = '<div class="preview-image preview-show-' + num + '" >' +
'<div class="image-cancel" data-no="' + num + '" id="' + files[i].name + '">x</div>' +
'<div class="image-zone"><img id="pro-img-' + num + '" src="' + objectUrl + '"></div>' +
'</div>';
output.append(html);
num = num + 1;
window.URL.revokeObjectURL(files[i]);
}
$("#pro-image").val('');
}
else {
console.log('Browser not support');
}
}
$("#submit").click(function () {
event.preventDefault();
debugger;
var url = "/Administration/CreateAlbum";
var albumName = $("#AlbumName").val();
var albumDescription = $("#AlbumDescription").val();
var IsActive = $("#IsActive").val();
var filess = new Array();
var data = new FormData();
data.append('albumName', albumName);
data.append('albumDescription', albumDescription);
data.append('IsActive', IsActive);
$("#submit").prop("disabled", true);
for (var i = 0; i < filess.length; i++) {
data.append('image', filess[i] );
}
var request = $.ajax({
url: url,
enctype: 'multipart/form-data',
type: 'POST',
processData: false,
contentType: false,
cache: false,
timeout: 600000,
data: data
});
request.done(function (response) {
$("#resultCode").html(response.ResultCode);
$("#resultMessage").html(response.ResultMessage);
$('#reasonCode').val("");
$('#quantity').val("");
$('#inventoryCode').val("");
$('#unitCost').val("");
});
request.fail(function (jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
});

For loop <p> tag in jquery

I need to loop using jQuery. Sometimes my query returns more than one row, so I want to check if the query returned more than one. I want to view all outputs in p tags (one by one). I wrote my code and it gives only the last row in my query. How can I return all rows in <p> tags? What is the error in my code?
<p id="prodDeccarea"> </p>
$("#slsNo").keyup(function () {
$("#hsCode").val(null);
$("#slsiUnit").val(null);
var slsNo = $("#slsNo").val();
$.ajax({
type: 'GET',
url: '${pageContext.request.contextPath}/restservice/ViewProd/' + slsNo,
success: function (result) {
var jString = JSON.stringify(result);
var jdata = JSON.parse(jString);
for (var x = 0; x < jdata.length; x++) {
if (1 < jdata.length) {
var td1 = jdata[x].itemDesc;
var td2 = jdata[x].hsCode;
var td3 = jdata[x].slsiUnit;
$("#prodDeccarea").html("Your product catagory is " + jdata[x].itemDesc + ".");
} else {
var td1 = jdata[x].itemDesc;
var td2 = jdata[x].hsCode;
var td3 = jdata[x].slsiUnit;
$("#hsCode").val(td2);
$("#prodDeccarea").html("Your product catagory is " + td1 + ".");
if (td3 == "1") {
$("#slsiUnit").val("UNIT1");
}
if (td3 == "2") {
$("#slsiUnit").val("UNIT2");
}
if (td3 == "3") {
$("#slsiUnit").val("UNIT3");
}
if (td3 == "4") {
$("#slsiUnit").val("UNIT4");
}
if (td3 == "5") {
$("#slsiUnit").val("UNIT5");
}
if (td3 == "6") {
$("#slsiUnit").val("UNIT6");
}
}
}
}
}
);
});
You have some issues in your code
Let's analyze them :-)
You're using a condition when the array jdata's length === 1 within the for-loop. Move that logic outside from the for-loop.
for (var x = 0; x < jdata.length; x++) {
if (1 < jdata.length) {
^
You're overriding the content of your previously call of function .html(...). Therefore, you're losing the previous HTML.
$("#prodDeccarea").html("Your product catagory is " + td1 + ".");
^
You're stringifying an already JSON String, just parse it.
var jString = JSON.stringify(result);
^
You have multiple conditions to set a value according to tdr3's value. Just use that value and set it to the element. I.e: $("#slsiUnit").val("UNIT" + td3);
if (td3 == "1") { <- Here
$("#slsiUnit").val("UNIT1");
}
if (td3 == "2") { <- Here, and so on
$("#slsiUnit").val("UNIT2");
}
Look at this code snippet with those fixes
$("#slsNo").keyup(function() {
$("#hsCode").val(null);
$("#slsiUnit").val(null);
var slsNo = $("#slsNo").val();
$.ajax({
type: 'GET',
url: '${pageContext.request.contextPath}/restservice/ViewProd/' + slsNo,
success: function(result) {
var jString = JSON.stringify(result);
var jdata = JSON.parse(jString);
if (jdata.length === 1) {
var td1 = jdata[0].itemDesc;
var td2 = jdata[0].hsCode;
var td3 = jdata[0].slsiUnit;
$("#hsCode").val(td2);
$("#prodDeccarea").html("Your product catagory is " + td1 + ".");
$("#slsiUnit").val("UNIT" + td3);
return;
}
for (var x = 0; x < jdata.length; x++) {
var td1 = jdata[x].itemDesc;
var td2 = jdata[x].hsCode;
var td3 = jdata[x].slsiUnit;
var $prodDeccarea = $("#prodDeccarea");
$prodDeccarea.html($prodDeccarea.html() + '<p>' + "Your product catagory is " + jdata[x].itemDesc + "." + "</p>");
}
}
});
});
$.ajax({
type: 'GET',
url: '${pageContext.request.contextPath}/restservice/ViewProd/' + slsNo,
dataType: "json",//if you return json data you don't need var jString = JSON.stringify(result);var jdata = JSON.parse(jString);
beforeSend: function () {
$("#prodDeccarea").html("");//this will clear previous results
},
success: function (data) {
$.each(data, function (i, e) {//this will loop through all the results
$("#prodDeccarea").append("<p>RESULT " + i + " : ".JSON.stringify(e));//this will add to the at the end of #prodDeccarea
});
}
});
You can use each method https://api.jquery.com/each/
$("p").each(function(element) {
console.log(element.text);
});
This will print out the contents of all p elements in your code.
guess the problem is here,you didn't accumulate;
$("#slsNo").keyup(function () {
$("#hsCode").val(null);
$("#slsiUnit").val(null);
var slsNo = $("#slsNo").val();
$.ajax({
type: 'GET',
url: '${pageContext.request.contextPath}/restservice/ViewProd/' + slsNo,
success: function (result) {
var jString = JSON.stringify(result);
var jdata = JSON.parse(jString);
for (var x = 0; x < jdata.length; x++) {
if (1 < jdata.length) {
var td1 = jdata[x].itemDesc;
var td2 = jdata[x].hsCode;
var td3 = jdata[x].slsiUnit;
//accumulate
$("#prodDeccarea").html($("#prodDeccarea").html()+"Your product catagory is " + jdata[x].itemDesc + ".");
} else {
var td1 = jdata[x].itemDesc;
var td2 = jdata[x].hsCode;
var td3 = jdata[x].slsiUnit;
$("#hsCode").val(td2);
$("#prodDeccarea").html("Your product catagory is " + td1 + ".");
if (td3 == "1") {
$("#slsiUnit").val("UNIT1");
}
if (td3 == "2") {
$("#slsiUnit").val("UNIT2");
}
if (td3 == "3") {
$("#slsiUnit").val("UNIT3");
}
if (td3 == "4") {
$("#slsiUnit").val("UNIT4");
}
if (td3 == "5") {
$("#slsiUnit").val("UNIT5");
}
if (td3 == "6") {
$("#slsiUnit").val("UNIT6");
}
}
}
}
}
);
});

localstorage multiple values

Alright, so i have textbox where I enter grades, and then they're saved in localstorage and i can see them under my textbox. But if I want to add more text boxes in which i can add more grades, and they will be saved in localstorage but they will be in another array or something how i can do that? I will be grateful for any help.
$(document).ready(function () {
var i = 0;
for (i = 0; i < localStorage.length; i++) {
var gradeID = "grade-" + i;
$('#gradeList').append("<b id='" + gradeID + "'>" + localStorage.getItem(gradeID) + "</b>, ");
}
$('#clear').click(function () {
localStorage.clear();
});
$('#gradeEntryForm').submit(function () {
if ($('#gradeInput').val() !== "") {
var gradeID = "grade-" + i;
var gradeMessage = $('#gradeInput').val();
localStorage.setItem(gradeID, gradeMessage);
$('#gradeList').append("<b class='task' id='" + gradeID + "'>" + gradeMessage + "</b>, ");
var grade = $('#' + gradeID);
task.slideDown();
$('#gradeInput').val("");
i++;
}
return false;
});
$('#gradeList').on("click", "b", function (event) {
self = $(this);
gradeID = self.attr('id');
localStorage.removeItem(gradeID);
self.remove();
});
});
DEMO
You can set dynamic id to your LocalStorage keys which you can relate to your generated TextBoxes
Something like below
localStorage['grade_' + some_id] = value;
You could use the following example:
document.getElementById("addGrade").onclick = function() {
var gradeCell = document.getElementById("gradeCell");
var input = document.createElement("input");
input.type = "number";
var br = document.createElement("br");
gradeCell.appendChild(input);
gradeCell.appendChild(br);
}
EXAMPLE

Javascript Sort Error with sort function possible simple fix

Probably a simple fix, The rest of the table is sorted excpet this part here
(right at the top)
The table will work now and again in the right order (data from source does not change) but is really dicey when it does or not
Ideas?
Sam
Heres the code
//first define a function
var sortTable = function() {
$("#tableid tbody tr").detach().sort(function(a, b) {
var dataA = $(a).find("td:eq(3)").text().trim();
var dataB = $(b).find("td:eq(3)").text().trim();
return parseFloat(dataA.substring(1)) - parseFloat(dataB.substring(
1));
}).appendTo('#tableid');
};
//include two files where rows are loaded
//1.js
$.ajax({
type: 'GET',
crossDomain: true,
dataType: 'json',
url: 'url1',
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").append("<tr ><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: 'url2',
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'>Click Here</button>";
$("#tableid").append("<tr><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);
}
});
The sorting as to do with spaces but is also linked to your jquery selector.
As often, array are 0 index based in Jquery, then if you want to sort on your price your 2nd column (0-index based) you need to do as below :
var sortTable = function() {
$("#tableid tbody tr").detach().sort(function(a, b) {
var dataA = $(a).find("td:eq(2)").text().replace(/\s/g, "");
var dataB = $(b).find("td:eq(2)").text().replace(/\s/g, "");
return parseFloat(dataA.substring(1)) - parseFloat(dataB.substring(
1));
}).appendTo('#tableid');
};
var json = {results:[{price:"$12 .45"}, {price:"$13 .45"}, {price:"$12 .05"}, ]}
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;
$("#tableid").append("<tr ><td>section</td><td>no</td><td>" + price);
}
sortTable();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="tableid"></table>
`

Categories

Resources