how to remove already present data while making search - javascript

I had to integrate search engine in website. But there is already a list of data on first page.
my question is how this data should hide or remove when making a new search request. !https://1drv.ms/f/s!AsW4Pb3Y55Qjb34OtQI7qQotLzc
In mention image let I enter something to search and upon hitting enter how the present elements should be removed.
I mean after getting successful response how can I remove the already present list of data on website.
I tried to find resources but no clue. If someone give me some directions, I will be thankful. I am completely new to ajax and jquery.
Code start :
$("#search").keyup(function(){
clearInterval(timer);
timer = setInterval(update, 50);
});
function update() {
clearInterval(timer);
var myInput = $("#search").val();
if ((myInput != "") && (myInput != searchText)) {
$.ajax({
url: '/search-start',
type: 'GET',
data: {"data": myInput},
success: function (response) {
console.log(response);
},
error: function () {
console.log("Error.")
}

Assumptions
<div id="data-container"> <!-- main container which holds your data list -->
<ul id="data-list"> <!-- list of data here -->
<li>Data 1</li>
<li>Data 2</li>
<!--- ...other datas --->
</ul>
</div>
Then
$.ajax({
url: '/search-start',
type: 'GET',
data: {"data": myInput},
success: function (response) {
if(/**response contains correct data**/){
$('#data-list').html(''); // empty the data list
//prepare the data list view like
var newDataList = "";
$.each(response['data'], function(key, val){
newDatalist += "<li>"+val+"</li>";
});
// then append your new data to the data list
$('#data-list').html(newDataList);
}
},
error: function () {
console.log("Error.")
}
});

Related

How to find the id of the html while looping through <tr> in javascript/jquery

I'm working on a queue management page where we have multiple Html tables on a single page and each table holds 10 values including name and image, now I wanna remove a row from the table when the present button is pressed and I did it using this following code
function removePresent() {
const urlParams = new URLSearchParams(window.location.search);
const HallNo = urlParams.get('hallno');
const TvIP = urlParams.get('tvip');
$.ajax({
url: '#Url.Action("PresentDisplayRemover")',
type: "GET",
data: { 'HallNo': HallNo, 'TvIP': TvIP },
contentType: "application/json",
success: function (response) {
$.each(response, function (j, e) {
const rows = Array.from(document.getElementsByTagName('TD'));
$.each(rows, function (i) {
if ($(rows[i]).text() === e.StudentId) {
$(rows[i]).parent().remove();
}
});
}
});
}
Now my flow also requires me to find the Id of the matched to increment a counter, I have no idea how to do it and I also tried searching online but I ended up finding nothing,I'm relatively new to js and jquery since my main workflow only consists of me working with .NET so any help would be great, Thank You.

Adding to JSON array by HTML button

I have an AJAX call, as below. This posts data from a form to JSON. I then take the values and put them back into the div called response so as to not refresh the page.
$("form").on("submit", function(event) { $targetElement = $('#response'); event.preventDefault(); // Perform ajax call // console.log("Sending data: " + $(this).serialize()); $.ajax({
url: '/OAH',
data: $('form').serialize(),
datatype: 'json',
type: 'POST',
success: function(response) {
// Success handler
var TableTing = response["table"];
$("#RearPillarNS").empty();
$("#RearPillarNS").append("Rear Pillar Assembly Part No: " + response["RearPillarNS"]);
$("#TableThing").empty();
$("#TableThing").append(TableTing);
for (key in response) {
if (key == 'myList') {
// Add the new elements from 'myList' to the form
$targetElement.empty();
select = $('<select id="mySelect" class="form-control" onchange="myFunction()"></select>');
response[key].forEach(function(item) {
select.append($('<option>').text(item));
});
$targetElement.html(select);
} else {
// Update existing controls to those of the response.
$(':input[name="' + key + '"]').val(response[key]);
}
}
return myFunction()
// End handler
}
// Proceed with normal submission or new ajax call }) });
This generates a new <select id="mySelect">
I need to now extract the value that has been selected by the newly generated select and amend my JSON array. Again, without refreshing the page.
I was thinking of doing this via a button called CreateDrawing
The JS function for this would be:
> $(function() {
$('a#CreateDrawing').bind('click', function() {
$.getJSON('/Printit',
function(data) {
//do nothing
});
return false;
});
});
This is because I will be using the data from the JSON array in a Python function, via Flask that'll be using the value from the select.
My question is, what is the best way (if someone could do a working example too that'd help me A LOT) to get the value from the select as above, and bring into Python Flask/JSON.

Using JavaScript to refresh or retrieve current information on button click

I'll preface this with I'm still new to JavaScript. So problem is in a larger application, our controller is passing in a list of information to the view where certain JavaScript functions rely on certain ViewModel properties. I've written a simple application to hopefully illustrate what I'm getting at.
Below is a sample controller that's passing in List to the Index page:
public ActionResult Index() {
List<int> activeIds = new List<int>();
SqlConnection sqlConn = new SqlConnection(connection_String);
sqlConn.Open();
string sqlStr = "SELECT * FROM dbo.[JS-Test] WHERE Active = 1";
SqlCommand sqlCmd = new SqlCommand(sqlStr, sqlConn);
SqlDataReader sqlDR = sqlCmd.ExecuteReader();
if(sqlDR.HasRows) {
while (sqlDR.Read()) {
activeIds.Add((int)sqlDR["ID"]);
}
}
sqlDR.Close();
sqlCmd.Dispose();
sqlConn.Close();
return View(activeIds);
}
This returns the current "active" items in the database. The (rough) view is as follows...
#model List<int>
#{
ViewBag.Title = "Index";
}
<p>Current Recognized Count: #Model.Count() </p>
Print
<script>
$(document).ready(function () {
$('#printBtn').click(function () {
var numberOfActiveIds = #Model.Count();
$.ajax({
type: "POST",
url: "/Home/PostResults",
data: { ids: numberOfActiveIds},
success: function (results) {
if(results == "Success") {
window.location.href = '/Home/Results';
}
}
});
});
});
</script>
The issue is getting the current number of active items from the database when the button is clicked. Let's say that the user remains idle on the page after it loads for a few minutes. When their page originally loaded, the model returned 5 items listed as active... but while they've been waiting 3 additional items were switched to active in the database for a total of 8. However, when the user finally clicks the button it'll submit 5 items instead of the current 8.
I'm unable to run the query to get the current number of active items in the "/Home/PostResults" ActionResult due to the nature of how the larger application is set up. Is there a way I could refresh the page (getting the updated model) before the rest of the function carries out using values of the refreshed model?
If you have any additional questions, please let me know and I will gladly comply. I've looked at other questions and answers on SO but I haven't found one that quite works for my situation. Thanks!
Edit #1
So, I've added this function to the Home controller which just returns the list count as Json.
public ActionResult GetIds(){
List<int> activeIds = new List<int>();
SqlConnection sqlConn = new SqlConnection(connection_String);
sqlConn.Open();
string sqlStr = "SELECT * FROM dbo.[JS-Test] WHERE Active = 1";
SqlCommand sqlCmd = new SqlCommand(sqlStr, sqlConn);
SqlDataReader sqlDR = sqlCmd.ExecuteReader();
if (sqlDR.HasRows) {
while (sqlDR.Read()) {
activeIds.Add((int)sqlDR["ID"]);
}
}
sqlDR.Close();
sqlCmd.Dispose();
sqlConn.Close();
return Json(activeIds.Count());
}
The view script now looks like this...
<script>
$(document).ready(function () {
$('#printBtn').click(function () {
var numberOfActiveIds = #Model.Count();
$.ajax({
type: "GET",
url: "/Home/GetIds",
success: function(response) {
numberOfActiveIds = response;
$.ajax({
type: "POST",
url: "/Home/PostResults",
data: { ids: numberOfActiveIds},
success: function (results) {
if(results == "Success") {
window.location.href = '/Home/Results';
}
}
});
}
});
});
});
</script>
I'm currently getting the following error...
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
Edit #2
I had to set the JsonRequestBehavior to AllowGet for it to work properly. Thanks again, everyone!
gforce301 mentioned to GET the current actives via an ajax call to an additional, separate method making the query to the database and THEN ajax post the returned "actives". Is that possible?
Yes this is possible. That's why I mentioned it. Irregardless of other peoples opinions on how they think you should do this, I understand that you may be limited on why you can't do it their way even if they don't.
The code below is a restructuring of your code. It chains 2 ajax calls together, with the second one depending on the success of the first. Notice the comment block in the success handler of the first ajax call. Since I don't know what the response will be, I can't fill in the part on how to use it. This accomplishes your goal of having the user only make a single button click.
<script>
$(document).ready(function () {
$('#printBtn').click(function () {
var numberOfActiveIds = #Model.Count();
$.ajax({
type: 'GET',
url: '/path/to/get/activeIds',
success: function(response) {
/*
Since I don't know the structure of response
I have to just explain.
use response to populate numberOfActiveIds
now we just make our post ajax request.
*/
$.ajax({
type: "POST",
url: "/Home/PostResults",
data: { ids: numberOfActiveIds},
success: function (results) {
if(results == "Success") {
window.location.href = '/Home/Results';
}
}
});
}
});
});
});
</script>
I can give you an idea, i hope it can help,
run another ajax 1st on btnclick to get the data(or datat count) again, if the record count is greater then current then update the view and don't PostResults and if its same then just PostResults
on ajax success you can reload the data or view
and on failure(when no new record) just do PostResults

jQuery Mobile listview styles not refreshing after emptying and dynamically recreating the list items

I have a listview which has its list items created by javascript code. The first time the code runs, it works fine. The second time it runs, the list is created and works fine, but the jQuery Mobile styling is gone. Searching other threads has led me to try the following lines of code in different places, to no avail:
$('#ul').listview('refresh');
and
$('#ul').listview().listview('refresh');
and
$('#ul').trigger('create');
My listview is declared in html like this:
<div ID="myUL" class="nav">
<ul data-role="listview" ID="ul"></ul>
</div>
and the following javascript creates the list items:
$.ajax( {
async: 'false',
type:'POST',
url:'[redacted]',
contentType: "text/xml",
dataType: "xml",
data: soapRequest,
success:function processSuccess(data, status, req) {
var returnString = $(req.responseXML).find("GetMyWebServiceResult").text().split("|");
$("#ul").children().remove('li');
for (var i = 0; i < length; i++) {
var addressString = returnString[i].split(";");
//create list item
var myList = document.getElementById("ul");
var liSold = document.createElement("li");
var aTag = document.createElement('a');
aTag.innerHTML = addressString[0];
aTag.setAttribute('onClick','somefunction(i)');
aTag.setAttribute('data-transition','slide');
liSold.appendChild(aTag);
myList.appendChild(liSold);
}
$('#ul').listview('refresh');
},
error: function(e){
alert('error 2: ' + e);
}
})
Also, I'm doing this in a phonegap (cordova) app, if that makes a difference.
EDIT Additional details:
The page div is not in focus anymore when the list is recreated. Also, the js code snippet is located in a function that is called when a webservice is successfully consumed.
it is wrong with list id.try
$('#myUL').listview('refresh');

Filtering AJAX returned data and performing .each on selected elements within

Lets say I have 4 tabs within nothing in them until they are clicked (lazy load concept).
When:
Tab1 is clicked: Data is inserted into that tab via ajax.
Tab2 is clicked: Data is inserted into that tab via ajax.
etc.
The data that's being returned consists of:
<ul class="elements">
<li>
<div>Stuff</div>
<ul class="comments">
...Initially empty
</ul>
</li>
</ul>
Now in the success function I'm calling another function that gets all the comments associated with the li children of the parent ul.elements and this is where I'm having trouble.
So after all the elements are loaded into the tab, I have this function which needs doctoring:
function LoadComments(data) {
$newData = $(data).filter('ul.elements');
$newData.find('ul.comments').each(function() {
var commentsHome = $(this);
$.ajax({
url: '/MyFeed.aspx',
type: 'POST',
dataType: 'html',
data: {
"xfd" : "GetComments',
},
success: function(data) {
commentsHome.html(data);
}
});
});
}
So far my variable commentsHome doesn't seem to be working. My goal here is to load the comments for each returned element of the new data only. So when Tab2 is clicked, this function is performed only on the data returned after clicking on Tab2.
Not sure what I'm doing wrong :(
The commentsHome variable won't be available to you in the AJAX success function.
However, you can create a hidden <input type="hidden" id="commentsHome" /> and store the value in there, then reference that in the AJAX success function.
function LoadComments(data) {
$newData = $(data).filter('ul.elements');
$newData.find('ul.comments').each(function() {
$('#commentsHome').val($(this));
$.ajax({
url: '/MyFeed.aspx',
type: 'POST',
dataType: 'html',
data: {
"xfd" : "GetComments',
},
success: function(data) {
var commentsHome = $('#commentsHome).val();
commentsHome.html(data);
}
});

Categories