简体   繁体   中英

On function Call getting error as Variable is not defined

I have an HTML table which i am creating with Json Data.I have Three buttons inside my form save , View and Edit edit is initially hidden on clicking on view it shows up.

so on clicking view i am calling a function which is doing some work, then again i am clicking on edit and i am calling my addTable(tableData) function it says un defined

 $(document).ready(function() { $('.loader').show(); $('.overlay').show(); $.ajax({ url: "CategoryOlWiseFilter", method: "GET", dataType: "json", contentType: "application/json; charset=utf-8", success: function(tableData) { addTable(tableData); $('.loader').hide(); $('.overlay').hide(); $("#divHide").show(); } }); $("#clear").click(function() { if (confirm("Want to clear?")) { $('.dataReset').val(0); } return false; }); $("#CategoryName").on("change", function() { var selectedOption = this.value; console.log(selectedOption); var itemRows = document.getElementsByClassName("item-row"); if (selectedOption === "All") { for (var i = 0; i < itemRows.length; i++) { itemRows[i].style.visibility = "visible"; } } else { for (var i = 0; i < itemRows.length; i++) { itemRows[i].style.visibility = "collapse"; } var selectedItemRows = document.querySelectorAll("[data-category='" + selectedOption + "']"); for (var i = 0; i < selectedItemRows.length; i++) { selectedItemRows[i].style.visibility = "visible"; } } }); }); var itemsQuantiry = []; function addTable(tableData) { var col = Object.keys(tableData[0]); var countNum = col.filter(i => !isNaN(i)).length; var num = col.splice(0, countNum); col = col.concat(num); var table = document.createElement("table"); var tr = table.insertRow(-1); var colNum = col.length; for (var i = 0; i < colNum + 1; i++) { var th = document.createElement("th"); if (i >= colNum) { th.innerHTML = "Quantity"; tr.appendChild(th); tr.classList.add("text-center"); tr.classList.add("head"); } else { th.innerHTML = col[i]; tr.appendChild(th); tr.classList.add("text-center"); tr.classList.add("head"); } } for (var i = 0; i < tableData.length; i++) { tr = table.insertRow(-1); tr.classList.add("item-row"); for (var j = 0; j < col.length + 1; j++) { var categoryName = tableData[i]["Category Name"]; tr.dataset.category = categoryName; let tabCell = tr.insertCell(-1); var hiddenField = document.createElement("input"); hiddenField.style.display = "none"; var quantityField = document.createElement("input"); var tabledata = tableData[i][col[j]]; if (i > -1 && j >= colNum) { quantityField.style.border = "none"; quantityField.style["text-align"] = "right"; quantityField.setAttribute("name", "Quantity"); quantityField.setAttribute("autocomplete", "on"); if (itemsQuantiry[i]) { quantityField.setAttribute("value", itemsQuantiry[i]); } else { quantityField.setAttribute("value", "0"); } quantityField.setAttribute("index", i); quantityField.setAttribute("type", "number"); quantityField.setAttribute("required", "required"); quantityField.classList.add("dataReset"); quantityField.toLocaleString('en-IN'); tabCell.appendChild(quantityField); } else { if (tableData[i]["Item Code"] === tableData[i][col[j]]) { tabCell.innerHTML = tabledata; hiddenField.setAttribute("name", "Item_Code"); hiddenField.setAttribute("value", tabledata); tabCell.appendChild(hiddenField); } if (tableData[i]["Item Name"] === tableData[i][col[j]]) { tabCell.innerHTML = tabledata; hiddenField.setAttribute("name", "Item_Name"); hiddenField.setAttribute("value", tabledata); tabCell.appendChild(hiddenField); } if (tableData[i]["Category Name"] === tableData[i][col[j]]) { tabCell.innerHTML = tabledata; hiddenField.setAttribute("name", "Category_Name"); hiddenField.setAttribute("value", tabledata); tabCell.appendChild(hiddenField); } if (j > 1) tabCell.classList.add("text-right"); } } } var divContainer = document.getElementById("HourlysalesSummary"); divContainer.innerHTML = ""; divContainer.appendChild(table); table.classList.add("table"); table.classList.add("table-striped"); table.classList.add("table-bordered"); table.classList.add("table-hover"); } function editData() { $('#CategoryName').val('All'); $('#view').show(); $('#edit').hide(); addTable(tableData); // here i am getting the error } $(".dataReset").on("change", function(e) { itemsQuantiry[$(this).attr('index')] = e.target.value; }); $("#save").click(function() { var outlet = $('#outlet'); if (outlet.val() === 'Select Outlet') { alert("Please Select An Outlet!"); $('#outlet').focus(); return false; } else return; }); function viewData() { var quantityFields = document.getElementsByClassName("dataReset"); for (var i = 0; i < quantityFields.length; i++) { if (quantityFields[i].value != 0) { quantityFields[i].closest(".item-row").style.visibility = "visible"; } else { quantityFields[i].closest(".item-row").style.display = "none"; } } $('#CategoryName').val('All'); $('#view').hide(); $('#edit').show(); } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css"> <div class="container" id="divHide"> <form action="InsertQuantityIndent" method="post" id="indentForm" autocomplete="on"> <div class="row position-relative"> <div class="col-lg-4 brder"> <h5 id="commonHeader">Outlet Name</h5> <select class="test" id="outlet" name="outlet"> <option>Select Outlet</option> </select> </div> <div class="col-lg-4"> <h5 id="commonHeader">Outlet Code</h5> <select class="test" id="outletCode" name="outletCode"> <option>Outlet Code</option> </select> </div> <div class="col-lg-4"> <h5 id="commonHeader">Category</h5> <select class="test" id="CategoryName" name="categoryCode"> <option>All</option> </select> </div> </div> <hr style="border: 1px solid black"> <div class="table-responsive"> <table class="w-100" id=HourlysalesSummary></table> </div> <div> <button type="submit" id="save" class="commonButton"> <i class="fas fa-save"></i> Save </button> <button type="button" id="view" class="commonButton" onclick="viewData()"> <i class="fas fa-eye"></i> View </button> <button id="edit" type="button" class="commonButton" onclick="editData()" style="display: none"> <i class="far fa-edit"></i>edit </button> </div> </form> </div> 

initially when page loads i am making an ajax call and populating the table in side success function i am calling addTable(tableData) function

  • then user clicks on view and again clicks on edit it shows error as ReferenceError: tableData is not defined as you can see in my code i have commented that line
  • I think it is not able to find tableData
  • So where should i put my editdata function
  • I think i am misplacing the code pattern

On clicking of edit you can see it shows the error on console

The JSON i am getting from back-end.value of tableData

[{"Item Code":"1978","Item Name":"Alu Chat-S","Category Name":"Chats"},{"Item Code":"1979","Item Name":"Dahi Alu Chat-S","Category Name":"Chats"},{"Item Code":"1980","Item Name":"Samosa-S","Category Name":"Chats"},{"Item Code":"1981","Item Name":"SamosaChat-S","Category Name":"Chats"},{"Item Code":"1982","Item Name":"Dahi Samosa Chats-S","Category Name":"regular"},{"Item Code":"1983","Item Name":"Garam Samosa Chats-S","Category Name":"regular"},{"Item Code":"1984","Item Name":"Kachori Chats-S","Category Name":"regular"},{"Item Code":"1985","Item Name":"Garam Kachori Chat-S","Category Name":"regular"},{"Item Code":"1986","Item Name":"Dahi Kachori Chat-S","Category Name":"fastfood"},{"Item Code":"1987","Item Name":"Dai Raj Kachori-S","Category Name":"fastfood"},{"Item Code":"1988","Item Name":"Baby Kachori Chat-S","Category Name":"fastfood"},{"Item Code":"1989","Item Name":"Dahi Baby Kachori-S","Category Name":"fastfood"},{"Item Code":"1990","Item Name":"Anar Bhalla-S","Category Name":"fastfood"},{"Item Code":"1991","Item Name":"Dahi Bhalla-S","Category Name":"fastfood"},{"Item Code":"1992","Item Name":"Jhal Muri-S","Category Name":"fastfood"},{"Item Code":"1993","Item Name":"Chat Platter-S","Category Name":"fastfood"},{"Item Code":"1994","Item Name":"Dahi Papdi Chat-S","Category Name":"GIFT PACK"}]

Yes that would be of course undefined as you did not declare variable tableData inside edit function

You can get data of table by table id for reference check this Get data of table by table id

Now you need to modify edit function like this

function editData() {
   var tableData = document.getElementById("myTable").rows
   $('#CategoryName').val('All');
   $('#view').show();
   $('#edit').hide();
   addTable(tableData); // here i am getting the error

}

Let me know if id did not work or you need more help

Your problem is tableData falls in the scope of the Ajax call with line:

success: function(tableData) {

You can make it available but assigning it to a variable outside this scope, to the same scope as editData eg:

var returned_data;
$(document).ready(function() {

And then updating your success function in your ajax:

 success: function(tableData) {
      addTable(tableData);
      returned_data = tableData;

It can then be called in in editData

function editData() {
  $('#CategoryName').val('All');
  $('#view').show();
  $('#edit').hide();
  addTable(returned_data); // here i am getting the error

}

editdata function has not access to tableData and that's why it makes error.

You can define tableData variable in outer scope and after ajax call assign value to that:

var tableData;
$(document).ready(function() {
...
success: function(tableDataResponse) {
      tableData = tableDataResponse;  // assign value to our global variable
      addTable(tableData);
...

Now editData has access to tableData .

Hope to help.

 <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script> </head> <body> <div class="container" id="divHide"> <form action="InsertQuantityIndent" method="post" id="indentForm" autocomplete="on"> <div class="row position-relative"> <div class="col-lg-4 brder"> <h5 id="commonHeader">Outlet Name</h5> <select class="test" id="outlet" name="outlet"> <option>Select Outlet</option> </select> </div> <div class="col-lg-4"> <h5 id="commonHeader">Outlet Code</h5> <select class="test" id="outletCode" name="outletCode"> <option>Outlet Code</option> </select> </div> <div class="col-lg-4"> <h5 id="commonHeader">Category</h5> <select class="test" id="CategoryName" name="categoryCode"> <option>All</option> </select> </div> </div> <hr style="border: 1px solid black"> <div class="table-responsive"> <table class="w-100" id=HourlysalesSummary></table> </div> <div> <button type="submit" id="save" class="commonButton"> <i class="fas fa-save"></i> Save </button> <button type="button" id="view" class="commonButton" onclick="viewData()"> <i class="fas fa-eye"></i> View </button> <button id="edit" type="button" class="commonButton" onclick="editData()" style="display: none"> <i class="far fa-edit"></i>edit </button> </div> </form> </div> </body> <script> var tableData = [{"Item Code":"1978","Item Name":"Alu Chat-S","Category Name":"Chats"},{"Item Code":"1979","Item Name":"Dahi Alu Chat-S","Category Name":"Chats"},{"Item Code":"1980","Item Name":"Samosa-S","Category Name":"Chats"},{"Item Code":"1981","Item Name":"SamosaChat-S","Category Name":"Chats"},{"Item Code":"1982","Item Name":"Dahi Samosa Chats-S","Category Name":"regular"},{"Item Code":"1983","Item Name":"Garam Samosa Chats-S","Category Name":"regular"},{"Item Code":"1984","Item Name":"Kachori Chats-S","Category Name":"regular"},{"Item Code":"1985","Item Name":"Garam Kachori Chat-S","Category Name":"regular"},{"Item Code":"1986","Item Name":"Dahi Kachori Chat-S","Category Name":"fastfood"},{"Item Code":"1987","Item Name":"Dai Raj Kachori-S","Category Name":"fastfood"},{"Item Code":"1988","Item Name":"Baby Kachori Chat-S","Category Name":"fastfood"},{"Item Code":"1989","Item Name":"Dahi Baby Kachori-S","Category Name":"fastfood"},{"Item Code":"1990","Item Name":"Anar Bhalla-S","Category Name":"fastfood"},{"Item Code":"1991","Item Name":"Dahi Bhalla-S","Category Name":"fastfood"},{"Item Code":"1992","Item Name":"Jhal Muri-S","Category Name":"fastfood"},{"Item Code":"1993","Item Name":"Chat Platter-S","Category Name":"fastfood"},{"Item Code":"1994","Item Name":"Dahi Papdi Chat-S","Category Name":"GIFT PACK"}]; $(document).ready(function() { $('.loader').show(); $('.overlay').show(); $.ajax({ url: "CategoryOlWiseFilter", method: "GET", dataType: "json", contentType: "application/json; charset=utf-8", success: function(data) { tableData = data; console.log(tableData); addTable(tableData); $('.loader').hide(); $('.overlay').hide(); $("#divHide").show(); } }); $("#clear").click(function() { if (confirm("Want to clear?")) { $('.dataReset').val(0); } return false; }); $("#CategoryName").on("change", function() { var selectedOption = this.value; console.log(selectedOption); var itemRows = document.getElementsByClassName("item-row"); if (selectedOption === "All") { for (var i = 0; i < itemRows.length; i++) { itemRows[i].style.visibility = "visible"; } } else { for (var i = 0; i < itemRows.length; i++) { itemRows[i].style.visibility = "collapse"; } var selectedItemRows = document.querySelectorAll("[data-category='" + selectedOption + "']"); for (var i = 0; i < selectedItemRows.length; i++) { selectedItemRows[i].style.visibility = "visible"; } } }); }); var itemsQuantiry = []; function addTable(tableData) { console.log(1); var col = Object.keys(tableData[0]); var countNum = col.filter(i => !isNaN(i)).length; var num = col.splice(0, countNum); col = col.concat(num); var table = document.createElement("table"); var tr = table.insertRow(-1); var colNum = col.length; for (var i = 0; i < colNum + 1; i++) { var th = document.createElement("th"); if (i >= colNum) { th.innerHTML = "Quantity"; tr.appendChild(th); tr.classList.add("text-center"); tr.classList.add("head"); } else { th.innerHTML = col[i]; tr.appendChild(th); tr.classList.add("text-center"); tr.classList.add("head"); } } for (var i = 0; i < tableData.length; i++) { tr = table.insertRow(-1); tr.classList.add("item-row"); for (var j = 0; j < col.length + 1; j++) { var categoryName = tableData[i]["Category Name"]; tr.dataset.category = categoryName; let tabCell = tr.insertCell(-1); var hiddenField = document.createElement("input"); hiddenField.style.display = "none"; var quantityField = document.createElement("input"); var tabledata = tableData[i][col[j]]; if (i > -1 && j >= colNum) { quantityField.style.border = "none"; quantityField.style["text-align"] = "right"; quantityField.setAttribute("name", "Quantity"); quantityField.setAttribute("autocomplete", "on"); if (itemsQuantiry[i]) { quantityField.setAttribute("value", itemsQuantiry[i]); } else { quantityField.setAttribute("value", "0"); } quantityField.setAttribute("index", i); quantityField.setAttribute("type", "number"); quantityField.setAttribute("required", "required"); quantityField.classList.add("dataReset"); quantityField.toLocaleString('en-IN'); tabCell.appendChild(quantityField); } else { if (tableData[i]["Item Code"] === tableData[i][col[j]]) { tabCell.innerHTML = tabledata; hiddenField.setAttribute("name", "Item_Code"); hiddenField.setAttribute("value", tabledata); tabCell.appendChild(hiddenField); } if (tableData[i]["Item Name"] === tableData[i][col[j]]) { tabCell.innerHTML = tabledata; hiddenField.setAttribute("name", "Item_Name"); hiddenField.setAttribute("value", tabledata); tabCell.appendChild(hiddenField); } if (tableData[i]["Category Name"] === tableData[i][col[j]]) { tabCell.innerHTML = tabledata; hiddenField.setAttribute("name", "Category_Name"); hiddenField.setAttribute("value", tabledata); tabCell.appendChild(hiddenField); } if (j > 1) tabCell.classList.add("text-right"); } } } var divContainer = document.getElementById("HourlysalesSummary"); divContainer.innerHTML = ""; divContainer.appendChild(table); table.classList.add("table"); table.classList.add("table-striped"); table.classList.add("table-bordered"); table.classList.add("table-hover"); } function editData() { $('#CategoryName').val('All'); $('#view').show(); $('#edit').hide(); if (typeof tableData != 'undefined' && tableData != '') { alert('before edit'); addTable(tableData); }// here i am getting the error } $(".dataReset").on("change", function(e) { itemsQuantiry[$(this).attr('index')] = e.target.value; }); $("#save").click(function() { var outlet = $('#outlet'); if (outlet.val() === 'Select Outlet') { alert("Please Select An Outlet!"); $('#outlet').focus(); return false; } else return; }); function viewData() { var quantityFields = document.getElementsByClassName("dataReset"); for (var i = 0; i < quantityFields.length; i++) { if (quantityFields[i].value != 0) { quantityFields[i].closest(".item-row").style.visibility = "visible"; } else { quantityFields[i].closest(".item-row").style.display = "none"; } } $('#CategoryName').val('All'); $('#view').hide(); $('#edit').show(); } </script> </html> 

Yes tableData is not defined and you are using it from out of scope.For this you need to declared it inside document ready and assign success response in that.For avoiding error you have to implement undefined and not empty check.Please see below code:-

$(document).ready(function() {
 $('.loader').show();
 $('.overlay').show();
 var tableData = '';

After success call assign value to tableData you should also handle failure response as your api returning 404.

success: function(data) {
tableData = data;
addTable(tableData);

Inside editData function handle this

function editData() {
 $('#CategoryName').val('All');
 $('#view').show();
 $('#edit').hide();
 if (typeof tableData != 'undefined' && tableData != '') {
  addTable(tableData);
 }// here i am getting the error

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM