how can I do for this function below to generate an incremental index in the table? Names are being generated right.
I thought of an incremental variable (a), something like that.
function sortear()
{
var a = 1;
$.ajax({
url: 'prize',
type: 'POST',
dataType: 'json',
data: 'employees=' + $('#employees').val() + "&sorted=" + sorteados,
beforeSend: function() {
$('#loading').modal();
},
success: function(data) {
$('#loading').modal('hide');
if (data == null) {
window.alert('Todos os nomes foram sorteados');
$('#button').attr('disabled', 'disabled');
return;
}
$('#employee').html(data.name);
$('#myModal').modal();
$('#sorted tbody').append('<tr><td>' + a + '</td><td>' + data.name + '</td></tr>');
sorteados.push(data.name);
a++;
},
error: function() {
}
});
}
You can get the length of <tr> and sum 1:
/*...*/
// store the element in a variable to reuse it
const $sortedTbody = $('#sorted tbody');
// in the first iteration lenght will be 0, so it will print 1, then 2, etc
$sortedTbody.append('<tr><td>' + ($sortedTbody.children().length + 1) + '</td><td>' + data.name + '</td></tr>');
/*...*/
I keep getting results as false when running my POST & PUT & DELETE methods.
When I used POSTMAN I get 200 OK but my response returns as false?
Here's what I get when i use POST:
https://i.stack.imgur.com/fytB1.png
Here's what I get when i use UPDATE:
https://i.stack.imgur.com/y3vdv.png
Here's what I get when i use DELETE:
https://i.stack.imgur.com/hSNjy.png
Here is my controller code:
[HttpPost("AddNewOwner")]
public Boolean AddNewOwner(Owner theOwner)
{
DBConnect objDB = new DBConnect();
string strSQL = "INSERT INTO HomeOwnership_T (HomeOwnerID, FirstName, LastName, Address, City, State, ZipCode, TelNo, Email, BlockNo, LotNo, SaleDate, SalePrice, IsSold) " +
"VALUES ('" + theOwner.HomeOwnerID + "', '" + theOwner.FirstName + "', '" +
theOwner.LastName + "', '" + theOwner.Address + "', '" + theOwner.City +
"', '" + theOwner.State + "', '" + theOwner.ZipCode + "', '" + theOwner.TelNo + "', '"
+ theOwner.Email + "', '" + theOwner.BlockNo + "', '" + theOwner.LotNo + "', '"
+ theOwner.SaleDate + "', '" + theOwner.SalePrice + "', '" + theOwner.IsSold + "')";
//Execute the INSERT statement in the database
int result = objDB.DoUpdate(strSQL);
if (result > 0)
{
string command = "SELECT TOP 1 HomeOwnerID FROM HomeOwnership_T ORDER BY DESC";
DataSet ds = objDB.GetDataSet(command);
Tax taxInfo;
foreach (DataRow record in ds.Tables[0].Rows)
{
taxInfo = new Tax();
taxInfo.HomeOwnerID = int.Parse(record["HomeOwnerID"].ToString());
string strSQL2 = "INSERT INTO TaxInfo_T (AccessedVal, LandVal, AdditionalVal, TaxRate, TaxPerYear, RealEstateTax, HomeOwnerID)"
+ "VALUES (0.0, 0.0, 0.0, 0.0, 0.0, 0.0, '" + taxInfo.HomeOwnerID + "')";
objDB.DoUpdate(strSQL2);
}
return true;
}
else
{
return false;
}
}
[HttpPut]
public Boolean Update(Owner theOwner)
{
DBConnect objDB = new DBConnect();
HomeTax owner = new HomeTax();
string strSQL = "UPDATE HomeOwnership_T SET HomeOwnerID = " + theOwner.HomeOwnerID +
", FirstName = '" + theOwner.FirstName + "', LastName: '" + theOwner.LastName +
"', Address = '" + theOwner.Address + "', City = '" + theOwner.City +
"', City = '" + theOwner.City + "', State = '" + theOwner.State +
"', ZipCode = '" + theOwner.ZipCode + "', TelNo = '" + theOwner.TelNo +
"', Email = '" + theOwner.Email + "', BlockNo = " + theOwner.BlockNo +
", LotNo = " + theOwner.LotNo + "', SaleDate = '" + theOwner.SaleDate +
"', SalePrice = " + theOwner.SalePrice + ", IsSold = '" + theOwner.IsSold +
" WHERE HomeOwnerID = " + theOwner.HomeOwnerID;
int result = objDB.DoUpdate(strSQL);
if (result > 0)
{
return true;
}
else
{
return false;
}
}
[HttpDelete("{id}")]
public Boolean Delete(int id)
{
DBConnect objDB = new DBConnect();
string strSQL = "DELETE * FROM HomeOwnership_T INNER JOIN TaxInfo_T " +
"ON HomeOwnership_T.HomeOwnerID = TaxInfo_T.HomeOwnerID WHERE HomeOwnerID = " + id;
int result = objDB.DoUpdate(strSQL);
if(result > 0)
{
return true;
}
else
{
return false;
}
}
Here are my ajax calls:
$(document).on("click", "#btnAddHomeOwner", function () {
var strURL = "https://localhost:44395/api/ServiceDeed/AddNewOwner";
$("#msg").html("");
$("#update").html("");
$("#updateResult").html("");
console.log("btnAddHomeOwner selected");
var owner = new Object();
owner.HomeOwnerID = $("#txtHomeOwnerID").val();
owner.FirstName = $("#txtFirstName").val();
owner.LastName = $("#txtLastName").val();
owner.Address = $("#txtAddress").val();
owner.City = $("#txtCity").val();
owner.State = $("#txtState").val();
owner.ZipCode = $("#txtZipCode").val();
owner.TelNo = $("#txtTelNo").val();
owner.Email = $("#txtEmail").val();
owner.BlockNo = $("#txtBlockNo").val();
owner.LotNo = $("#txtLotNo").val();
owner.SaleDate = $("#txtSaleDate").val();
owner.SalePrice = $("#txtSalePrice").val();
owner.IsSold = $("#txtIsSold").val();
var strInput = JSON.stringify(owner);
// Make an AJAX request to get a home and store the response in the appropriate div.
$.ajax({
type: "POST",
url: strURL,
contentType: "application/json", // set the data type sent to the Web Service.
dataType: "json", // set the data type expected from the Web Service.
data: strInput, // send an empty JSON object (no input required).
success: function (data) { // set callback function used to update the page/
console.log(data);
var result = data;
if (result == true)
$("#msg").text("The record was successfully added to the database.");
else
$("#msg").text("The record was not added to the database. Try again later.");
},
error: function (req, status, error) { // sets the error callback function used when an error occurs.
alert("Error: " + req.responseText + " | " + status + " | " + error);
}
}); //end of ajax method
}); // end of btnStoreHomeOwner click event
$(document).on("click", "#btnDelete", function () {
var strURL = "https://localhost:44395/api/ServiceDeed/";
var param = $("#txtHomeOwnerID").val();
$("#msg").html("");
$("#update").html("");
$("#updateResult").html("");
console.log("Delete button selected.");
$.ajax({
type: "DELETE",
url: strURL + param,
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{5}",
success: function (data) {
console.log(data);
var result = data;
if (result == true) {
$("#msg").text("The record with HomeOwnerID: " + param + " was deleted.");
alert("Deleted!");
}
else {
$("#msg").text("The record with HomeOwnerID: " + param + " was not deleted.");
alert("Not Deleted");
}
},
error: function (req, status, error) { // sets the error callback function used when an error occurs.
alert("Error: " + req.responseText + " | " + status + " | " + error);
}
}); //end of ajax method
}); // end of btnDelete click event
$(document).on("click", "#btnUpdateAll", function () {
var strURL = "https://localhost:44395/api/ServiceDeed/Update";
// Clear the divs contents.
//$("#display").html("");
//$("#msg").html("");
$("#update").html("");
$("#updateResult").html("");
console.log("Update home owner button selected.");
var owner = new Object();
owner.HomeOwnerID = $("#txtHomeOwnerID").val();
owner.FirstName = $("#txtFirstName").val();
owner.LastName = $("#txtLastName").val();
owner.Address = $("#txtAddress").val();
owner.City = $("#txtCity").val();
owner.State = $("#txtState").val();
owner.ZipCode = $("#txtZipCode").val();
owner.TelNo = $("#txtTelNo").val();
owner.Email = $("#txtEmail").val();
owner.BlockNo = $("#txtBlockNo").val();
owner.LotNo = $("#txtLotNo").val();
owner.SaleDate = $("#txtSaleDate").val();
owner.SalePrice = $("#txtSalePrice").val();
owner.IsSold = $("#txtIsSold").val();
var strInput = JSON.stringify(owner);
//Make an AJAX request to get a home owner and display the response in the appropriate div
$.ajax({
type: "PUT",
url: strURL,
contentType: "application/json; charset=utf-8",
dataType: "json",
data: strInput,
success: function (data) {
console.log(data);
var owner = data;
$("#display").html("<hr><p>".concat("HomeOwnerID: ", owner.HomeOwnerID,
"<br>FirstName: ", owner.FirstName, "<br>LastName: ", owner.LastName,
"<br>Address: ", owner.Address, "<br>City: ", owner.City,
"<br>State: ", owner.State, "<br>ZipCode: ", owner.ZipCode,
"<br>Telephone Number: ", owner.TelNo, "<br>Email: ", owner.Email,
"<br>Block Number: ", owner.BlockNo, "<br>Lot Number: ", owner.LotNo,
"<br>Date of Sale: ", owner.SaleDate, "<br>Sale Price: $", owner.SalePrice,
"<br>Sold Status: ", owner.IsSold, "<br>Accessed Value: $", owner.AccessedVal,
"<br>Land Value: $", owner.LandVal, "<br>Additional Value: $", owner.AdditionalVal,
"<br>Tax Rate: $", owner.TaxRate, "<br>Tax Per Year: $", owner.TaxPerYear,
"<br>Real Estate Tax: $", owner.RealEstateTax, "</p >"));
if (owner == true)
$("#updateResult").text("The record was successfully updated to the database.");
else
$("#updateResult").text("The record was not updated to the database. Try again later.");
},
error: function (req, status, error) { // sets the error callback function used when an error occurs.
alert("Error: " + req.responseText + " | " + status + " | " + error);
}
}); //end of ajax method
}); //end of btnUpdate
check your sql string when you set the homeownerid is it suppose to be "SET hoID = '" + theOwner.HomeOwnerID + "', ownerName = '" + theOwner.ownerName + "'....etc
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 have a jquery save function like this -
$(".SaveBtn").click(function () {
if ($("#Form1").valid()) {
var rowData = $("#TestTable").getRowData($(this).data("rowid"));
var currentRow = $(this).closest("tr");
var postData = {
testID: rowData.testID,
testNotes: currentRow.next().find(".NotesEntry").val(),
isActive: currentRow.next().next().find(".CheckEntry") == null ? "false" : currentRow.next().next().find(".CheckEntry").prop("checked"),
};
$.ajax({
type: "POST",
url: "../Services/test.asmx/UpdateTestRowData",
data: JSON.stringify(postData),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data.d != null) {
$("#TestTable").setGridParam({ postData: { myID: $('#hfmyID').val() }, datatype: 'json' }).trigger("reloadGrid");
}
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
}
});
The problem is with this line -
isActive: currentRow.next().next() == null ? "false" : currentRow.next().next().find(".CheckEntry").prop("checked"),
};
When currentRow.next().next() is not available, the isActive is not set as "false" and is even not in the request body to web service.
Currently the request body is {"testID":"e9c966ace446-4f73-9ba0-26e686b2a308","testNotes":"TEST"}
I expect it to be -
{"testID":"e9c966ace446-4f73-9ba0-26e686b2a308","testNotes":"TEST", "isActive":"false"}
Why the "isActive" parameter is missed and how to make it available when currentRow.next().next() is not available?
Thanks
I fixed the problem by adding the else part in the following statement -
if (data.d.IsActived) {
output += "<td colspan='6' align=\"left\"><input type='checkbox' id='cbActive" + rowId + " checked" + " name='cbManualDeactive" + rowId + "' class='CheckEntry CheckEntry' data-registrationid='" + data.d.ID + "' data-rowid='" + rowId + "'/></td>";
}
else {
output += "<td style=\"display:none;\"><input type='checkbox' id='cbActive" + rowId + " name='cbActive" + rowId + "' class='CheckEntry CheckEntry' data-registrationid='" + data.d.ID + "' data-rowid='" + rowId + "'/></td>";
}
Thanks
In the following script, although the two weather objects are both populated with data in the ajax calls, the updateWeather call shows them both as undefined prior to that line executing. I moved the variable declarations so they would be global but they still both show undefined prior to the updateWeather call. What am I missing? Can I not set up a variable in the ajax success function and then pass it later?
Note: If you want to test this use a different url as this one won't work for you with out my credentials
function getWeatherForecastStationCode() {
var d = new Date();
var parts = d.toString().split(" ");
var dDate = parts[1] + " " + parts[2] + ", " + parts[3];
var ampm;
if (parts[4].split(":")[0] <= 12) {
ampm = "AM";
} else {
ampm = "PM";
}
var dtime = parts[4].split(":")[0] + ":" + parts[4].split(":")[1];
var datetime = dDate + " " + dtime + ampm;
alert(datetime);
var weatherStation = "KPBI"; // get from GetWeatherService.svc
var forecastFields = "&fields=periods.maxTempF%2cperiods.minTempF%2cperiods.vaildTime%2cperiods.weather%2cperiods.icon";
var currentFields = "&fields=ob.tempC%2cob.tempF%2cob.icon%2cplace.name%2cplace.state";
var forecastUrlWeatherStation = 'http://api.aerisapi.com/forecasts/' + weatherStation + '?limit=1&client_id=' + AerisClientId + '&client_secret=' + AerisWeatherApiSecret + forecastFields;
var currentUrlWeatherStation = 'http://api.aerisapi.com/observations/' + weatherStation + '?limit=1&client_id=' + AerisClientId + '&client_secret=' + AerisWeatherApiSecret + currentFields;
$.ajax({
type: "GET",
url: forecastUrlWeatherStation,
dataType: "json",
success: function (json) {
if (json.success === true) {
forecastedWeather = {
weather: json.response[0].periods[0].weather,
maxTemp: json.response[0].periods[0].maxTempF,
minTemp: json.response[0].periods[0].minTempF,
weatherIcon: json.response[0].periods[0].icon,
obsTime: datetime
};
}
else {
alert('An error occurred: ' + json.error.description);
}
}
});
var location;
$.ajax({
type: "GET",
url: currentUrlWeatherStation,
dataType: "json",
success: function (json) {
if (json.success === true) {
var place = json.response.place.name.split(" ");
if (place.length === 1) {
location = place[0].charAt(0).toUpperCase() + place[0].substr(1, place[0].length);
} else {
location = place[0].charAt(0).toUpperCase() + place[0].substr(1, place[0].length) + " " + place[1].charAt(0).toUpperCase() + place[1].substr(1, place[1].length) + ", " + json.response.place.state.toUpperCase();
}
currentWeather = {
location: location,
currentTemp: json.response.ob.tempF
};
} else {
alert('An error occurred: ' + json.error.description);
}
}
});
updateWeather(forecastedWeather,currentWeather);
}
The problem is that AJAX is Asynchronous (Thats the "A" in "AJAX"), so the call to updateWeather is executing before a response is received from your 2 ajax calls.
The way to do this then, is to wait for all ajax calls to complete before calling updateWeather.
Something like the following (untested):
$.when(getForecast(),getCurrent()).done(function(f,c){
updateWeather(forecastedWeather,currentWeather)
});
function getForecast(){
return $.ajax({
type: "GET",
url: forecastUrlWeatherStation,
dataType: "json"
....
});
};
function getCurrent(){
return $.ajax({
type: "GET",
url: currentUrlWeatherStation,
dataType: "json"
....
});
};