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' />
Related
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
I have an API that gives me a user list and its edit button being created dynamically. the edit button needs to pass data into PATCH API. the form submits button just refreshes the page. without firing the PATCH API. Below is what I am trying to do:
function completeUserListRequest(result) {
console.log(result);
var givenName;
var familyName;
var eMail;
var status;
var userSub;
//console.log(result[0].Attributes[3].Name); // example to get the First Name
for (var counterx = 0; counterx < result.length; counterx++) {
//console.log(result[counterx].UserStatus);
userSub = result[counterx].Username;
var userStatus = result[counterx].UserStatus;
if (userStatus === 'CONFIRMED') {
status = 'Active';
} else if (userStatus === 'FORCE_CHANGE_PASSWORD'){
status = 'Pending';
} else {
status = 'Deactive';
}
for (var countery = 0; countery < result[counterx].Attributes.length; countery++) {
var attributeName = result[counterx].Attributes[countery].Name;
//console.log(attributeName);
if (attributeName === 'given_name') {
givenName = result[counterx].Attributes[countery].Value;
}
if (attributeName === 'family_name') {
familyName = result[counterx].Attributes[countery].Value;
}
if (attributeName === 'email'){
eMail = result[counterx].Attributes[countery].Value;
}
}
console.log(givenName + familyName + eMail + userSub);
var userTable = document.getElementById('user_table');
var userList = document.createElement('tr');
userList.innerHTML = '<td class="text-center">' + givenName + ' ' + familyName + '</td><td class="text-center">' +
eMail + '</td><td class="text-center"><span class="label label-primary">' + status + '</span></td><td class="text-center"><div class="btn-group"><button class="btn-default btn btn-xs"><a data-toggle="modal" href="#addStoreForm">Add Store</a></button><button id="editUserModal" value="' + userSub + '" class="btn-default btn btn-xs"><a data-toggle="modal" href="#editUserForm' + counterx + '">Edit User</a></button></div><div id="editUserForm' + counterx + '" class="modal fade" aria-hidden="true"><div class="modal-dialog"><div class="modal-content"><div class="modal-body"><form method="patch" role="form"><div class="form-group"><input id="userGivenName" type="text" placeholder="First Name" class="form-control" value="' + givenName + '"></div><div class="form-group"><input id="userLastName" type="text" placeholder="Last Name" class="form-control" value="' + familyName + '"></div><div class="form-group"><input id="userEmail" type="email" placeholder="E-mail" class="form-control" value="' + eMail + '"><input id="userUUID" type="hidden" value="' + userSub + '"><input id="userActiveStatus" type="hidden" value="' + userStatus + '"></div><br><div><button id="editUserBtn" class="btn btn-sm btn-primary m-t-n-xs" type="submit"><strong>Go!</strong></button></div></form></div></div></div></div></td>';
document.getElementById('user_table').appendChild(userList);
}
}
$('#editUserBtn').click(function (event) {
event.preventDefault();
var userName = $('#userUUID').val();
var userGivenNameBoxValue = $('#userGivenName').val();
var userLastNameBoxValue = $('#userLastName').val();
var userEmailBoxValue = $('#userEmail').val();
console.log(userGivenNameBoxValue);
console.log(userLastNameBoxValue);
console.log(userEmailBoxValue);
console.log(userStatusBoxValue);
console.log(userName);
//var userStatusValue = $('#userStatus').val();
//editUser (userName, userGivenNameBoxValue, userLastNameBoxValue, userEmailBoxValue);
$('#editUserForm').modal('hide');
});
function editUser (userName, userGivenNameBoxValue, userLastNameBoxValue, userEmailBoxValue) {
alert("lets run this");
console.log(givenNameBoxValue);
console.log(familyNameBoxValue);
console.log(emailBoxValue);
$.ajax({
method: 'PATCH',
url: _config.api.invokeUrl + '/admin/user/' + userName,
headers: {
Authorization: authToken
},
data: JSON.stringify({
given_name: userGivenNameBoxValue,
family_name: userLastNameBoxValue,
email: userEmailBoxValue
}),
contentType: 'application/json',
success: function(result){
completeEditUserRequest(result);
},
error: function ajaxError(jqXHR, textStatus, errorThrown) {
console.error('Error requestUserList: ', textStatus, ', Details: ', errorThrown);
console.error('Response: ', jqXHR);
alert('An error occured when requesting your user list:\n' + jqXHR);
}
});
}
function completeEditUserRequest (result) {
//console.log(result);
if (result !== []){
alert("User Details Changed Successfully!");
} else {
alert("Error! Please try again.");
}
}
If you see the code you will be able to see clearly that I am creating a table dynamically in which each row has Name, Email, A button to add stores and another one to edit the row/user. the edit button opens a modal form that uses the PATCH API.
I have a javascript code which renders <ol><li></li></ol> , Using a json from the server . The code looks something like this
function loadWorkFlowRules() {
var wf_id = <?php echo $wf->id; ?>;
$.post("/api/wfengine/get_wf_rules/", {
wf_id: wf_id
}, function(result) {
var wf_rules = JSON.parse(result).data;
if (makeView(wf_rules)) {
toastr.success('The Rules are Successfully Loaded!');
} else
toastr.info('Welcome to Work Flow Editor');
});
}
function makeView(wf_rules) {
//console.log(wf_rules);
var html_str = '',
response = false;
$.each(wf_rules, function(key, value) {
if (value.length > 0) {
$.each(value, function(key1, value1) {
var ui_l1 = '<li class="alert mar" data-id="' + value1.id + '" data-name="' + value1.name + '" style=""><div class="dd-handle state-main">' + value1.name + '<span class="cust-close" data-dismiss="alert" aria-label="Close"><i class="fa fa-times"></i></span></div><ol>';
html_str = html_str + ui_l1;
if (value1.children.length > 0) {
$.each(value1.children, function(key2, value2) {
$.each(value2, function(key3, value3) {
var ui_l2 = '<li class="alert mar" data-id="' + value3.id + '" data-name="' + value3.name + '" style=""><div class="dd-handle state-main">' + value1.name + '<span class="cust-close" data-dismiss="alert" aria-label="Close"><i class="fa fa-times"></i></span></div><ol>';
html_str = html_str + ui_l2;
if (value3.children.length > 0) {
$.each(value3.children, function(key4, value4) {
if (value4.length > 0) {
var ui_l3 = '<li class="dd-item alert mar action" data-id="' + value4[0].id + '" data-name="' + value4[0].name + '" data-api="' + value4[0].api + '" data-url="' + value4[0].url + '" data-json="' + value4[0].json + '" style=""><div class="dd-handle">' + value4[0].name + '<span class="cust-close" data-dismiss="alert" aria-label="Close"><i class="fa fa-times"></i></span> <span class="edit cust-close" data-toggle="modal" data-target="#editAction" ><i class="fa fa-pencil"></i></span></div></li>';
html_str = html_str + ui_l3;
}
})
}
html_str = html_str + '</ol></li>';
});
})
}
html_str = html_str + '</ol></li>';
});
$('.contract_main').html(html_str);
response = true;
} else
response = false;
});
return response;
}
HTML
<div class="dd">
<ol class="dd-list simple_with_drop vertical contract_main">
</ol>
</div>
I got into a situation where Ill have to Bind the data element of the child <li> with an HTML MODAL popup , So that if the value in Modal is updated it shoud change in the Object/Dom also .
I was recommended to use VueJs.
I have went through! the basics of the VueJs , But that didn't cover how I ccan bind complete list from a Json ,
Any help in how I can do this would be great
Currently I don't see any structure of Vue.Js in your code and you are manipulating the JSON data and constructing the HTML in the JS code itself. You can do it in vue way, where you will create an Vue instance, do loading of data in Vue methods and use Vue syntax to iterate over data and other things. One Simple example you can see in this fiddle or in below code:
new Vue({
el: '#app',
data: {
jsonData: []
},
mounted () {
this.loadJsonData();
},
methods: {
loadJsonData(){
setTimeout(()=>{
this.jsonData = ["first", "Second", "Third", "And So On"]
}, 300)
}
}
})
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<div id="app">
<ul>
<li v-for="data in jsonData">{{data}}</li>
</ul>
</div>
You can look at vue-hackernews to understand more about structuring of code, How to fetch data from remote APIs in JSON format and display it.
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);
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).