cancel all ajax request when search field is empty - javascript

Cancel all Ajax Request if search field is empty and if the search character length is < 3
$('#search-box').keyup(function() { // bind the search data
var input = $('.search-input').val();
if (input.length >= 3) {
$.getJSON({ // get JSON data
url: 'example.com?keyword=' + input,
success: function(data) {
// do processing.
var output = "<ul class='search-lists'>"; //output search data list
$.each(data, function(key, val) {
output += '<li><a>' + val.term + '</a></li>';
});
output += '</ul>';
$('.search-results').html(output);
}
}); // JSON request
}
}); // data bind

From your code it's OK to use but what happens when second request finish after first request? for example first send "ab" and send "abc" later, the second result will be replace with the first. You can use abort() to abort the first connection before start the second one.
if(ajaxRequest){ajaxRequest.abort();}
ajaxRequest = $.ajax({
url: '...',
success: function(){
/* ... */
}
});

Use keyup event of search inputbox instead of section element.
$('#search').keyup(function() { // bind the search data
var input = $('.search-input').val();
if (input.length >= 3) {
$.getJSON({ // get JSON data
url: 'example.com?keyword=' + input,
success: function(data) {
// do processing.
var output = "<ul class='search-lists'>"; //output search data list
$.each(data, function(key, val) {
output += '<li><a>' + val.term + '</a></li>';
});
output += '</ul>';
$('.search-results').html(output);
}
}); // JSON request
}
}); // data bind

Related

Passing parameters to an anoynmous function in AJAX call

I'd like to load items from an XML file and display them on a webpage via AJAX and limit the output via a date range. However I am struggling to pass the parameters to the anonymous function. All tries to hand over the parameter 'displayDateLimit' have ended in syntax errors. Any idea how to do this?
In addition to that: If do not pass the the parameter I get an incremented counter for inpTest instead. Why does this happen?
// loads XML to Div-Element.
function loadItemsToBox(id)
{
var boxElement = document.getElementById('someid');
if (!boxElement){ return;}
xmlUrl = 'someurl'];
displayDateLimit = new Date().getTime();
displayDateLimit -= 3600*1000;
$.ajax({
type: "GET",
url: xmlUrl,
dataType: "xml",
success: function (xml) {
var content = "";
$(xml).find("item").each(function (inpTest) { // or "item" or whatever suits your feed
var el = $(this);
content += "<p>";
content += el.find("title").text() + "<br>";
content += "<br>DateLimit: " + inpTest;
content += "</p>";
})(displayDateLimit);
boxElement.innerHTML = content;
},
error : function(xhr, textStatus, errorThrown )
{
// some errorhandling
}
});
}

How to set the data in AJAX success function?

I have an ajax call that is returning me the data to be populated in a drop down list. Now, I need to be able to select a value which is returned and set the value of the drop down in the same function if possible. But by using $("#idOfDropDown").val(data), it is not getting set i.e While I am submitting the data, in the database all the options that were returned and populated are getting submitted and not the selected option. So, How do I set the selected value only?
Here's my AJAX function:
$.ajax({
type: "POST",
dataType: 'json',
url: "/Controller/Action",
data: {
param: param,
},
success: function(data) {
if (data.Response == "Unsuccessful") {
console.log("Unsuccessful");
} else if (data.Response == "Successful" || data.Response == "ConditionallySuccessful") {
for (var i = 0; i < data.ExteriorColor.Data.length; i++) {
$("#Exterior_Color").append($("<option></option>").val(data.ExteriorColor.Data[i]).html(data.ExteriorColor.Data[i]));
console.log(data.ExteriorColor.Data[i]);
}
var html = '<ul>'
for (var i = 0; i < data.Options.length; i++) {
html += '<li>' + data.Options[i] + '</li>';
}
html += '</ul>'
$("#twoColumnOptions").append(html);
$("#twoColumnOptions").data(html);
$("#Options").val(data.Options);
$("#Exterior_Color").val(data.ExteriorColor.Data).change(); //Value to be changed
if (data.ExteriorColor.isInstalled == true)
$("#Exterior_Color").attr("disabled", true);
}
},
error: function(result) {
console.log("Error while fetching data");
}
});
Try to trigger the change you made using .trigger('change') like:
$("#Options").val(data.Options).trigger('change');
//Or
$("#Options").val(data.Options).change();
I implemented something similar in my solution and my code is like this, you need to set the value like this:
success: function (response) {
var array = response;
if (array != '') {
for (i in array) {
$("#district").append("<option value='"+
array[i].Id + "'>" + array[i].DistrictName + "</option>");
}
}
},

Can't retrieve data in table from json

I am trying to load data into table using JQuery and AJAX but when I click on the button data is not retrieved. I have done coding as shown below:
var globalgrid;
Here I am going to call json url and try to display it in the table.
function loadgrid() {
$.ajax({
type: 'GET',
dataType: 'json',
url: 'http://instatalk.in/sip/GetApprovedUsersList?page=1&limit=10',
success: function(griddata) {
globalgrid = griddata.lines;
// remove all data - but the headers!
$("#gridtable").find("tr:gt(0)").remove();
if (globalgrid.length === 0) {
$('#errormsg').html('Sorry, <strong>no</strong> rows returned!');
return;
}
for (var i = 0; i < globalgrid.length; i++) {
var line = globalgrid[i];
// insert after last row!
$('#gridtable > tbody:last').append('<tr><td>' + line.Id + '</td><td>' + line.AccountId + '</td><td>' + line.Name + '</td><td>' + line.IsFranchiseUser + '</td></tr>');
}
},
error: function(data, errorText) {
$("#errormsg").html(errorText).show();
}
});
}
I am getting the table heading only. When I click on the button I want data to be retrieved from the json data. I don't know where I am going wrong. Please do help.
This is my json file:
{"results":[{"Id":17,"AccountId":"5737329468","Name":"Martin (Nigeria)","IsFranchiseUser":false},{"Id"
:16,"AccountId":"3644824444","Name":"Deep Patel","IsFranchiseUser":false},{"Id":15,"AccountId":"4692068407"
,"Name":"Jacob (kiribati)","IsFranchiseUser":false},{"Id":14,"AccountId":"4650982975","Name":"sebin John
(spain)","IsFranchiseUser":false},{"Id":13,"AccountId":"2855375107","Name":"Jassi want(new jersey)"
,"IsFranchiseUser":false},{"Id":12,"AccountId":"6242007588","Name":"Moussa","IsFranchiseUser":false}
,{"Id":11,"AccountId":"3075258818","Name":"srkrbm (saudi arab)","IsFranchiseUser":true},{"Id":10,"AccountId"
:"3615509810","Name":"Om Saini","IsFranchiseUser":false},{"Id":9,"AccountId":"9251133143","Name":"swati
mohandas","IsFranchiseUser":false},{"Id":8,"AccountId":"8143395019","Name":"babu Kuppu","IsFranchiseUser"
:false}],"totalAccounts":16}
This line: globalgrid = griddata.lines;
According to your Json data format, you should use griddata.results.

AJAX list update, get new elements and count

I have this HTML list
<ul id='usernameList'>
<li class='username'>John</li>
<li class='username'>Mark</li>
</ul>
and a form to add new names via AJAX, multiple add separated by commas. The response is a list with the names
[{name:David, newUser:yes}, {name:Sara, newUser:yes}, {name:Mark, newUser:no}]
I'm trying to insert this names sorted alphabetically in the list, like this example https://jsfiddle.net/VQu3S/7/
This is my AJAX submit
var form = $('#formUsername');
form.submit(function () {
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize(),
dataType: "json",
beforeSend: function () {
//
},
success: function (data) {
var listUsernames = $('#usernameList');
var numUsernames = listUsernames.children().length;
$.each(data, function(i, user) {
if(user.newUser == "yes"){
var htmlUser = "<li class='username'>" + user.name + "</li>";
var added = false;
$(".username", listUsernames).each(function(){
if ($(this).text() > user.name) {
$(htmlUser).insertBefore($(this));
added = true;
}
});
if(!added)
$(htmlUser).appendTo($(listUsernames));
}
// HERE I DO alert('numUsernames')
// I get the same number of users before sending form
// How can I update here the value of listUsernames and numUsernames?
});
}
});
return false;
});
My question is, how I can update the value of listUsernames and numUsernames after adding an item?
You just need to update numUsernames at that point.
Add this where your comments are:
numUsernames = listUsernames.children().length;
listUsernames already has the updated children, as it's a reference to the parent element.
Edit: Re: your comment below:
This should probably work:
$(".username", listUsernames).each(function(){
if ($(this).text() > user.name) {
$(htmlUser).insertBefore($(this));
added = true;
return false; // stop `.each` loop.
}
});
First you don't need a double jQuery wrapping:
$(htmlUser).appendTo($(listUsernames));
listUsernames is already a jQuery object, so try:
$(htmlUser).appendTo(listUsernames);
And after every adding, you can update the numUsernames variable with:
numUsernames = listUsernames.children().length;
but this is not necessary because you can always access listUsernames.children().length in the success handler.
I update your JSFiddle
var listUsernames = $('#usernameList');
var numUsernames = listUsernames.children().length;
var data = [{name:'David', newUser:'yes'}, {name:'Sara', newUser:'yes'}, {name:'Mark', newUser:'no'}]
$.each(data, function(i, user) {
if(user.newUser == "yes"){
var htmlUser = "<li class='username'>" + user.name + "</li>";
var added = false;
$(".ingredient", listUsernames).each(function(){
if ($(this).text() > user.name) {
$(htmlUser).insertBefore($(this));
added = true;
}
});
if(!added)
$(htmlUser).appendTo($(listUsernames));
}
// HERE I DO alert('numUsernames')
// I get the same number of users before sending form
// How can I update here the value of listUsernames and numUsernames?
});

Javascript / JQuery loop through posted ajax data string to assign new values to

I have a function which updates a database via ajax. My issue is then how to update the data displayed on the page to show updated details. The POST data can vary and therefore the datastring would be something like this:
var dataString = '[name resource we are editing]=1' +
'&para1='+ para1 +
'&para2=' + para2+
'&para3=' + para3
I want the function below to split or loop through each of the POST variables in the datastring to update the text of an element on the page. I cannot figure out how.
function editAccount(dataString, details, form){
status = $(".status");
$.ajax({
type: "POST",
url: "<?php echo BASE_PATH; ?>/edit/",
data: dataString,
success: function(response) {
$.each(response, function(key, value) {
success_code = key;
message = value;
});
if(success_code == 1){
status.text(message).addClass("valid");
//show details and hide form
$("#" + details).show();
$("#" + form).hide();
//HOW to do below?
//update details being displayed with datasource data
//loop through dataString to assign eg. $('#para1')text(para1);
} else {
status.text(message).addClass("invalid");
}
},
error: function(response){
status.text("There was a problem updating your details into our database. Please contact us to report this error.").addClass("invalid");
}
});
}
As mentioned in a previous comment, I would suggest declaring the dataString variable as an object:
var dataString = { '[name resource we are editing]' : 1,
'para1': para1,
'para2': para2,
'para3': para3
}
Now it'll be much easier to loop over the params, just using the function each, for instance, which you already use in your code:
$.each(dataString, function(key, value) {
// Do stuff with each param
});
EDIT:
As #Qpirate suggests, you also can use the javascript for loop:
for(var key in dataString){
// value => dataString[key]
}

Categories

Resources