Ajax request not aborting - javascript

I have a basic live search built with jQuery ajax which searches through a JSON file from the server and outputs a list of events.
My script is set so that if the search text box has less than 2 characters, it should display the list of the events which were already displayed on the page prior to the user using the ajax search.
var currentEvents = $(".event-list-container").contents();
if(searchField.length < 2)
{
if(currentRequest != null) {
currentRequest.abort();
}
$('.event-list-container').empty();
$('.event-list-container').append(currentEvents);
}
The issue I am having is that if the user were to quickly empty the textbox (e.g. by doing CTRL + A & backspace), the currentEvents would display and then the ajax request after that and therefore remove the currentEvents and display the results for what was in the search textbox before the user had emptied it.
Below is the full script for this:
$(document).ready(function () {
var currentEvents = $(".event-list-container").contents();
var currentRequest = null;
var searchField;
var expression;
$.ajaxSetup({
cache: false
});
$('#refine-event-txtbox').keyup(function () {
searchField = $('#refine-event-txtbox').val();
expression = new RegExp(searchField, "i");
if(searchField.length < 2)
{
if(currentRequest != null) {
currentRequest.abort();
}
$('.event-list-container').empty();
$('.event-list-container').append(currentEvents);
}
else
{
searchEvents(currentRequest, searchField, expression);
}
});
function searchEvents(currentRequest, searchField, expression)
{
currentRequest = jQuery.ajax({
type: 'GET',
url: 'http://127.0.0.1:8000/api/events',
success: function(data) {
$('.event-list-container').empty();
$.each(data, function (key, value) {
if (value.title.search(expression) != -1 ||
value.location.search(expression) !=
-1) {
var startDate = value.startDate;
var startDateDay = moment.utc(startDate).format('D');
var startDateMonth = moment.utc(startDate).format('MMM');
var fullDate = moment.utc(startDate).format('D MMM YYYY');
var eventURL = "/events/" + value.id + "/" + value.title;
eventURL = eventURL.replace(/\s+/g, '-').toLowerCase();
$('.event-list-container').append(
`<div class="event-box">
<div class="row">
<div class="col-xs-12 col-sm-2 col-md-2 col-lg-1">
<div class="date">
<p class="day">${startDateDay}</p>
<p class="month">${startDateMonth}</p>
</div>
</div>
<div class="col-xs-12 col-sm-4 col-md-3 col-lg-3">
<div class="event-image">
<a href="${eventURL}">
<img class="img-responsive" src="${value.image}">
</a>
</div>
</div>
<div class="col-xs-12 col-sm-6 col-md-7 col-lg-7">
<div class="event-details">
<h2 class="title">
${value.title}
</h2>
<p class="when"><span class="inline-title">When: </span>${fullDate} | ${value.startTime}-${value.finishTime}</p>
<p class="where"><span class="inline-title">Where:</span>${value.location}</p>
</div>
</div>
</div>
</div>
`);
}
});
},
error:function(e){
// Error
}
});
}});
As you can see inside the $('#refine-event-txtbox').keyup function if the search field length is set to less than 2, it should check to see if there is an ajax request and if so then abort it but the script is not doing this.

You can remove the reference of currentRequest from the function searchEvents.
Function Call:
searchEvents(searchField, expression);
And function:
function searchEvents(searchField, expression) {
.......
}
Try now..!

Figured it out. Adding the below to my ajax function as well as doing Shitole's answer seemed to do the trick.
beforeSend : function() {
if(currentRequest != null) {
currentRequest.abort();
}
},

Related

ajaxSetup for specific function (JS)

i am doing a project to have a single page dynamically fill with some html code fetch from a DataBase. I'll post the code:
$.ajaxSetup({
async: false
});
$(document).on("click", "#all-book", function () {
console.log("hello JQ!");
$.getJSON("./books", function (data) {
console.log(data);
categories = getCategories();
var htmlAppend = ``;
$.each(data, function (key, value) {
var index = categories.findIndex(function (category) {
return category.id == value.category_id;
});
console.log(`index: ${index}`);
console.log(categories);
htmlAppend = htmlAppend + `
<button class="btn col-lg-4 col-md-6 col-sm-12" id="specific-book-button" type="button" value="${value.id}" onclick="">
<div class="card">
<img src="https://picsum.photos/id/233/400/250" class="card-img-top" alt="...">
<div class="card-body">
<ul class="list-group list-group-flush">
<li class="list-group-item">Title: ${value.title}</li>
<li class="list-group-item">Author: ${value.author}</li>
<li class="list-group-item">Category: ${categories[index].name}</li>
</ul>
</div>
</div>
</button>
`
});
$("#button-card").html(htmlAppend);
});
});
function getCategories(i) {
var x = null;
$.getJSON(`./categories`, function (data) {
console.log(data);
x = data;
});
return x;
}
basically it gets two dictionary with the .getJSON() methods but because is asynchronous ill have to put ajaxSetup with the async: false.
Is there a way to setu up ajax only for some specific methods? I'll want to have some other methods async or for example if the user want to change page does not have to wait the getJSON.
Thanks :)

After clicked on Link Count One Down (-1) from Total of Count JavaScript - MVC

I have page ,where im showing all messages and in header im showing Total of messages by counting them and im looking for something with javascript or MVC ,when user click on link (its means message be opened) count one down (-1) of total count which is messages and then use localstorage or Cookies to remember the count for next time, when user coming back to check their messages.
Can anyone please help me or point me in the right direction!
Thanks in advance :)
For example : lets say i have 14 messages , when user click on link i should be 13
Controller:
public ActionResult Messages(RMAHistory m2)
{
string EmailID = Session["Email"].ToString();
ViewBag.CountMSG = (new DbNamespace().Besked.Where(x => x.KundensEmail == EmailID).Select(f => f.KundensEmail).ToList().Count);
var bla7 = (from RB in db.Besked
where RB.KundensEmail == EmailID
select new RMAHistory.Comment_List
{
id = RB.ID,
MSG = RB.MSG,
se = RB.Seen,
Date = RB.Date,
Forfatter = RB.Writer,
KundensEmail =RB.KundensEmail,
Id = RB.RMAID,
MSGType =RB.MSGType
});
m2.Comment_Lists = bla7.ToList();
return View(m2);
}
View:
<div class="col-lg-8 col-md-7 col-md-offset-2">
<div class="card">
<div class="card-header" data-background-color="purple">
<span class="category">(You have #ViewBag.CountMSG New Messages)</span>
</div>
<div class="content">
#if (!Model.Comment_Lists.Any())
{
<div class="bs-callout bs-callout-danger">
<h4>You Do not Have New Messages</h4>
</div>
}
else
{
foreach (var item in Model.Comment_Lists)
{
if (item.se == "Kunde")
{
<div class="bs-callout bs-callout-success message">
<div class="col-xs-3 text-right">
<a target="_blank" href="/Account/RMADetails?id=#item.Id" id="#item.id" class="btn btn-sm btn-success btn-icon btnChangestu"><i class="fa fa-envelope"></i></a>
</div>
<h4><i class="fa fa-bookmark-o" aria-hidden="true"></i> Message number #item.Id</span></h4>
<span class="text-muted"><small> #item.Date.ToString("dd/MMMM/yyy")</small></span><br />
<span class="text-muted status"><span> #item.MSGType</span></span>
<input type="hidden" name="ChangeStu" id="ChangeStu" value="read massage" />
</div>
}
}
}
</div>
</div>
</div>
JavaScript:
<script>
$(document).ready(function () {
$('.btnChangestu').click(function () {
var id = $(this).attr('id');
if (!id) {
return;
}
var button = $(this);
var status = $(this).closest('.message').find('.status');
$.ajax({
type: "POST",
url: '#Url.Action("UpdateMSGStatus", "Account")',
data: {
IDMSG: id,
ChangeStu: $("#ChangeStu").val()
},
dataType: 'json',
success: function (result) {
if (result) {
status.text("read message");
button.removeData('id')
console.log("Ok")
} else {
// display error?
console.log("error");
}
},
error: function () {
console.log('something went wrong - debug it!');
}
})
});
});
</script>

Add tab item dynamically not working as expected

<div class="page-content">
<div class="content-block">
<div id="tab-holder" class="buttons-row">
Tab 1
Tab 2
Tab 3
</div>
</div>
</div>
how should i add tabs dynamically?
Tab 1
I made a function like this but not working:
function createTabButton(_holder, _text, _isActive) {
var thm = $(`<a class="tab-link button ${_isActive ? 'active' : ''}">${_text}</a>`);
_holder.append(thm);
console.log(_text);
}
did i miss something ?
I did that using only Dom7(framework7 own dom manipulator), using almost the same code that you.
Used https://jsonplaceholder.typicode.com/ as example
<div class="page-content">
<div class="content-block">
<div id="tab-holder" class="buttons-row">
Tab 1
Tab 2
Tab 3
</div>
</div>
<button class="button">add</button>
</div>
Javascript - [Updated with template String]
var myApp = new Framework7();
// Export selectors engine
var $$ = Dom7;
$$("#btnLoad").on('click', function() {
$$.ajax({
url: "https://jsonplaceholder.typicode.com/todos",
data: {
'userId': 1
},
type: 'GET',
beforeSend: function(){
$$("#btnLoad").text("Loading...");
},
success: function(data) {
var list = JSON.parse(data);
for (var i = 0; i < 5; i++) {
createTabButton($$("#tab-holder"), list[i].id, list[i].completed);
}
$$("#btnLoad").text("Tabs Added");
}
});
});
function createTabButton(_holder, _text, _isActive) {
//var thm = $$('<a class="tab-link button ' + (_isActive ? 'active' : '') + '">' + _text + '</a>');
var thm = `<a class="tab-link button ${_isActive ? 'active' : ''}">${_text}</a>`;
_holder.append(thm);
}
http://jsfiddle.net/alexprazeres11/0cwvejcx/76/
Tested in Framework7 v1.4.2 and 1.6.4, it may work also on v2.0+.

change an element's text with variable id

I am designing a social network that has timeline and there is like button. I use AJAX to apply the like button on the server side. the problem is that I want to change the number of like for each post immediately after they have liked successfully. Because my elements are generated by for-each, I want to change the number of like for the exact element, I really have a problem with it.I am using thymeleaf.
I am looking for an idea that how to do this.
here is my html code:
<div class="col-sm-4">
<div class="row" >
<div class="col-sm-12">
<img th:if="${tweet.isFavorited()}" src="../static/images/like.png" th:src="#{/images/like.png}" th:class="like-img" th:id="${tweet.getId()}" width="35" height="35"/>
<img th:if="${!tweet.isFavorited()}" src="../static/images/dislike.png" th:src="#{/images/dislike.png}" th:class="like-img" th:id="${tweet.getId()}" width="35" height="35"/>
</div>
</div>
<div class="row">
<div class="col-sm-12" >
<h6 th:if="${tweet.isRetweet()}" th:class="like-count" th:id="${tweet.getId()}" th:text="${tweet.getRetweetedStatus().getFavoriteCount()}"></h6>
<h6 th:if="${!tweet.isRetweet()}" th:class="like-count" th:id="${tweet.getId()}" th:text="${tweet.getFavoriteCount()}"></h6>
</div>
</div>
and it is my script code:
$(function () {
$(".like-img").click(function () {
event.preventDefault();
var $post = $(this);
var toSend = {
"tweetId": this.getAttribute("id")
}
$.ajax({
type : "POST",
contentType: "application/json; charset=utf-8",
url : "like",
data : JSON.stringify(toSend),
dataType : 'json'
}).done(function (data) {
if(data.status == "success") {
if ($($post).attr("src") == "/images/dislike.png") {
$($post).attr('src','/images/like.png');
}
else {
$($post).attr('src','/images/dislike.png');
}
return false;
}
});
});
})
Okay so to make this work you will need to assign unique ids to the like-count elements, something like so:
<h6 th:if="${tweet.isRetweet()}" th:class="like-count" th:id="${tweet.getId()}_like_count" th:text="${tweet.getRetweetedStatus().getFavoriteCount()}"></h6>
Then you can retrieve the current count, increment it, and set the text of the count element. Something like so:
var currentCount = parseInt($('#'+toSend.tweetId+'_like_count').innerHtml)
var newCount = currentCount++;
$('#'+toSend.tweetId+'_like_count').text(newCount);

Accessing Newer Version of Variable from Different Scope (JavaScript / jQuery)

I want to populate the results div with the already loaded variable, data1, when the back button is clicked. With this code, when the back button is clicked, the results div gets set to "". How do I access the newer version of data1?
Javascript:
function finddata(def,id){
$("#doctitle").html($("#exp").val() + " - Writer's Dictionary");
$("#results").html('<span class="glyphicon glyphicon-cog glyphicon-spin" title="loading..."></span>').fadeIn();
if (def == 1) {
var word = id.innerHTML;
$.get( "processor.php?query=" + word + "&def=" + def, function(data2) {
$("#results").html(data2);
$("#back").click(function(){
$("#results").html(data1);
});
});
} else {
$.get( "processor.php?query=" + $("#exp").val(), function(data1) {
$("#results").html(data1);
});
}
}
HTML:
<div class="container">
<div class="col-md-6 col-md-offset-3" id="results">
<div id="back">Back</div>
</div>
</div>
Try
<div id="back" onclick="finddata(2)">Back</div>
to set def parameter to value other than 1 , which should call $.get() within else statement of finddata
Edit, Updated
var data;
function finddata(def) {
if (def === 1) {
// do stuff
} else {
// if `data` defined
if (data) {
// do not do stuff here
}
// else call `.get()`
else {
var word = id.innerHTML;
$.get( "processor.php?query=" + word + "&def=" + def, function(data2) {
$("#results").html(data2);
$("#back").click(function(){
$("#results").html(data1);
});
});
}
}
}
$("#back").click(function() {
finddata(2)
})
jsfiddle http://jsfiddle.net/229ad2b2/2/

Categories