I'm trying to make loading appear before making a request using ajax and even then the screen is only locked.
JS:
function showEstoque(productId) {
if (url !== '' && url != '-1') {
if (active) {
hideEstoques(active);
}
var target = document.getElementById("productInfo" + productId);
target.innerHTML = generateRows(productId);
target.style.display = "block";
active = productId;
}
}
function hideEstoques(productId) {
document.getElementById("productInfo" + productId).style.display = "none";
active = null;
}
function generateRows(productId) {
var rows = '';
rows += generateRowsEstoque(productId);
rows += generateRowsReserva(productId);
return rows;
}
function generateRowsEstoque(productId) {
var textContent = searchE(productId);
var parse = JSON.parse(textContent);
var data = parse.length ? parse[0].nothing : null;
if (!data)
return '<span>Nothing</span><table><tr><td>Nothing</td></tr></table>';
var rows = '<span>Nothing</span> <table><thead> <tr> <th>Nothing</th></tr> </thead> <tbody>';
for(var n=0; n < data.length; n++) {
rows += '<tr>' +
'<td>' + data[n].nothing + '</td>' +
'</tr>';
}
rows += '</tbody> </table>';
return rows;
}
function searchE(productId) {
var view_data = "[]";
jQuery.ajax({
url: url + "product/" + productId,
type: "GET",
dataType: "text",
async: false,
success: function (response_data) {
if (response_data == undefined){
view_data=0;
return view_data;
}
view_data = response_data.replace(/\r\n/g, "");
},
error: function (xhr, textStatus, thrownError){
if(xhr.status == 404){
view_data=0;
}else{
view_data=0;
}
}
});
return view_data;
}
function generateRowsReserva(productId) {
var textContent = searchEReserva(productId);
var parse = JSON.parse(textContent);
var data = parse.length ? parse : null;
if (!data)
return '<table class="info"><tr><td class="none">Nothing</td></tr></table>';
var foo = data.filter(function(p) { return p.idType === 'foo' });
var bar = data.filter(function(p) { return p.idType === 'bar' });
var fooQtd = foo.length ? foo[0].nothing : 0;
var barQtd = bar.length ? bar[0].nothing : 0;
var rows = '<br/><table class="info"><thead> <tr class="labels"> <th>Nothing</th> </tr> </thead> <tbody>';
rows += '<tr>' +
'<td>' + fooQtd + '</td>' +
'<td>' + barQtd + '</td>' +
'</tr>';
rows += '</tbody> </table>';
return rows;
}
function searchEReserva(productId) {
var view_data = "[]";
$j.ajax({
url: "url" + productId,
type: "GET",
dataType: "text",
async: false,
success: function (response_data) {
if (response_data == undefined){
view_data=0;
return view_data;
}
view_data = response_data.replace(/\r\n/g, "");
},
error: function (xhr, textStatus, thrownError){
if(xhr.status == 404){
view_data=0;
}else{
view_data=0;
}
}
});
return view_data;
}
function startLoading(productId) {
var imgEstoqueProduto = document.getElementById("imgEstoqueProduto" + productId);
if (imgEstoqueProduto) {
imgEstoqueProduto.style.display = "";
}
}
function stopLoading(productId) {
var imgEstoqueProduto = document.getElementById("imgEstoqueProduto" + productId);
if (imgEstoqueProduto) {
imgEstoqueProduto.style.display = "none";
}
}
HTML:
<td
onclick="showEstoque(1);">
<div id="estoque_1" class="estoqueCor st-color_"/>">1</div>
<img id="imgEstoqueProduto"
style="vertical-align: middle; display: none;"
src="<c:url value="/images/ajaxLoader.gif"/>">
<div class="container-product-info">
<div onmouseout="hideEstoques(1);"
class="productInfo"
id="productInfo1"></div>
</div>
</td>
I tried to use the beforeSend, call before the ajax method starts, ajaxStart and even then it doesn't work and the screen just hangs. Could you help me please?
I called startLoading before everything and it still doesn't work
I removed async: false but, I need to wait for the data to be returned from the API
Related
I am getting rows of content via jQuery AJAX and then populating the table with new content as it is being added. The problem is that some content may be deleted from the database, in which case I also want it removed in real-time from the table.
I suspect I need to loop through the table div IDs and remove any IDs that don't exist in the AJAX response but I'm unsure how to compare them to the data response and then remove them:
function startRecords() {
$.ajax({
url: URL,
dataType: 'json',
success: function(data) {
var res = data;
for (var i = 0, len = res.length; i < len; i++) {
if ($("#records-row-" + res[i].id).length == 0) {
$("#records-content tbody").prepend('<tr class="table-wrapper" id="records-row-' + res[i].id + '"><td class"" style="">' + res[i].content_1 + '</td><td class"" style="">' + res[i].content_2 + '</td></tr>');
}
}
var delay = 3000;
setTimeout(function() {
startRecords();
}, delay);
},
cache: false
}).fail(function(jqXHR, textStatus, error) {
var delay = 3000;
setTimeout(function() {
startRecords();
}, delay);
});
}
Any recommendations on how to achieve this?
you are prepending to "records-content" div without clearing it first.
you need to add
$("#records-content tbody").html('')
before starting your for loop.
this way only current data in you database table will populate in table.
Use empty() to clear the records, before prepending new ones.
function startRecords() {
$.ajax({
url: URL,
dataType: 'json',
success: function(res) {
$("#records-content tbody").empty();
for (var i = 0, len = res.length; i < len; i++) {
if ($("#records-row-" + res[i].id).length == 0) {
$("#records-content tbody").prepend('<tr class="table-wrapper" id="records-row-' + res[i].id + '"><td class"" style="">' + res[i].content_1 + '</td><td class"" style="">' + res[i].content_2 + '</td></tr>');
}
}
var delay = 3000;
setTimeout(function() {
startRecords();
}, delay);
},
cache: false
}).fail(function(jqXHR, textStatus, error) {
var delay = 3000;
setTimeout(function() {
startRecords();
}, delay);
});
}
To remove elements that are not in the response from server.
Add the following right after success: function(res) {
var currentRows = $("[id^=records-row-]").toArray()
var currentRowsId = currentRows.map(function(row) { return row.id })
var resRows = res.map(function(row) { return "records-row-" + row.id })
var removeRows = currentRowsId.filter(function(rowId) { return resRows.indexOf(rowId) === -1 })
removeRows.forEach(function(rowId) { $("#" + rowId).remove() })
So that it looks like this
function startRecords() {
$.ajax({
url: URL,
dataType: 'json',
success: function(res) {
var currentRows = $("[id^=records-row-]").toArray()
var currentRowsId = currentRows.map(function(row) { return row.id })
var resRows = res.map(function(row) { return "records-row-" + row.id })
var removeRows = currentRowsId.filter(function(rowId) { return resRows.indexOf(rowId) === -1 })
removeRows.forEach(function(rowId) { $("#" + rowId).remove() })
for (var i = 0, len = res.length; i < len; i++) {
if ($("#records-row-" + res[i].id).length == 0) {
$("#records-content tbody").prepend('<tr class="table-wrapper" id="records-row-' + res[i].id + '"><td class"" style="">' + res[i].content_1 + '</td><td class"" style="">' + res[i].content_2 + '</td></tr>');
}
}
var delay = 3000;
setTimeout(function() {
startRecords();
}, delay);
},
cache: false
}).fail(function(jqXHR, textStatus, error) {
var delay = 3000;
setTimeout(function() {
startRecords();
}, delay);
});
}
With comments
var currentRows = $("[id^=records-row-]").toArray() // get rows with id starting with "records-row-"
var currentRowsId = currentRows.map(function(row) { return row.id }) // extract ids from rows
var resRowsId = res.map(function(row) { return "records-row-" + row.id }) // extract ids from response that will be added to DOM
var removeRows = currentRowsId.filter(function(rowId) { return resRowsId.indexOf(rowId) === -1 }) // remove every element that is added to DOM and in response from server
removeRows.forEach(function(rowId) { $("#" + rowId).remove() }) // remove elements that are not in response and is added to DOM
Alternative solution
$("#records-content tbody").empty(); to remove every element each time the client fetches new data from server.
I want to show data in a table by clicking on a searching button. I am facing issue which is that if there is no data in between "Fromdate - Todate" , error is coming properly but now after this i enter correct fromdate and todate then nothing is displaying in table. I checked chrome console data is coming from backend but not displaying in table
$('#paymentdetails').click(function() {
var getData = basePath + 'Admin/GetPaymentsForDate/?FromDate=' + $(".datepickerInputFROM").val() + '&ToDate=' + $(".datepickerInputTO").val()
if (($(".datepickerInputFROM").val() == "") && ($(".datepickerInputTO").val() == "")) {
alertify.alert('Please select dates to proceed.')
return false;
//$('#financetbl').html('');
} else if (($(".datepickerInputFROM").val() == "") || ($(".datepickerInputTO").val() == "")) {
alertify.alert('Please select dates to proceed.')
return false;
//$('#financetbl').html('');
}
$.ajax({
url: getData,
async: true,
success: function(response) {
// alert(response[0]);
$('#financetbl').html('');
// if (response.resultCourse != '' && response[0]!= 'null') {
if (response.length > 0) {
var tr;
for (var i = 0; i < response.length; i++) {
tr = '<tr>'
tr += "<td>" + response[i].applicationNumber + "</td>";
tr += "<td>" + response[i].applicantName + "</td>"
tr += '</tr>'
$('#financetbl tbody').append(tr);
}
inittable();
console.log(response)
} else {
console.log(response)
alertify.alert("Error : No Payments Details Found");
//flush the table
$('#financetbl').html('No Payments Details Found');
}
}
});
});
I believe that when you execute:
$('#financetbl').html('');
Then tbody is gone you lose your selector for:
$('#financetbl tbody').append(tr);
I think the first line should be:
$('#financetbl tbody').empty();
change
$('#financetbl').html('No Payments Details Found');
to
$('#financetbl').html('<tr><td colspan="2">No Payments Details Found</td></tr>');
You have excess if statements and need to properly manage the table when results returned are empty. So let's put that in an empty table row.
No idea what inittable(); does so you may have to fix this to account for that.
$('#paymentdetails').on('click', function() {
if (($(".datepickerInputFROM").val() == "") || ($(".datepickerInputTO").val() == "")) {
alertify.alert('Please select dates to proceed.')
return false;
}
var getData = basePath + 'Admin/GetPaymentsForDate/?FromDate=' + $(".datepickerInputFROM").val() + '&ToDate=' + $(".datepickerInputTO").val();
$.ajax({
url: getData,
async: true,
success: function(response) {
$('#financetbl').find('tbody').html('');
if (response.length > 0) {
var tr;
for (var i = 0; i < response.length; i++) {
tr = '<tr>'
tr += "<td>" + response[i].applicationNumber + "</td>";
tr += "<td>" + response[i].applicantName + "</td>"
tr += '</tr>'
$('#financetbl tbody').append(tr);
}
inittable();
console.log(response);
} else {
console.log(response);
alertify.alert("Error : No Payments Details Found");
//flush the table
$('#financetbl').find('tbody').html('<tr><td>No Payments Details Found</td></tr>');
}
}
});
});
Try something like JSON.parse()
var json = '{"applicationName":"XYZ","applicationNumber":1}',
obj = JSON.parse(json);
alert(obj.applicationName);
or
var json = '{"applicationName":"XYZ","applicationNumber":1}',
obj = JSON && JSON.parse(json) || $.parseJSON(json);
I am using table2excel.js for export HTML to Excel and it is working fine. I want to change row or column color as per condition. Is it possible?
<table id="ExcelTable" style="text-align: left;display:none">
<tr class="rpthide">
<td class="Supplier" style="font-size:14px;"></td>
<td class="ContractNo" style="font-size:14px;"></td>
<td class="OrderNo" style="font-size:14px;"></td>
<td class="Article" style="font-size:14px;"></td>
<td class="Ordered" style="font-size:14px;"></td>
<td class="ContainerNo" style="font-size:14px;"></td>
<td class="ETA" style="font-size:14px;"></td>
<td class="Dispatched" style="font-size:14px;"></td>
<td class="AtPort" style="font-size:14px;"></td>
<td class="Arrived" style="font-size:14px;"></td>
</tr>
</table>
$("#ExcelTable").table2excel({
// exclude CSS class
exclude: ".noExl",
name: "Yarn Status List",
filename: "Yarn Status List" //do not include extension
});
I suggest you use better tools like as ExcellentExport.js
you can apply any css style to the html table, and they will be exported at the output.
Sample Usage:
<script src="excellentexport.js"></script>
<table id="ExcelTable">
<tr>
<td style="color:red">Column 1</td>
<td style="color:blue">Column 2</td>
<td style="color:green; font-weight:bold">Column 3</td>
</tr>
<tr style="color: purple">
<td>400</td>
<td>500</td>
<td>600</td>
</tr>
</table>
<a download="myFile.xls" href="#" onclick="return ExcellentExport.excel(this, 'ExcelTable', 'Sheet1');">Export to Excel</a>
use span tag in td.
Ex: <td> <span style="color:red">6000</span> </td>
its work fine for me.
make preserveFont:true to use font-size and font-weight
$(function () {
$("#exportexcel").click(function () {
var $table = $('.table2excel');
$table.removeData(); //data is removed, previous when data existed was preventing initialization of table2excel
$table.table2excel({
exclude: ".noExl",
sheetName: "Demo_Report",
filename: "demo_Report",
fileext: ".xls",
preserveFont:true,
});
});
});
yes you can to change color you should use PreserveColor:true option which has given in table2excel github repo and for font-size and font-weight I have make changes in main file below Iam sharing you my table2excel raw code and PreserveFont option is made by me so you can use it .it get you fontsize and font-weight from your table
/*
* jQuery table2excel - v1.1.2
* jQuery plugin to export an .xls file in browser from an HTML table
* https://github.com/rainabba/jquery-table2excel
*
* Made by rainabba
* Under MIT License
*/
//table2excel.js
(function ($, window, document, undefined) {
var pluginName = "table2excel",
defaults = {
exclude: ".noExl",
name: "Table2Excel",
filename: "table2excel",
fileext: ".xls",
exclude_img: true,
exclude_links: true,
exclude_inputs: true,
preserveColors: false
};
// The actual plugin constructor
function Plugin(element, options) {
this.element = element;
// jQuery has an extend method which merges the contents of two or
// more objects, storing the result in the first object. The first object
// is generally empty as we don't want to alter the default options for
// future instances of the plugin
//
this.settings = $.extend({}, defaults, options);
this._defaults = defaults;
this._name = pluginName;
this.init();
}
Plugin.prototype = {
init: function () {
var e = this;
var utf8Heading = "<meta http-equiv=\"content-type\" content=\"application/vnd.ms-excel; charset=UTF-8\">";
e.template = {
head: "<html xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:x=\"urn:schemas-microsoft-com:office:excel\" xmlns=\"http://www.w3.org/TR/REC-html40\">" + utf8Heading + "<head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets>",
sheet: {
head: "<x:ExcelWorksheet><x:Name>",
tail: "</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet>"
},
mid: "</x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body>",
table: {
head: "<table>",
tail: "</table>"
},
foot: "</body></html>"
};
e.tableRows = [];
// Styling variables
var additionalStyles = "";
var compStyle = null;
// get contents of table except for exclude
$(e.element).each(function (i, o) {
var tempRows = "";
$(o).find("tr").not(e.settings.exclude).each(function (i, p) {
// Reset for this row
additionalStyles = "";
// Preserve background and text colors on the row
if (e.settings.preserveColors) {
compStyle = getComputedStyle(p);
additionalStyles += (compStyle && compStyle.backgroundColor ? "background-color: " + compStyle.backgroundColor + ";" : "");
additionalStyles += (compStyle && compStyle.color ? "color: " + compStyle.color + ";" : "");
}
// Create HTML for Row
tempRows += "<tr style='" + additionalStyles + "'>";
// Loop through each TH and TD
$(p).find("td,th").not(e.settings.exclude).each(function (i, q) { // p did not exist, I corrected
// Reset for this column
additionalStyles = "";
// Preserve background and text colors on the row
if (e.settings.preserveColors) {
compStyle = getComputedStyle(q);
additionalStyles += (compStyle && compStyle.backgroundColor ? "background-color: " + compStyle.backgroundColor + ";" : "");
additionalStyles += (compStyle && compStyle.color ? "color: " + compStyle.color + ";" : "");
}
if (e.settings.preserveFont) {
compStyle = getComputedStyle(q);
additionalStyles += (compStyle && compStyle.fontSize ? "font-size : " + compStyle.fontSize + ";" : "");
additionalStyles += (compStyle && compStyle.fontWeight ? "font-weight : " + compStyle.fontWeight + ";" : "");
}
var rc = {
rows: $(this).attr("rowspan"),
cols: $(this).attr("colspan"),
flag: $(q).find(e.settings.exclude)
};
if (rc.flag.length > 0) {
tempRows += "<td> </td>"; // exclude it!!
} else {
tempRows += "<td";
if (rc.rows > 0) {
tempRows += " rowspan='" + rc.rows + "' ";
}
if (rc.cols > 0) {
tempRows += " colspan='" + rc.cols + "' ";
}
if (additionalStyles) {
tempRows += " style='" + additionalStyles + "'";
}
tempRows += ">" + $(q).html() + "</td>";
}
});
tempRows += "</tr>";
});
// exclude img tags
if (e.settings.exclude_img) {
tempRows = exclude_img(tempRows);
}
// exclude link tags
if (e.settings.exclude_links) {
tempRows = exclude_links(tempRows);
}
// exclude input tags
if (e.settings.exclude_inputs) {
tempRows = exclude_inputs(tempRows);
}
e.tableRows.push(tempRows);
});
e.tableToExcel(e.tableRows, e.settings.name, e.settings.sheetName);
},
tableToExcel: function (table, name, sheetName) {
var e = this, fullTemplate = "", i, link, a;
e.format = function (s, c) {
return s.replace(/{(\w+)}/g, function (m, p) {
return c[p];
});
};
sheetName = typeof sheetName === "undefined" ? "Sheet" : sheetName;
e.ctx = {
worksheet: name || "Worksheet",
table: table,
sheetName: sheetName
};
fullTemplate = e.template.head;
if ($.isArray(table)) {
Object.keys(table).forEach(function (i) {
//fullTemplate += e.template.sheet.head + "{worksheet" + i + "}" + e.template.sheet.tail;
fullTemplate += e.template.sheet.head + sheetName + i + e.template.sheet.tail;
});
}
fullTemplate += e.template.mid;
if ($.isArray(table)) {
Object.keys(table).forEach(function (i) {
fullTemplate += e.template.table.head + "{table" + i + "}" + e.template.table.tail;
});
}
fullTemplate += e.template.foot;
for (i in table) {
e.ctx["table" + i] = table[i];
}
delete e.ctx.table;
var isIE = navigator.appVersion.indexOf("MSIE 10") !== -1 || (navigator.userAgent.indexOf("Trident") !== -1 && navigator.userAgent.indexOf("rv:11") !== -1); // this works with IE10 and IE11 both :)
//if (typeof msie !== "undefined" && msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) // this works ONLY with IE 11!!!
if (isIE) {
if (typeof Blob !== "undefined") {
//use blobs if we can
fullTemplate = e.format(fullTemplate, e.ctx); // with this, works with IE
fullTemplate = [fullTemplate];
//convert to array
var blob1 = new Blob(fullTemplate, { type: "text/html" });
window.navigator.msSaveBlob(blob1, getFileName(e.settings));
} else {
//otherwise use the iframe and save
//requires a blank iframe on page called txtArea1
txtArea1.document.open("text/html", "replace");
txtArea1.document.write(e.format(fullTemplate, e.ctx));
txtArea1.document.close();
txtArea1.focus();
sa = txtArea1.document.execCommand("SaveAs", true, getFileName(e.settings));
}
} else {
var blob = new Blob([e.format(fullTemplate, e.ctx)], { type: "application/vnd.ms-excel" });
window.URL = window.URL || window.webkitURL;
link = window.URL.createObjectURL(blob);
a = document.createElement("a");
a.download = getFileName(e.settings);
a.href = link;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
return true;
}
};
function getFileName(settings) {
return (settings.filename ? settings.filename : "table2excel");
}
// Removes all img tags
function exclude_img(string) {
var _patt = /(\s+alt\s*=\s*"([^"]*)"|\s+alt\s*=\s*'([^']*)')/i;
return string.replace(/<img[^>]*>/gi, function myFunction(x) {
var res = _patt.exec(x);
if (res !== null && res.length >= 2) {
return res[2];
} else {
return "";
}
});
}
// Removes all link tags
function exclude_links(string) {
return string.replace(/<a[^>]*>|<\/a>/gi, "");
}
// Removes input params
function exclude_inputs(string) {
var _patt = /(\s+value\s*=\s*"([^"]*)"|\s+value\s*=\s*'([^']*)')/i;
return string.replace(/<input[^>]*>|<\/input>/gi, function myFunction(x) {
var res = _patt.exec(x);
if (res !== null && res.length >= 2) {
return res[2];
} else {
return "";
}
});
}
$.fn[pluginName] = function (options) {
var e = this;
e.each(function () {
if (!$.data(e, "plugin_" + pluginName)) {
$.data(e, "plugin_" + pluginName, new Plugin(this, options));
}
});
// chain jQuery functions
return e;
};
})(jQuery, window, document);
I want to display image from my database which stores the path to the image's location. Following code gives me the image path only in the output. What changes do I need to make in order for image to appear instead of image path?
GetBusinessCategoryList: function () {
debugger;
var data = JSON2.stringify({
});
$.ajax(
{
contentType: "application/json; charset=utf-8",
type: 'POST',
url: 'http://localhost:44719/Modules/BusinessCategoryView/Service/BusinessCategoryWebService.asmx/GetAllBusinessCategory',
dataType: 'json',
data: data,
success: function (result) {
alert("ok");
var returnedData = result;
BusinessManagement.BindBusinessCategoryList(returnedData);
},
error: function (error) {
alert("error");
}
});
},
BindBusinessCategoryList: function (data) {
debugger;
var cLst = data.d;
if (cLst.length > 0) {
headElements += '<table id="customerTable" cellspacing="0" cellpadding="0" >';
headElements += '<thead class="sfHeadingone">';
headElements += '<tr><th align="left">Category Image</th>';
;
headElements += '</thead>';
$('#tblGrid').html(headElements);
var i = 0;
if (i === 0) {
bodyElements += '<tbody>';
}
$.each(cLst, function (index, value) {
bodyElements += "<td>" + value.CategoryImage + "</td>";
}
});
Use img to display an image. Pass the image url to the src attribute of the img tag
bodyElements += "<td><img src='" + value.CategoryImage + "'></td>";
Hi I am getting an error while implementing the following.
When I click on the "save" button in following code:
<td width="20%"> <input id="save" onClick="updateMouseInfo();" type="button" value="Save" /></td>
I want to call the mouse_id parameter from getMouseInfo() function to updateMouseInfo() and I am getting the error that mouse_id is undefined, so please help me with the solution.
function getMouseInfo(mouse_id)
{
var dataString = {auth_token: sessionStorage.auth_token, id: mouse_id};
var mh_url = MH_HOST + '/mice/get_mouse_info.json';
alert("Inside Mouse Get Info");
$.ajax(
{
type: "POST",
url: mh_url,
data: dataString,
dataType: "json",
success: function (data)
{
//for (var info_count = 0, info_len = data.length; info_count < info_len; info_count++ );
//{
alert("Inside for loop");
//var mouse_info = data.cage.mice[info_count];
var ear_tag = document.getElementById("ear_tag");
var age = document.getElementById("age");
var genotype = document.getElementById("genotype");
var owner = document.getElementById("owner");
//var born = document.getElementById("born");
//var euthanize = document.getElementById("euthanize");
//var note = document.getElementById("note");
ear_tag.innerHTML = data[0].ear_tag;
age.innerHTML = data[0].age;
genotype.innerHTML = data[0].genotype_id;
owner.innerHTML = data[0].owner_id;
//born.innerHTML = data[0].dob;
//euthanize.innerHTML = data[0].dob;
//note.innerHTML = data[0].dob;
//}
},
error: function (data)
{
alert("fail");
}
});
}
//update mouse info
function updateMouseInfo(mouseid)
{
var ear_tag = $('#input_ear_tag').val();
var age = $('#input_age').val();
var genotype = $('#input_genotype').val();
var owner = $('#input_owner').val();
var dataString = {auth_token: sessionStorage.auth_token, id: mouseid, mouse:
{ear_tag: ear_tag, age: age,}};
var mh_url = MH_HOST + '/mice/update.json';
alert("Inside Mouse update Info");
console.log('Data String='+ dataString.auth_token + 'Mouse id=' + dataString.id);
$.ajax(
{
type: "POST",
url: mh_url,
data: dataString,
dataType: "json",
success: function (data)
{
document.getElementById('ear_tag').innerHTML = "<div" + ear_tag + "'>" + ear_tag + "</div>";
document.getElementById('age').innerHTML = "<div" + age + "'>" + age + "</div>";
document.getElementById('genotype').innerHTML = "<div" + genotype + "'>" + genotype + "</div>";
document.getElementById('owner').innerHTML = "<div" + owner + "'>" + owner + "</div>";
},
error: function (data)
{
alert("fail");
}
});
}
I am getting the following error in the browser console.
m_id=99
Data String=pvHxzkr3cys1gEVJRpCDMouse id=undefined
Whereas the id should be 99 in the above case it is showing undefined.
You are calling the updateMouseInfo function in the following manner:
onClick="updateMouseInfo();"
if you want to have same mouseid value which is taken by getMouseInfo() function when you call updateMouseInfo(),you will have to globalize getMouseInfo()
Hope it works.