I am using the following code to pull in data from my database and plot points with google maps. What I want to do is something like, "if response=null, alert('empty')" but everytime I try to work that into this code, something just breaks. If anyone could offer any help that would be awesome.
Here is my code:
<script type="text/javascript">
$(function ()
{
var radius3 = localStorage.getItem("radius2");
var lat3 = localStorage.getItem("lat2");
var long3 = localStorage.getItem("long2");
var type2 = localStorage.getItem("type2");
var citya = localStorage.getItem("city2");
var rep2 = localStorage.getItem("rep2");
var size2 = localStorage.getItem("size2");
var status2 = localStorage.getItem("status2");
$.ajax({
url: 'http://examplecom/test/www/base_search.php',
data: "city2=" + city2 + "&rep2=" + rep2 + "&status2=" + status2 + "&size2=" + size2 + "&type2=" + type2 + "&long2=" + long2 + "&lat2=" + lat2 + "&radius2=" + radius2,
type: 'post',
dataType: 'json',
success: function (data) {
if (data) {
$.each(data, function (key, val) {
var lng = val['lng'];
var lat = val['lat'];
var id = val['id'];
var name = val['name'];
var address = val['address'];
var category = val['category'];
var city = val['city'];
var state = val['state'];
var rep = val['rep'];
var status = val['status'];
var size = val['size'];
$('div#google-map').gmap('addMarker', {
'position': new google.maps.LatLng(lat, lng),
'bounds': true,
'icon': 'images/hospital.png'
}).click(function () {
$('div#google-map').gmap('openInfoWindow', {
'backgroundColor': "rgb(32,32,32)",
'content': "<table><tr><td>Name:</td><td>" + name + "</td></tr><tr><td>Address:</td><td>" + address + ", " + city + " " + state + "</td></tr><tr><td>Category:</td><td>" + category + "</td></tr><tr><td>Rep:</td><td>" + rep + "</td></tr><tr><td>Status:</td><td>" + status + "</td></tr><tr><td>Size:</td><td>" + size + "</td></tr></table>"
}, this);
});
} else {
alert('hello');
}
}
})
}
});
})
}
</script>
Something like
success: function (data) {
if(!data) {
alert('empty');
return;
}
$.each(data, function (key, val) { ...
should work.
Something like this!
success: function (data) {
if(data.length == 0) {
alert('empty');
return;
}
Something like this?
success: function (data) {
if(data){
//do your stuff here
}
else{
alert('empty');
}
}
Related
I am working on a MVC4 C#.Net project and when I am trying to
click the button ('#btn_rightArw_Dwn') then the ajax call fires multiple times in MVC4. Why this is happening? Please look up on below jQuery code.
Below I have added jQuery code.
$("#btn_rightArw_Dwn").click(function() {
$('.fade_bg').show();
var Masterid = $('#MastersId').val();
var pgm_id = $('#program1').val();
if ($('#rdclick').val() == "0") {
$.ajax({
url: "/DataInput/Arrow_Load_Down?Id=" + Masterid + "&flag=" + "Right" + "&type=" + 0 + "&pgm_id=" + pgm_id,
async: true,
data: {},
success: function(data) {
$('#DVmaster').html(data);
$('#btn_rightArw1').attr('hidden', false);
$('#btn_LeftArw1').attr('hidden', false);
var production_id = $('#program1').val();
$.ajax({
url: "/DataInput/Arrow_Load_Details_Down?Id=" + Masterid + "&flag=" + "Right" + "&ProductnSts_id=" + pgm_id + "&type=" + 0,
async: false,
data: {},
success: function(data) {
$('#DVDetails').html(data);
$('#DVDetails').show();
$('#btn_rightArw_Dwn').attr('hidden', false);
$('#btn_LeftArw_dwn').attr('hidden', false);
},
error: function(html) {
$('.fade_bg').hide();
}
});
var channelid = $("#channel1").val();
var starttime = $("#StartTime").val();
var Endtime = $("#EndTime").val();
var date = $("#Date").val();
var Vimpact = $("#Viewers").val();
var gradeid = $("#grade1").val();
var seclength = $("#Seconds option:selected").text();
var Daypartid = $('#daypartid').val();
var itemid = $('#item1 option:selected').val();
var brandid = $("#brand1 option:selected").val();
$.ajax({
url: "/DataInput/Print_Labels_in_Edit?starttime=" + starttime + "&finishtime=" + Endtime + "&date=" + date + "&channelid=" + channelid + "&impact1=" + Vimpact + "&Seclength=" + seclength + "&gradesid=" + gradeid + "&itemid=" + itemid + "&brandid=" + brandid,
cache: false,
success: function(html) {
var labels = html.split(',');
var daypartname = labels[0];
var CPH = labels[1];
var TVR = labels[2];
var Mediavalue = labels[3];
var daypartid = labels[4];
$('.fade_bg').hide();
$('#lblDaypart').text(" " + daypartname);
$("#lblCPH").text('£' + " " + CPH);
$('#lblTvr').text(" " + TVR);
$('#lblMediaValue').text(" " + "£ " + Mediavalue);
$('#daypartid').val(daypartid);
},
error: function(html) {
$('.fade_bg').hide();
}
});
}
});
}
});
Thanks in advance.
I am trying to pass a value from Javascript to ASP pages. But it can't run properly.
This is my Javscript:
function btn_upgrade_onclick() {
var dlr = document.getElementById("<%txt_sapcode.ClientID%>").value;
var dlrname = document.getElementById('<%=tex_dealername.ClientID %>').value;
var addr1 = document.getElementById('<%=txt_addr1.ClientID %>').value;
var addr2 = document.getElementById('<%=txt_addr2.ClientID %>').value;
var addr3 = document.getElementById('<%=txt_addr3.ClientID %>').value;
var mobno = document.getElementById('<%=txt_mob.ClientID %>').value;
var stat = document.getElementById('drp_state').value;
$.ajax({
async: false,
type: "POST",
url: "DealerDetails.aspx/UpdateDealer",
data: "{DlrId:'" + dealerID + "',DlrCode:'" + dlr + "',DlrName:'" + dlrname + "',Dlrad1:'" + addr1 + "',Dlrad2:'" + addr2 + "',Dlrad3:'" + addr3 + "',DlrMob:'" + mobno + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$("#drp_support").get(0).options.length = 0;
$("#drp_support").get(0).options[0] = new Option("--Select--", "0");
$("#drp_support").unbind("change");
$.each(msg.d, function (index, item) {
$("#drp_support").get(0).options[$("#drp_support").get(0).options.length] = new Option(item.Display, item.Value);
});
$("#drp_support").bind("change", function () {
sprtengId = $(this).val();
});
},
error: function () {
alert("Error");
}
});
}
And the value are passed to the function
region update
[WebMethod]
public static DataSet UpdateDealer(Int32 DlrId,Int32 DlrCode,string DlrName,string Dlrad1,string Dlrad2,string Dlrad3,Int16 Dlrddd,Int32 DlrLan,Int32 DlrMob)
{
DataSet update = new DataSet();
try
{
update=obj.UpdateDealerDetails(DlrId,DlrCode,DlrName,Dlrad1,Dlrad2,Dlrad3,DlrMob);
}
catch {}
return update;
}
#endregion
When I press the Update button, it will call the Javascript function and then it passes the value in the text boxes to the ASP code UpdateDealer();
Before am writing this function in Javascript all other functions worked properly but now it's not working properly
There is a bug in your first line of js.
var dlr = document.getElementById("**<%**txt_sapcode.ClientID%>").value;
Fix this (= missing) and check.
Where have you defined, dealerID
data: "{DlrId:'" + dealerID + "',DlrCode:'" + dlr
also, i dont' think your stat variable is initialized with following line of code just confirm.
var stat = document.getElementById('drp_state').value;
Make sure you debug and variables you have defined are initialized.
remove static from
public DataSet UpdateDealer(Int32 DlrId, Int32 DlrCode, string
DlrName, string Dlrad1, string Dlrad2, string Dlrad3, Int16 Dlrddd,
Int32 DlrLan, Int32 DlrMob)
{
DataSet update = new DataSet();
try
{
update = obj.UpdateDealerDetails(DlrId, DlrCode, DlrName, Dlrad1, Dlrad2, Dlrad3, DlrMob);
}
catch { }
return update;
}
function btn_upgrade_onclick() {
var dealerID = "1";
var dlr = "1";
var dlrname = "abc";
var addr1 = "india";
var addr2 = "delhi";
var addr3 = "delhi";
var mobno = "1234567890";
var stat = "";
var DlrLan = "123";
var Dlrddd = "1123";
$.ajax({
type: "POST",
url: "AutoComplete.asmx/UpdateDealer",
data: "{DlrId:'" + dealerID + "', DlrCode:'" + dlr + "', DlrName:'" + dlrname + "', Dlrad1:'" + addr1 + "' , Dlrad2:'" +
addr2 + "', Dlrad3:'" + addr3 + "', Dlrddd:'" + Dlrddd + "', DlrLan:'"
+ DlrLan + "', DlrMob:'" + mobno + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
$("#drp_support").get(0).options.length = 0;
$("#drp_support").get(0).options[0] = new Option("--Select--", "0");
$("#drp_support").unbind("change");
alert(data);
$.each(msg.d, function(index, item) {
$("#drp_support").get(0).options[$("#drp_support").get(0).options.length] = new Option(item.Display, item.Value);
});
$("#drp_support").bind("change", function() {
sprtengId = $(this).val();
});
},
error: function() {
alert("Error");
}
});
}
How can I force google to redraw its infoWindow or atleast refresh its contents?
I noticed that I must click twice on a marker before the correct data appears inside the infoWindow -maybe my closure here is the culprit.
var markers = new Array();
var allMarkers = new Array();
var infoWindow = new google.maps.InfoWindow();
var infoWindows = new Array();
// IE caches ajax request - need a way to clear cache with each fetch of data
randomize = function () {
var randomnumber = Math.floor(Math.random() * 100000);
return randomnumber;
}
function getBeachLocations() {
// construct query
var queryURL = "https://www.googleapis.com/fusiontables/v1/query?sql=";
var queryTail = "&key=apiKey&callback=?";
var query = "SELECT * FROM BeachTable"; // beach locations tbl
var queryText = encodeURI(query);
$.ajax({
type: "GET",
url: queryURL + queryText + queryTail,
cache: false,
dataType: 'jsonp',
success: createMarkers,
error: function () {
alert("Sorry, no spatial data is available at this time, please check back on a later date.");
}
});
} //end getBeachLocations
function createMarkers(data) { // =====================create markers
url = "http://swim.jpg";
var rows = data['rows'];
var ecoli_rows;
var algae_rows;
for (var m in rows) {
var ecoli_array = new Array();
var marker = new google.maps.Marker({
map: map,
icon: new google.maps.MarkerImage(url),
beach_id: rows[m][0],
beach_name: rows[m][1],
beach_region: rows[m][2],
position: new google.maps.LatLng(rows[m][4], rows[m][5]),
idx: m,
getHeader: function () {
var str = [
'<div style="width:650px;">',
'<div class="tabs">',
'<ul>',
'<li><span>E. Coli Data</span></li>',
'<li><span>Algae Data</span></li>',
'</ul>',
'<div id="tab-1">',
'<h1>' + this.beach_name + '</h1>',
'<h3>' + this.beach_region + '</h3>'
].join('');
return str;
}, // end getHeader method
getEcoliData: function () { // begin getEcoliData
var obj;
obj = getEcoliData(this.beach_id);
return obj;
}, // end getEcoliData method
afterGetEcoliData: function (data) {
var ecoli_rows;
var ecoli_rows_str;
ecoli_rows = data['rows'];
var ecoli_rows_str = [
'<table id="ecoli_table " class="data" style="width:500px;">',
'<tr>',
'<th>Sample Date</th>',
'<th>Average E. coli Density <br/> (200 cfu/100 ml)</th>',
'<th>Recreational Water Quality Guideline</th>',
'</tr>'
].join('');
if (typeof ecoli_rows == 'undefined') {
ecoli_rows_str = '<p>Sorry no ecoli data currently exists for this beach.</p></div>'
} else {
for (var i = 0; i < ecoli_rows.length; i++) {
//console.log(rows[i]);
ecoli_rows_str += '<tr><td>' + formatDate(ecoli_rows[i][2]) + '</td><td>' + checkEcoliCount(ecoli_rows[i][3]) + '</td><td>' + ecoli_rows[i][4] + '</td></tr>';
}
ecoli_rows_str += '</table>'
ecoli_rows_str += '</div>';
// remove after test
ecoli_rows_str += '<div id="tab-2"><h1>nothing loaded</h1></div></div></div>';
} //end if
return ecoli_rows_str;
}, // end outPutEcoliData method
getAlgaeData: function () { // begin getAlgaeData
var obj;
var algae_rows_str = [
'<div id="tab-2">',
'<h1>' + this.beach_name + '</h1>',
'<h3>' + this.beach_region + '</h3>',
'<table id="algae_table " class="data" style="width:500px;">',
'<tr>',
'<th>Sample Date</th>',
'<th>Algal Toxin Microcystin <br/> (20 ug/L)</th>',
'<th>Recreational Water Quality Guideline</th>',
'<th>Blue Green Algae Cells <br/>(100,000 cells/ml)</th>',
'<th>Recreational Water Quality Guideline</th>',
'</tr>'
].join('');
obj = getAlgaeData(this.beach_id);
return obj;
}, // end getAlgaeData method
outPutAlgaeData: function (data) {
obj.done(function (data) {
algae_rows = data['rows'];
}); // end success
//console.log(algae_rows);
if (typeof algae_rows === 'undefined') {
algae_rows_str = [
'<div id="tab-2">',
'<h1>' + this.beach_name + '</h1>',
'<h3>' + this.beach_region + '</h3>',
'<p>Sorry no algae data exists for this beach.</p>',
'</div>',
'</div>',
'</div>',
'</div>'
].join('');
} else {
for (var i = 0; i < algae_rows.length; i++) {
//console.log(rows[i]);
algae_rows_str += '<tr><td>' + formatDate(algae_rows[i][2]) + '</td><td>' + checkAlgaeToxinCount(algae_rows[i][3]) + '</td><td>' + algae_rows[i][4] + '</td><td>' + checkAlgaeCount(algae_rows[i][5]) + '</td><td>' + algae_rows[i][6] + '</td></tr>';
}
algae_rows_str += '</table>'
algae_rows_str += '</div></div></div>';
//return algae_rows_str;
} //end if
return algae_rows_str;
} // end outPutAlgaeData
}); // ====================end marker
allMarkers.push(marker); //required for drop down menu
console.log(marker.beach_id + " " + marker.beach_name);
// click event handler
google.maps.event.addListener(marker, 'click', function () {
var ajaxObj = this.getEcoliData();
var marker = this;
var str;
// add loading gif
//infoWindow.setContent('<img src="../img/loading.gif" alt="loading data"/>');
ajaxObj.done(function (data) {
/*
str = marker.getHeader() + marker.afterGetEcoliData(data);
console.log(str);
*/
infoWindow.setContent(marker.getHeader() + '' + marker.afterGetEcoliData(data));
infoWindow.open(map, this);
$(".tabs").tabs({ selected: 0 });
}); // End done
}); // End click event handler
} // end for loop foreach marker
checkAdvisory(); // determine where this needs to be called from.
} //end function createMarkers
// format date as January 1, 2013
function formatDate(num) {
var d = Date.parse(num).toString('MMMM d, yyyy');
return d;
}
// check ecoli count - anything greater than or equal to 200 cfu/100ml is flagged
function checkEcoliCount(num) {
var str;
num = parseFloat(num);
if (num >= 200) {
str = '<span class="ecoliCount_on" style="color:orange"><b>' + num + '</b></span>';
} else {
return num;
}
return str;
}
// check blue green algae count - anything greater than or equal to 100,000 cells/ml is flagged
function checkAlgaeCount(num) {
var str;
num = parseFloat(num);
if (num >= 100000) {
str = '<span class="algaeCount_on" style="color:orange"><b>' + num + '</b></span>';
} else {
return num;
}
return str;
}
// check algae toxin microcystin - anything greater than or equal to 20 ug/L is flagged
function checkAlgaeToxinCount(num) {
// why include < ? - ask Cassie
var str;
var idx;
idx = num.indexOf("<");
num = num.substring(idx + 1);
num = parseFloat(num);
if (num >= 20) {
str = '<span class="algaeToxinCountOn" style="color:orange"><br>' + num + '</b></span>';
} else {
return num;
}
return str;
}
function checkAdvisory() {
/* add advisory images
ecoliCount_on
algaeCount_on
algaeToxinCountOn
*/
$(".ecoliCount_on").each(function (i, v) {
console.log(i, v);
$(this).css("color", "green");
});
$(".algaeCount_on").each(function (i, v) {
console.log(i, v);
$(this).css("color", "green");
});
$(".algaeToxinCountOn").each(function (i, v) {
console.log(i, v);
$(this).css("color", "green");
});
}
function getEcoliData(beach_id) {
//console.log(beach_id);
var rows;
var queryURL = "https://www.googleapis.com/fusiontables/v1/query?sql=";
var queryTail = '&key=apiKey&callback=?';
var whereClause = "WHERE 'Beach_ID' = " + beach_id;
var query = "SELECT * FROM EcoliTable "
+ whereClause + " ORDER BY 'Sample_Date' DESC";
var queryText = encodeURI(query);
var ecoli_array = new Array();
return $.ajax({
type: "GET",
url: queryURL + queryText + queryTail,
cache: false,
dataType: 'jsonp'
});
}
function getAlgaeData(beach_id) {
var queryURL = "https://www.googleapis.com/fusiontables/v1/query?sql=";
var queryTail = '&key=apiKey&callback=?';
var whereClause = " WHERE 'Beach_ID' = " + beach_id;
var query = "SELECT * FROM algaeTable "
+ whereClause + " ORDER BY 'Sample_Date' DESC";
var queryText = encodeURI(query);
// ecoli request
return $.ajax({
type: "GET",
url: queryURL + queryText + queryTail,
cache: false,
dataType: 'jsonp'
});
}
// create beach locations dropdown
function createDropDownMenu() {
var query = 'SELECT Beach_Location, Beach_ID FROM beachTable ORDER BY Beach_Location ASC';
var queryText = encodeURIComponent(query);
var gvizQuery = new google.visualization.Query(
'http://www.google.com/fusiontables/gvizdata?tq=' + queryText);
//Send query and draw table with data in response
gvizQuery.send(function (response) {
var numRows = response.getDataTable().getNumberOfRows();
var numCols = response.getDataTable().getNumberOfColumns();
var name = ['<label style="font-weight:bolder;font-size:16px"> Select a Beach:</label><select id="beach_menu" style="font-size:16px;" onchange="select_beach(this.options[this.selectedIndex].value);"><option class="defaultopt" value="">--All--</option>'];
for (var i = 0; i < numRows; i++) {
var nameValue = response.getDataTable().getValue(i, 0);
var idValue = response.getDataTable().getValue(i, 1);
name.push("<option value=" + "'" + idValue + "'" + ">" + nameValue + "</option>");
}
name.push('</select>');
document.getElementById('beach_location_dropdown').innerHTML = name.join('');
});
} // end createDropDownMenu Function
function select_beach(val) {
$("#beach_menu option[value='" + val + "']").attr('selected', 'selected');
if (val === "") {
resetMapExtent();
displayAllBeaches();
}
else {
update_layer(val)
}
} // end select_beach function
function resetMapExtent() {
google.maps.event.trigger(map, "resize");
map.setCenter(new google.maps.LatLng(53.760861, -98.813876));
map.setZoom(5);
} // end resetMapExtent function
// implement update_layer function
function update_layer(beach) {
infoWindow.close();
for (var z = 0; z < allMarkers.length; z++) {
if (beach === allMarkers[z].beach_id) {
allMarkers[z].setVisible(true);
} else {
// hide all other markers
allMarkers[z].setVisible(false);
}
}
} // end update_layer function
function displayAllBeaches() {
infoWindow.close();
// show all markers
for (var z = 0; z < allMarkers.length; z++) {
// hide all markers
allMarkers[z].setVisible(true);
}
} // end displayAllBeaches
/* start map initialization */
function initialize() {
// map
latlng = new google.maps.LatLng(49.894634, -97.119141);
var myOptions = {
center: latlng,
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL
},
mapTypeControl: true,
mapTypeControlOptions: {
mapTypeIds: [
google.maps.MapTypeId.ROADMAP,
google.maps.MapTypeId.SATELLITE,
google.maps.MapTypeId.HYBRID,
google.maps.MapTypeId.TERRAIN
],
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
overviewMapControl: true,
overviewMapControlOptions: {
opened: true
}
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
// invocation begins here
createDropDownMenu(); // not working now.
getBeachLocations();
// legend
map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(
document.getElementById('legend'));
var legend = document.getElementById('legend');
var swim_icon = "swim.jpg";
var div = document.createElement('div');
div.innerHTML = '<h4>Features</h4>' +
'<br/><img src="' + swim_icon + '"> ' + "Beaches";
legend.appendChild(div);
} // end initialization function
$(function () {
$('.view_normal').live('click', function () {
$(".container").css("width", "930px").css("margin", "auto");
$(".onewidecenter").css("width", "930px").css("margin", "auto");
$("#map_canvas").css("width", "930px").css("margin", "auto");
google.maps.event.trigger(map, "resize");
map.setCenter(new google.maps.LatLng(53.760861, -98.813876));
map.setZoom(5);
});
$('.view_full_screen').live('click', function () {
$(".container").css("width", "100%").css("margin", "auto");
$(".onewidecenter").css("width", "100%").css("margin", "auto");
$("#map_canvas").css("width", "100%").css("margin", "auto");
$(" #dropdown_container").css("width", "100%").css("margin", "auto");
google.maps.event.trigger(map, "resize");
map.setCenter(new google.maps.LatLng(53.760861, -98.813876));
map.setZoom(5);
});
}); // end page load
I have included the sample code above. Please pay special attention to my click event handler. As always, as suggestions on how best to remedy this would be greatly appreciated.
Thanks in advance,
Michael
jQuery AJAX methods are asynchronous. That means:
obj.success(function (data) {
ecoli_rows = data['rows'];
}); // end sucess
Returns immediately but the callback function doesn't run until the ajax request completes.
This means that:
infoWindow.setContent(this.getHeader() + '' +
this.getEcoliData() + '' + this.getAlgaeData());
infoWindow.open(map, this); //ajax callback hasn't fired here
opens the info window with the content BEFORE the ajax request completes.
To correct, you might do something like this:
In marker.getEcoliData:
obj = getEcoliData(this.beach_id);
return obj;
// move processing below this point to new method
And in the click event handler:
google.maps.event.addListener(marker, 'click', function () {
var ajaxObj = this.getEcoliData();
var marker = this;
ajaxObj.done(function() {
infoWindow.setContent(marker.getHeader() + '' +
marker.afterGetEcoliData() + '' +
this.getAlgaeData());
infoWindow.open(map, this);
$(".tabs").tabs({ selected: 0 });
});
This is not a complete solution since you have two asynchronous calls happening. You could either chain them, or set some kind of counter to make sure that the callback only executes when both have completed.
An even better approach would be to immediately open the infowindow with some kind of information to tell the user that data is being loaded. Then after the requests complete, you simply update the infowindow content again (with a handle to the content element) to show the returned data.
Thanks for the help with this. I managed to get this to work as expected. As it turned out I had to restructure the marker class so that two ajax requests weren't be returned an additional time.
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.
I am new to ajax and am trying to get the following script working. I just want to take info from a json object and print it to the document.
Here is the JSON file called companyinfo.json:
{
'id':1,
'name':'Stack'
}
The Ajax request looks like this:
ar xhr = false;
var xPos, yPos;
$(function(){
var submitButton = $("#dostuff");
submitButton.onclick = sendInfoRequest;
});
function sendInfoRequest (evt) {
if (evt) {
var company1 = $("#companyInput1").val;
var company2 = $("#companyInput2").val;
}
else {
evt = window.event;
var company = evt.srcElement;
}
$.ajax({
url : 'companyinfo.json',
dataType: 'json',
data: company1,
success: function(data) {
console.log(data);
var items = new Array ();
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
}
});
return false;
}
console.log(data.id);
To start simple. I just console.log the data.id to see if the script returned a value from the json file.
To write it to the document I would do something like this, calling the showContents function in the callback function above:
function showContents(companyNumber) {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var outMsg = xhr.responseXML;
$("." + data.companyName.toLowerCase + companyNumber).innerHTML(data.companyName)
}
else {
var outMsg = "There was a problem with the request " + xhr.status;
}
}
}
I'm pretty new to Ajax, but hopefully that makes some sense. Thanks
if you are trying to get something i think you should add
type:"GET"
on your $.ajax it should look like this.
$.ajax({
url : 'companyinfo.json',
dataType: 'json',
type:"GET",
contentType: "application/json; charset=utf-8",
data: company1, //What is your purpose for adding this?
success: function(data) {
console.log(data);
var items = new Array ();
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
}
});
Im not sure about this in your code:
var company1 = $("#companyInput1").val; //should it be with ()??
var company2 = $("#companyInput2").val; //should it be with ()??
should it be with () like this one:
var company1 = $("#companyInput1").val();
var company2 = $("#companyInput2").val();
The easiest way to get and parse JSON is to use $.getJSON
// you need to use a map as your data => {key : value}
$.getJSON("companyinfo.json", {company : company1}, function(data){
console.log(data);
var items = []; // new Array();
$.each(data, function(key, val){
items.push('<li id="' + key + '">' + val + '</li>');
});
// do something with items
});
you can do like this:
$.getJSON("getJson.ashx", { Index: 1 }, function (d) {
alert(d);
});