Push a list into array in JavaScript - javascript

I have a list of Data I get from dynamic inputs like this ones
FirstNames : Person1 FN, Person2 FN, Person3 FN, ...
LastNames : Person1 LN, Person2 LN, Person3 LN, ...
The list is dynamic and I'm Getting the values by input Name like this
var FirstNames = $("input[name='FirstName']").map(function(){return $(this).val();}).get();
I want to pass these and many others to my C# backend as an array like This
details:[
0: {FirstName: 'Person1 FN', LastName: 'Person1 LN'}
1: {FirstName: 'Person2 FN', LastName: 'Person2 LN'}
....................................................
N{FirstName: 'PersonN FN', LastName: 'PersonN LN'}
]
I tried many different approaches like split() & Push() as below
let FNs = [];
let FN = FirstNames.toString().split(',');
console.log("Splitted First Names : "+TFNs);
$.each(TFNs, function(){
FNs.push({FirstName:$(this)}.toString());
});
console.log("First Names[] : "+FNs);
Edit : Added Form markup(dynamic) & JS Save() Function
Here is the form (dynamically generated)
function GenerateFrms(Id) {
//alert('Function Scripts');
$("#FrmContainer").empty();
var html = "";
$.ajax({
type: "POST",
url: "WebService.asmx/GenerateForms",
data: "{'Id':'" + Id + "'}",
contentType: "application/json",
dataType: "json",
success: function (data) {
console.log(Object.values(data))
try {
for (var i = 0; i <= data.d.length; i++) {
if (data.d[i].Persons != "0") {
html += " <div class='theme-box-shadow theme-border-radius bg-light mb-3'> ";
html += " <div class='row border-bottom py-2 m-auto'> ";
html += " <div class='col-8'>";
html += " <div class='fw-bold font-medium'> Details </div> ";
html += " </div> ";
html += "<div class='col-4 text-end align-self-center'> ";
html += " <a class='font-small' data-bs-toggle='collapse' href='#collapseFrm' role='button' aria-expanded='false' aria-controls='collapseFrm'><i class='bi bi-chevron-down ps-1'></i></a>";
html += " </div>";
html += " </div>";
html += " <div class='' id='collapseFrm'> ";
html += " <div class='row'> ";
html += " <div class='col-sm-12'> ";
html += " <div class='px-3 FrmDetails' id='FrmDetails'> ";
for(var j=1; j<=data.d[i].Persons; j++)
{
html += " <legend class='fw-bold' style='border-bottom:2px solid blue;'> Persons " + j + " Details</legend> ";
html += " <ul class='row py-3'> ";
html += " <li class='col-12 col-md-12 pb-3'> ";
html += " <div class='row'> ";
html += " <div class='col-12 col-sm-6 col-md-3 mb-3 mb-md-0'> ";
html += " <label for='inlineFormSelectTitle3'> selected Title </label> ";
html += " <select class='form-select Title' name='Title' id='Title" + j + "' > ";
html += " <option selected>Title</option> ";
html += " <option value='Mr'>Mr.</option> ";
html += " <option value='Mrs'>Mrs.</option> ";
html += " <option value='Ms'>Ms.</option> ";
html += " </select> ";
html += " </div> ";
html += " <div class='col-12 col-sm-6 col-md-3 mb-3 mb-md-0'> ";
html += " <label for='inlineFormSelectTitle3'> First Name </label> ";
html += " <input type='text' class='form-control FirstName' name='FirstName' id=' FirstName" + j + "' placeholder='First Name'> ";
html += " </div> ";
html += " <div class='col-12 col-sm-6 col-md-3 mb-3 mb-md-0'> ";
html += " <label for='inlineFormSelectTitle3'> Last Name </label> ";
html += " <input type='text' class='form-control LastName' name='LastName' id=' LastName" + j + "' placeholder=' Last Name'> ";
html += " </div> ";
html += " <div class='col-12 col-sm-6 col-md-3 mb-3 mb-md-0'> ";
html += " <label for='inlineFormSelectTitle3'> Date of Birth </label> ";
html += " <label class='visually-hidden' for='DateofBirth'> Date of Birth</label> ";
html += " <input type='date' class='form-control DOB' name='DOB' id='DOB" + j + "'> ";
html += " </div> ";
html += " </div> ";
html += " </li> ";
html += " </li> ";
html += " </ul> ";
}
html += " </div> ";
html += " </div> ";
html += " </div> ";
html += " </div> ";
html += " </div> ";
}
$("#FrmContainer").append(html)
}
//
} catch (e) {
console.log(e);
}
},
error: function (xhr, status, e) { alert(xhr.responseText); }
});
}
The Script function with Sample static data I'm working with now(I want get them dynamically from the above form)
function Save() {
$('#create').prop('disabled', true);
//Reading Values from the respective inputs/select
var Titles = $("select[name='Title']").map(function(){return "Title:"+$(this).val();}).get();
var FNames = $("input[name='FirstName']").map(function(){return $(this).val();}).get();
var LNames = $("input[name='LastName']").map(function(){return $(this).val();}).get();
var DOBs = $("input[name='DOB']").map(function(){return "DOB:"+$(this).val();}).get();
//here I want to put them in array like `details[]` array below
setTimeout(function () {
let details=[];
details.push({
Title:"Mr.",
FirstName:"Person1 FN",
LastName:"Person1 LN",
DOB:"1990-05-20"
});
details.push({
Title:"Mrs.",
FirstName:"Person2 FN",
LastName:"Person2 LN",
DOB:"2001-06-18"
})
console.log(details);
var DataCarrier = {
Id: Id, //From Query string
PersonsDetails:details
};
$.ajax({
type: "POST",
url: "WebService.asmx/SavePersons",
data: JSON.stringify(DataCarrier),
contentType: "application/json",
dataType: "json",
success: function (data) {
try {
if (data != null) {
setTimeout(function () { window.location = "destinationPage.aspx?Id=" + Id; }, 500);
}
} catch (e) {
console.log(e);
}
},
error: function (xhr, status, e) { alert(xhr.responseText); }
});
}, 5000);
}
And the button
<input id="btnSave" class="btn btn-effect btn-book px-5" type="button" value="Continue" onclick="Save();" />
But I'm getting them as
[object Object],[object Object],[object Object],[object Object],[object Object]
I also tried .toString() but nothing changes, And console.log("FNs : "+json.stringify(FNs)); is throwing error.
How can I process these data as mentioned above before passing them to the backend? What I'm doing wrong? Is there a better way to do what I want achieve?

First step is to read the values from the inputs or select
//Reading Values from the respective inputs/select
var Titles = $("select[name='Title']").map(function() { return $(this).val(); }).get();
var FNames = $("input[name='FirstName']").map(function() { return $(this).val(); }).get();
var LNames = $("input[name='LastName']").map(function() { return $(this).val(); }).get();
var DOB = $("input[name='DOB']").map(function() { return $(this).val(); }).get();
Then split the values into array
//splitting the values into arrays
let TL = Titles.toString().split(',');
let FN = FNames.toString().split(',');
let LN = LNames.toString().split(',');
let BD = DOB.toString().split(',');
After that you can push them into the details[] array using for loop like this
let details = [];
for (var i = 0; i < FNames.length; i++) {
details.push({
Title: TL[i],
FirstName: FN[i],
LastName: LN[i],
DOB: BD[i],
TravllerType: TT[i]
});
}
console.log(JSON.stringify(details));
Note: if you console.log(details); you will find out that its object:Object stuff, to get around this, we stringify it.
finally incorprate all that into your SavePersons() function
function SavePersons() {
$('#create').prop('disabled', true);
//Reading Values from the respective inputs/select
var Titles = $("select[name='Title']").map(function () { return $(this).val(); }).get();
var FNames = $("input[name='FirstName']").map(function () { return $(this).val(); }).get();
var LNames = $("input[name='LastName']").map(function () { return $(this).val(); }).get();
var TravllerTypes = $("input[name='TravllerType']").map(function () { return $(this).val(); }).get();
var DOB = $("input[name='DOB']").map(function () { return $(this).val(); }).get();
//splitting the values into arrays
let TL = Titles.toString().split(',');
let FN = FNames.toString().split(',');
let LN = LNames.toString().split(',');
let TT = TravllerTypes.toString().split(',');
let BD = DOB.toString().split(',');
setTimeout(function () {
let details = [];
for (var i = 0; i < FNames.length; i++) {
details.push({
Title: TL[i],
FirstName: FN[i],
LastName: LN[i],
DOB: BD[i],
TravllerType: TT[i]
});
}
console.log(details);
var DataCarrier = {
Id: Id,
TravelersDetailsTT: details
};
$.ajax({
type: "POST",
url: "WebService.asmx/SavePersons",
data: JSON.stringify(DataCarrier),
contentType: "application/json",
dataType: "json",
success: function (data) {
try {
if (data != null) {
setTimeout(function () { window.location = "destinationPage.aspx?Id=" + Id; }, 5000);
}
} catch (e) {
console.log(e);
}
},
error: function (xhr, status, e) { alert(xhr.responseText); }
});
}, 5000);
}
it may not be the best answer but it works and I tested it. any improves are welcome. in the mean time I hope it helps.

I think the index of firstName and lastName in your array is identical so
var FirstNames = $("input[name='FirstName']")
.map(function(){return $(this).val();}).get();
var LastNames = $("input[name='LastName']")
.map(function(){return $(this).val();}).get();
var FN = FirstNames.map((FN,index) => {
return {{FirstName: FN, LastName: LastNames[index]}
})
It should be something like what you want

Related

Searching name using JS and AJAX

I am making name searching bar with JS and AJAX.
If write name on searching bar, only searched member must be shown.
And these are my code.
html:
...
<input type="text" id="searchName" name="searchName" placeholder="Search name..." onkeyup="nameFilter()" >
</div>
<ul class="invite-list03"></ul>
<ul id="memberList" class="member-list-group"></ul>
AJAX:
for (let i in user.family) {
let familyUserSn = user.family[i].familyUserSn;
let familyMemberNm = user.family[i].familyMemberNm;
let userProflPhotoCn = user.family[i].userProflPhotoCn;
let memberCreatDt = user.family[i].memberCreatDt;
let today = common_getTodayWithHyphen();
let family;
let hideDeleteBtn = '<div class="button-area"><button type="button" class="button-member-hide">hide</button><button type="button" class="button-member-delete" id="memberDeletePopUp">delete</button></div>';
// If today is invited day, show New icon up side of family member image
if(memberCreatDt == today) {
if(!userProflPhotoCn && userProflPhotoCn < 1) {
family = '<li class="family" id="'+ familyUserSn+'"><div class="member-profile"><figure class="default-bg"><img src="data:image/jpeg;base64,' + DATA_NO_PROFILE + '" alt="profilePicture"></figure><label class="new">N</label></div><p class="member-name">'+familyMemberNm+'</p>'+ hideDeleteBtn + '</li>';
} else {
family = '<li class="family" id="'+ familyUserSn+'"><div class="member-profile"><figure class="default-bg"><img src="data:image/jpeg;base64,' + userProflPhotoCn + '" alt="profilePicture"></figure><label class="new">N</label></div><p class="member-name">'+familyMemberNm+'</p>'+ hideDeleteBtn + '</li>';
}
} else {
if(!userProflPhotoCn && userProflPhotoCn < 1) {
family = '<li class="family" id="'+ familyUserSn+'"><div class="member-profile"><figure class="default-bg"><img src="data:image/jpeg;base64,' + DATA_NO_PROFILE + '" alt="profilePicture"></figure></div><p class="member-name">'+familyMemberNm+'</p>'+ hideDeleteBtn + '</li>';
} else {
family = '<li class="family" id="'+ familyUserSn+'"><div class="member-profile"><figure class="default-bg"><img src="data:image/jpeg;base64,' + userProflPhotoCn + '" alt="profilePicture"></figure></div><p class="member-name">'+familyMemberNm+'</p>'+ hideDeleteBtn + '</li>';
}
}
// append to memberList
$("#memberList").append(family);
}
// I am first member of list
$(".family").first().click();
JS:
function nameFilter() {
let searchNameSave = $('#searchName').val();
if(searchNameSave.length > 0) {
$("#memberList").html("");
$("ul#memberList > li > .member-name:contains('" + searchNameSave + "')").parent().show();
}
}
What should I write in javascript? Now it doesn't working.
Thank you for your help.
Hi there are a few things you need to do
Ajax get source information
Filter the source data according to the search criteria
Remove the old data and replace the filtered data
You can set your code according to this idea
The following is an example of using jquery-ui + ajax + autocomplete for your reference
$("#queryname").autocomplete({
source: function(request, response) {
$.ajax({
type: 'get',
url: "https://raw.githubusercontent.com/DataTables/DataTables/master/examples/ajax/data/objects_salary.txt",
dataType: 'json',
success: function(data) {
const matcher = new RegExp(request.term, "i");
const datas = data['data'];
response($.map(datas, function(item) {
if (matcher.test(item.name)) {
return {
label: item.name,
value: item.name
}
}
}));
}
});
}
});
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<input type='text' id='queryname' name='queryname' placeholder='Enter some text' />

Can't read checked value from checkbox returned from json

My web application has a Dropdown List which displays users and what I want is, when the field change happens it updates a set of check-boxes to either true or false, depending on the value stored in the DB.
My controller
public IActionResult Admin(string message) {
EditUser euModel = new EditUser();
List<EditUser> editUser= new List<EditUser> {
new EditUser { UserID = 0, Username = "--Select User--"},
new EditUser { UserID = 1, Username = "Unchecked"},
new EditUser { UserID = 2, Username = "Checked"}
};
ViewBag.haveAccess = HaveAccess;
List<EditUser> HaveAccess = new List<EditUser> {
new EditUser { DepartmentID = 1, DepartmentName = "IT", HaveAccess=false},
new EditUser { DepartmentID = 2, DepartmentName = "Financial", HaveAccess=false},
new EditUser { DepartmentID = 3, DepartmentName = "Sales", HaveAccess=false}
};
var SelectedValues = HaveAccess.Where(a => a.HaveAccess == true).Select(u => u.DepartmentID).ToArray();
ViewBag.haveAccess = new MultiSelectList(HaveAccess, "DepartmentID", "DepartmentName", SelectedValues);
return View(euModel);
}
My view
<form asp-controller="Admin" asp-action="HaveAccess" method="post" class="form-horizontal" role="form">
<div class="alert-danger" asp-validation-summary="ModelOnly"></div>
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-4">
<label asp-for="Username" class="control-label" value=""></label>
<select asp-for="UserID" class="form-control" id="changeid"
asp-items="#(new SelectList(ViewBag.editUser, "UserID", "Username"))"></select>
</div>
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-4">
<ul asp-for="haveAccess" class="control-label" id="haveAccess">
#foreach (var item in (new SelectList(ViewBag.haveAccess, "DepartmentID", "DepartmentName", "HaveAccess")))
{
<li class="checkbox-label">
<div class="checkbox">
#Html.CheckBox("HaveAccess", #item.Selected)
#Html.Label("HaveAccess", #item.Text)
</div>
</li>
}
</ul>
</div>
</form>
My js on-change for changeid (user ddl)
<script type="text/javascript">
$(document).ready(function () {
$("#changeid").change(function () {
var url = '#Url.Content("~/")' + "Admin/GetAccess";
var ddlsource = "#changeid";
$("#haveAccess").hide();
var items = " ";
$.getJSON(url, { UserID: $(ddlsource).val() }, function (data) {
$("#haveAccess").empty();
$.each(data, function (i, HaveAccess) {
items +=
"<li class='checkbox-label'>" +
"<div class='checkbox'>" +
"<input id='HaveAccess_" + HaveAccess.value + "' name='HaveAccess_" + HaveAccess.value + "' type='checkbox' " + "checked='" + HaveAccess.selected + "'/>" +
"<label for='HaveAccess_" + HaveAccess.value + "'>" + HaveAccess.text + "</label>" +
"</div>" +
"</li>";
});
$("#haveAccess").html(items);
$("#haveAccess").show();
});
})
})
</script>
JsonResult GetAccess
public JsonResult GetAccess(string UserID) {
List<EditUser> HaveAccess = new List<EditUser>();
//Getting Data from Database
con.Open();
string ua_query = "select gu.deptid as DepartmentID, d.department as DepartmentName , gu.have_access as Have_Access " +
"from it_materials_users u " +
"inner join it_materials_gu gu on u.id = gu.userid " +
"inner join it_materials_dept d on d.id = gu.deptid " +
"where u.id = '" + UserID + "'";
OracleCommand ua_cmd = new OracleCommand(ua_query, con);
OracleDataAdapter ua_da = new OracleDataAdapter(ua_cmd);
DataTable ua_dt = new DataTable();
ua_da.Fill(ua_dt);
foreach (DataRow ua_dr in ua_dt.Rows) {
HaveAccess.Add(new EditUser {
DepartmentID = Convert.ToInt16(ua_dr["DepartmentID"]),
DepartmentName = Convert.ToString(ua_dr["DepartmentName"]),
HaveAccess = Convert.ToBoolean(ua_dr["Have_access"])
});
}
con.Close();
var SelectedValues = HaveAccess.Where(a => a.HaveAccess == true).Select(u => u.DepartmentID).ToArray();
return Json(new MultiSelectList(HaveAccess, "DepartmentID", "DepartmentName", SelectedValues));
}
My load page works fine, but when I change the value of user the js triggers and the JsonResult GetAccess works as expected. But all the check-boxes at the browser are always checked even when the return of the sql HaveAccess is false.
Can someone point what I'm doing wrong?
Thanks in advance for your help.
Regards
all the check-boxes at the browser are always checked even when the return of the sql HaveAccess is false.
To fix above issue, please modify the code as below to set checked property for your checkboxes based on HaveAccess.selected value.
$.getJSON(url, { UserID: $(ddlsource).val() }, function (data) {
console.log(data);
$("#haveAccess").empty();
$.each(data, function (i, HaveAccess) {
var ischecked = HaveAccess.selected ? "checked" : "";
//console.log(ischecked);
items +=
"<li class='checkbox-label'>" +
"<div class='checkbox'>" +
"<input id='HaveAccess_" + HaveAccess.value + "' name='HaveAccess_" + HaveAccess.value + "' type='checkbox' " + ischecked + "/>" +
"<label for='HaveAccess_" + HaveAccess.value + "'>" + HaveAccess.text + "</label>" +
"</div>" +
"</li>";
});
$("#haveAccess").html(items);
$("#haveAccess").show();
});

Pass JSON result from AJAX to HTML

I am querying a fuseki server using AJAX and the result that I am getting is a JSON object.
I would like to use pagination to go through the result with a limit of records per page. I have tried to send the JSON object to a div in the html file but it is not working. Is there a workaround this? Here is my code:
function myCallBack2(data) {
var all_results = '';
for (var i = 0; i < data.results.bindings.length; i++) {
var bc = '';
if (i % 2 == 0) {
bc = '#b8cddb';
} else {
bc = '#f2f5f7';
}
all_results += '<div class="all_results" style="background-color:' + bc + '">';
for (var j = 0; j < data.head.vars.length; j++) {
var text = data.results.bindings[i][data.head.vars[j]].value;
var type = data.results.bindings[i][data.head.vars[j]].type;
all_results += '<div class="result_row">';
if (type == ('literal')) {
all_results += '<p> ' + data.head.vars[j] + ": " + text + '</p>';
} else {
all_results += '<a href=' + text + " title=" + data.head.vars[j] + '>' + text + '</a>';
}
all_results += '</div>';
}
all_results += '</div>';
}
$('#result').html(all_results);
}
function doSparql() {
var myEndPoint = "http://localhost:3030/Test/query";
name = document.getElementById("search").value;
var requiredName = "?Author foaf:firstName \"" + name + "\".}";
myQuery = ["PREFIX dcterms: <http://purl.org/dc/terms/>",
"PREFIX foaf: <http://xmlns.com/foaf/0.1/>",
"PREFIX locah: <http://data.archiveshub.ac.uk/def/>",
"SELECT ?Register ?Id ?Date ?Type",
"WHERE{",
"?Register dcterms:creator ?Author.",
"?Register dcterms:identifier ?Id.",
"?Register dcterms:type ?Type.",
"?Register locah:dateCreatedAccumulatedString ?Date.",
requiredName
].join(" ");
console.log('myQuery: ' + myQuery);
window.alert(myQuery);
$.ajax({
dataType: "jsonp",
url: myEndPoint,
data: {
"query": myQuery,
"output": "json"
},
success: myCallBack2,
error: myError
});
console.log('After .ajax');
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="//raw.github.com/botmonster/jquery-bootpag/master/lib/jquery.bootpag.min.js"></script>
<div id="page-selection1" "></div>
<div id="result " class="result "></div>
<div id="page-selection2 "></div>
<script>
$('#page-selection1,#page-selection2').bootpag({
total: 50,
page: 1,
maxVisible: 5,
leaps: true,
firstLastUse: true,
first: 'First',
last: 'Last',
wrapClass: 'pagination',
activeClass: 'active',
disabledClass: 'disabled',
nextClass: 'next',
prevClass: 'prev',
lastClass: 'last',
firstClass: 'first'
}).on("page ", function(event, num) {
$("#result ").html("Page " + num);
});
</script>
I am expecting to show part of the results instead Page 1, Page 2... in #result according to a limit per page.

.replacewith not working when called a second time

I have the following markup:
<fieldset>
<legend>Headline Events...</legend>
<div style="width:100%; margin-top:10px;">
<div style="width:100%; float:none;" class="clear-fix">
<div style="width:400px; float:left; margin-bottom:8px;">
<div style="width:150px; float:left; text-align:right; padding-top:7px;">
Team Filter:
</div>
<div style="width:250px; float:left;">
<input id="teamFilter" style="width: 100%" />
</div>
</div>
<div style="width:400px; float:left; margin-bottom:8px;">
<div style="width:150px; float:left; text-align:right; padding-top:7px;">
Type Filter:
</div>
<div style="width:250px; float:left;">
<input id="typeFilter" style="width: 100%" />
</div>
</div>
</div>
</div>
<div id="diaryTable" name="diaryTable" class="clear-fix">
Getting latest Headlines...
</div>
</fieldset>
I also have the following scripts
<script>
function teamFilterChange(e) {
//alert(this.value());
setCookie('c_team', this.value(), 90);
$c1 = getCookie('c_team');
$c2 = getCookie('c_type');
var param = "true|" + $c1 + "|" + $c2;
outputHLDiaryEntries(param);
}
function typeFilterChange(e) {
//alert(this.value());
setCookie('c_type', this.value(), 90);
$c1 = getCookie('c_team');
$c2 = getCookie('c_type');
var param = "true|" + $c1 + "|" + $c2;
outputHLDiaryEntries(param);
}
// This optional function html-encodes messages for display in the page.
function htmlEncode(value) {
var encodedValue = $('<div />').text(value).html();
return encodedValue;
}
function outputHLDiaryEntries(param) {
var url = "Home/DiaryEntries/";
var data = "id=" + param;
$.post(url, data, function (json) {
var n = json.length;
alert(n + ' ' + json);
if(n == 0){
//json is 0 length this happens when there were no errors and there were no results
$('#diaryTable').replaceWith("<span style='color:#e00;'><strong>Sorry: </strong> There are no headline events found. Check your filters.</span>");
} else {
//json has a length so it may be results or an error message
//if jsom[0].dID is undefined then this mean that json contains the error message from an exception
if (typeof json[0].dID != 'undefined') {
//json[0].dDI has a value so we
//output the json formatted results
var out = "";
var i;
var a = "N" //used to change the class for Normal and Alternate rows
for (i = 0; i < json.length; i++) {
out += '<div class="dOuter' + a + '">';
out += '<div class="dInner">' + json[i].dDate + '</div>';
out += '<div class="dInner">' + json[i].dRef + '</div>';
out += '<div class="dInner">' + json[i].dTeam + '</div>';
out += '<div class="dInner">' + json[i].dCreatedBy + '</div>';
out += '<div class="dType ' + json[i].dType + '">' + json[i].dType + '</div>';
out += '<div class="dServer">' + json[i].dServer + '</div>';
out += '<div class="dComment">' + htmlEncode(json[i].dComment) + '</div></div>';
//toggle for normal - alternate rows
if (a == "N") {
a = "A";
} else {
a = "N";
}
}
//output our formated data to the diaryTable div
$('#diaryTable').replaceWith(out);
} else {
//error so output json string
$('#diaryTable').replaceWith(json);
}
}
}, 'json');
}
$(document).ready(function () {
//Set User Preferences
//First check cookies and if null or empty set to default values
var $c1 = getCookie('c_team');
if ($c1 == "") {
//team cookie does not exists or has expired
setCookie('c_team', 'ALL', 90);
$c1 = "ALL";
}
var $c2 = getCookie('c_type');
if ($c2 == "") {
//type cookie does not exists or has expired
setCookie('c_type', "ALL", 90);
$c2 = "ALL";
}
// create DropDownList from input HTML element
//teamFilter
$("#teamFilter").kendoDropDownList({
dataTextField: "SupportTeamText",
dataValueField: "SupportTeamValue",
dataSource: {
transport: {
read: {
dataType: "json",
url: "Home/SupportTeams?i=1",
}
}
}
});
var teamFilter = $("#teamFilter").data("kendoDropDownList");
teamFilter.bind("change", teamFilterChange);
teamFilter.value($c1);
//typeFilter
$("#typeFilter").kendoDropDownList({
dataTextField: "dTypeText",
dataValueField: "dTypeValue",
dataSource: {
transport: {
read: {
dataType: "json",
url: "Home/DiaryTypes?i=1",
}
}
}
});
var typeFilter = $("#typeFilter").data("kendoDropDownList");
typeFilter.bind("change", typeFilterChange);
typeFilter.value($c2);
// Save the reference to the SignalR hub
var dHub = $.connection.DiaryHub;
// Invoke the function to be called back from the server
// when changes are detected
// Create a function that the hub can call back to display new diary HiLights.
dHub.client.addNewDiaryHiLiteToPage = function (name, message) {
// Add the message to the page.
$('#discussion').append('<li><strong>' + htmlEncode(name)
+ '</strong>: ' + htmlEncode(message) + '</li>');
};
// Start the SignalR client-side listener
$.connection.hub.start().done(function () {
// Do here any initialization work you may need
var param = "true|" + $c1 + "|" + $c2;
outputHLDiaryEntries(param)
});
});
</script>
On initial page load the outputHLDiaryEntries function is called when the signalR hub is started. If I then change any of the dropdownlists this calls the outputHLDiaryEntries but the $('#diaryTable').replaceWith(); does not work. If I refresh the page the correct data is displayed.
UPDATE!
Based on A.Wolff's comments I fixed the issue by wrapping the content I needed with the same element I was replacing... by adding the following line at the beginning of the outputHLDiartEntries function...
var outStart = '<div id="diaryTable" name="diaryTable" class="clear-fix">';
var outEnd = '</div>';
and then changing each of the replaceWith so that they included the wrappers e.g.
$('#diaryTable').replaceWith(outStart + out + outEnd);
replaceWith() replaces element itself, so then on any next call to $('#diaryTable') will return empty matched set.
You best bet is to replace element's content instead, e.g:
$('#diaryTable').html("<span>New content</span>");
I had the same problem with replaceWith() not working when called a second time.
This answer helped me figure out what I was doing wrong.
The change I made was assigning the same id to the new table I was creating.
Then when I would call my update function again, it would create a new table, assign it the same id, grab the previous table by the id, and replace it.
let newTable = document.createElement('table');
newTable.id = "sameId";
//do the work to create the table here
let oldTable = document.getElementById('sameId');
oldTable.replaceWith(newTable);

How do I insert an object data array into a database with AJAX

I want to insert data from an array into a database table in the submit() function where the sql syntax is at. I want to insert the data then redirect to another page after successful. I don't know how to do this with ajax.
I tried to make ajax syntax but I don't know if i'm passing the data correctly for obj.name and obj.books corresponding to their own values in the array.
example:
[{"name":"book1","books":["thisBook1.1","thisBook1.2"]},{"name":"book2","books":["thisBook2.1","thisBook2.2","thisBook2.3"]}]
function submit(){
var arr = [];
for(i = 1; i <= authors; i++){
var obj = {};
obj.name = $("#author" + i).val();
obj.books = [];
$(".auth" + i).each(function(){
var data = $(this).val();
obj.books.push(data);
});
//sql = ("INSERT INTO table (author, book) VALUES ('obj.name', 'obj.books')");
//mysqli_query(sql);
arr.push(obj);
}
$("#result").html(JSON.stringify(arr));
}
/////////////////////////////////
//I tried this:
$.ajax({
type: "POST",
data: {arr: arr},
url: "next.php",
success: function(){
}
});
/////////////////////////////////
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<style type="text/css">
<!-- #main {
max-width: 800px;
margin: 0 auto;
}
-->
</style>
</head>
<body>
<div id="main">
<h1>Add or Remove text boxes with jQuery</h1>
<div class="my-form">
<form action"next.php" method="post">
<button onclick="addAuthor()">Add Author</button>
<br>
<br>
<div id="addAuth"></div>
<br>
<br>
<button onclick="submit()">Submit</button>
</form>
</div>
<div id="result"></div>
</div>
<script type="text/javascript">
var authors = 0;
function addAuthor() {
authors++;
var str = '<br/>' + '<div id="auth' + authors + '">' + '<input type="text" name="author" id="author' + authors + '" placeholder="Author Name:"/>' + '<br/>' + '<button onclick="addMore(\'auth' + authors + '\')" >Add Book</button>' + '</div>';
$("#addAuth").append(str);
}
var count = 0;
function addMore(id) {
count++;
var str = '<div id="bookDiv' + count + '">' + '<input class="' + id + '" type="text" name="book' + id + '" placeholder="Book Name"/>' + '<span onclick="removeDiv(\'bookDiv' + count + '\')" style="font-size: 20px; background-color: red; cursor:pointer; margin-left:1%;">Remove</span>' + '</div>';
$("#" + id).append(str);
}
function removeDiv(id) {
//var val = confirm("Are you sure ..?");
//if(val){
$("#" + id).slideUp(function() {
$("#" + id).remove();
});
//}
}
function submit() {
var arr = [];
for (i = 1; i <= authors; i++) {
var obj = {};
obj.name = $("#author" + i).val();
obj.books = [];
$(".auth" + i).each(function() {
var data = $(this).val();
obj.books.push(data);
});
// sql = ("INSERT INTO table (author, book) VALUES ('obj.name', 'obj.books')");
// mysqli_query(sql);
arr.push(obj);
}
$("#result").html(JSON.stringify(arr));
}
</script>
</body>
</html>
Send your array to server ,stringify array before sending it to server so in server you can decode json and recover your array, and then insert received data to database
JS
function submit(){
var arr = [];
for(i = 1; i <= authors; i++){
var obj = {};
obj.name = $("#author" + i).val();
obj.books = [];
$(".auth" + i).each(function(){
var data = $(this).val();
obj.books.push(data);
});
//sql = ("INSERT INTO table (author, book) VALUES ('obj.name', 'obj.books')");
//mysqli_query(sql);
arr.push(obj);
}
sendToServer(arr)
$("#result").html(JSON.stringify(arr));
}
function sendToServer(data) {
$.ajax({
type: "POST",
data: {arr: JSON.stringify(data)},
url: "next.php",
success: function(){
}
});
}
PHP (next.php)
$data = json_decode(stripslashes($_POST['arr']));
foreach($data as $item){
echo $d;
// insert to db
}
Please Keep the following in mind
Javascript/JQuery is client side and hence cannot access the database which is on the server.
You can Send data via AJAX to next.php and then use this data to insert into your database.
To improve debugging, use the following code to ensure the correct data is being delivered in next.php
var_dump($_POST);
Your SQL statements must be executed in next.php using the data passed by $_POST (since your "type" of AJAX request is post).

Categories

Resources