jQuery post method fails if request is sent too fast - javascript

I have the below drop down list in my _Layout.cshtml
#Html.DropDownList("myList",
new SelectList(apps, "AppId", "Name", ViewBag.AppId),
new {#class = "mySelectBox", onchange = "updateAppLayout(this);"})
And the javscript function is in seperate .js file as :
function updateAppLayout(sel) {
var name = sel.options[sel.selectedIndex].text;
var appId = sel.options[sel.selectedIndex].value;
var data = { "appname": name, "appId": appId };
var url = "/Test/TestLayout";
$.post(url, data)
.done(function(msg) {})
.fail(function (xhr, status, error) {
});
}
Whenever i change the drop down value too fast the .fail() method is called. I put a console inside the .fail() method for the sel value and it gives this value - > select#myList.mySelectBox
But if i have the console just before the $.post method I get the dropdownlist.
Not sure whats wrong here.
PS: I do not want to use setTimeout

I would disable the select list while loading, this way you can ensure that it will only get new value on return of the first one
function updateAppLayout(sel) {
var name = sel.options[sel.selectedIndex].text;
var appId = sel.options[sel.selectedIndex].value;
document.getElementById("myList").disabled = true;
var data = { "appname": name, "appId": appId };
var url = "/Test/TestLayout";
$.post(url, data)
.done(function(msg) {
document.getElementById("myList").disabled = false;
//do something
})
.fail(function (xhr, status, error) {
});
}

Related

Insert user in PeopleOrGroup Field using javascript SharePoint 2013

I have only email address of user.
How to insert user in PeopleOrGroup Field using javascript SharePoint 2013.
If I directly pass email address to filed like
var MyUserEmail = 'mymanger's email adress' \\email id is proper and checked
oListItem.set_item('MyFieldName',MyUserEmail);
Throwing error as invalid data.
The following code for your reference:
<script src="//code.jquery.com/jquery-3.1.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
var ctx = SP.ClientContext.get_current();
var web = ctx.get_web();
var lists = web.get_lists();
var list = lists.getByTitle("CL");
var item = list.getItemById(1);
var assignedToVal = new SP.FieldUserValue();
var MyUserEmail = "app#xx.com";
var userId=GetUserId(MyUserEmail);
assignedToVal.set_lookupId(userId); //specify User Id
item.set_item("MyFieldName",assignedToVal);
item.update();
ctx.executeQueryAsync(
function() {
console.log('Updated');
},
function(sender,args) {
console.log('An error occurred:' + args.get_message());
}
);
});
function GetUserId(emailAddress){
var userId="";
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/siteusers?$select=Id&$filter=Email eq '"+emailAddress+"'";
//execute AJAX request
$.ajax({
url: requestUri,
type: "GET",
headers: { "ACCEPT": "application/json;odata=verbose" },
async: false,
success: function (data) {
if(data.d.results.length>0){
userId=data.d.results[0].Id;
}
},
error: function () {
//alert("Failed to get details");
}
});
return userId;
}
</script>
My code which is working. Do the Rest call. you can keep Ajax call as Asynchronous false to get the item before Execution Asynchronous () for item save

ajax postback method for refreshing dropdown list

Scoop...
I have a drop down list that might not display a particular option you're looking for. I added a button with pop up modal to type in a field you want to add to the drop down list. It functions perfectly, but I need to add an ajax postback method to refresh the list after the user hits enter. I don't want to refresh the whole page, just the list. any help?
Controller:
public ActionResult AddLeadSource()
{
return View();
}
[HttpPost]
public ActionResult AddLeadSource(string name)
{
LeadSource ls = new LeadSource();
ls.Name = name;
db.LeadSources.Add(ls);
db.SaveChanges();
return Json(new { success = true });
}
JS
<script>
$("#AddNew").change(function () {
var name = $("#Name").val();
// var order = $("#DisplayOrder").val();
$.ajax({
type: 'POST',
dataType: 'json',
cache: false,
url: '/Admin/LeadSource/AddLeadSource',
data: { name: name },
success: function (response) {
//alert("Success " + response.success);
$('#FollowUpNotes').kendoWindow('destroy');
// Refresh the DropDown <-- Heres where I need some help!
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error - ' + errorThrown);
}
});
});
In your success function of your Ajax call add this:
$("IdOfDropDownList").data("kendoDropDownList").dataSource.read();
In this way your dropdownlist will call the read function and reload all data. I assumed that your dropdownlist is binding throught read call.
I highly recommend looking at jQuery UI's autocomplete widget. That said,
$('#YourDropDownID option').remove(); //this will remove all option elements inside the <select id="YourDropDownID">
Then you just need to build new ones based on the response data,
for (var o in data) {
if (data[o].Value != undefined) {
$('#YourDropDownID').append('<option value="' + data[o].Value + '">' + ("" + data[o].Display) + '</option>');
}
}
I do this inside the .done() callback of my AJAX:
.done(function (data) {
//above code
}
Depending on the nature of the data you are sending back you may need to loop through it differently. Mine is an array of objects with a Value and Display properties (in my case, account numbers and account names).
//server side controller
var query = #"
Select
SubString([mn_no], 0, 6) As Value,
RTRIM([acct_desc]) As Display
From [some_table]";
return con.Query(query, new { AccountNumber = accounts.Select(x =>
{
return new { Value = x.Value, Display = x.Display };
});

Ajax request not posting ID to controller

I have wrote an AJAX post request to my deletewidget controller, it is posting the request token fine, however it does not seem to pass the widgetID to the controller. I have stepped through the javascript code and it assigns the ID to the variable widgetID fine, and have also put a breakpoint in my controller but it says null.
$(document).ready(function () {
$('#columns').on('click', '.glyphicon.glyphicon-trash', function (event) {
var panel = this;
//get id here
//toggle the modal
$('#deleteWidgetModal').modal('show');
var widgetID = $(this).closest('.panel.panel-default').attr('data-widgetid');
document.getElementById('delete-widget').onclick = function (event) {
event.stopPropagation();
//anti forgery token
//get the form
var form = $('#__AjaxAntiForgeryForm');
//from the form get the antiforgerytoken
var token = $('input[name="__RequestVerificationToken"]', form).val();
var URL = '/Dashboard/DeleteWidgetConfirmed';
//we make an ajax call to the controller on click
//because the controller has a AntiForgeryToken attribute
//we need to get the token from the form and pass it with the ajax call.
$.ajax({
url: URL,
data: {
__RequestVerificationToken: token,
id: widgetID
},
type: 'POST',
success: function(result){
var parentElement = $(panel).closest(".col-md-4.column");
var targetElement = $(panel).closest(".panel.panel-default");
targetElement.remove();
//parentElement.addClass("expand-panel");
checkEmptyPanelContainers();
$('#deleteWidgetModal').modal('hide');
},
error: function (jqXHR, textStatus, errorThrown) {
alert("An error has occurred please contact admin");
}
})
}
return false;
})
});
and here is my controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult DeleteWidgetConfirmed(int? id)
{
if(id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
WidgetModel widgetModel = db.widgets.Find(id);
db.widgets.Remove(widgetModel);
db.SaveChanges();
return new EmptyResult();
}
It seemed to be executing the ajax code twice, I moved my return false up one level and it solved the problem

ng-repeat update after build

I have a list of events that gets build from a JSON call to my server. The list gets parsed through ng-repeat. I want to implement a like button for the event and if its liked, replace that with unlike.
<a ng-show='event.liked==null' ng-click="like(event.event_id)">Like</a>
<a ng-show='event.liked!=null' ng-click="unLike(event.event_id)">Unlike</a>
Everything works perfectly except I have to refresh the feed to show "Unlike". Is there a way I can update the specific list item at the index that was liked once clicked without the need to refresh.
Please let me know if you need more information. Thanks!
edit: adding like function & unlike function. All it does is send request to my server to like or unlike a specific event with the event_id and user token.
$scope.like = function (event_id) {
var url = www.server.com?type=unlike&event_id=...
$http.post(url).success(function (data) {
console.log('success like');
//I want it to update my index here
}).error(function (data) {
console.log('fail like');
});
};
$scope.unLike = function (event_id) {
var url = www.server.com?type=unlike&event_id=...
$http.post(url).success(function (data) {
console.log('success unlike');
//I want it to update my index here
}).error(function (data) {
console.log('fail unlike');
});
};
Instead of passing in the event_id, pass the object to the like and unLike functions and update the object in success handler.
HTML
<a ng-hide='event.liked' ng-click="like(event)">Like</a>
<a ng-show='event.liked' ng-click="unLike(event)">Unlike</a>
Controller
$scope.like = function(event) {
var url = 'www.server.com?type=unlike&event_id=' + event.event_id;
$http.post(url).success(function (data) {
event.liked = true;
console.log('success like');
}).error(function (data) {
console.log('fail like');
});
};
$scope.unLike = function(event) {
var url = 'www.server.com?type=unlike&event_id=' + event.event_id;
$http.post(url).success(function (data) {
event.liked = null;
console.log('success unlike');
}).error(function (data) {
console.log('fail unlike');
});
};

Checking whether checkbox has been unchecked

I am trying to send post requests to the database dependant on whether a checkbox is checked or unchecked I want to add to database or delete from database with the post requests. I have managed to successfully get the add working via post request but I am unable to get it to delete using the jQuery below:
$(function () {
$("input:checkbox").change(function () {
var fullURL = document.URL;
var url = fullURL.split('userID=');
var userID = url[1];
var courseID = this.value;
var postData = { 'userId': userID, 'courseID': courseID };
if (!this.checked) {
$.post('/Admin/UnenrolUser/', postData, function (data) {
});
}
if (this.checked) {
$.post('/Admin/EnrolUser/', postData, function (data) {
});
}
});
});
My this.checked if statement seems to be working as expected. How can I get the unchecked to work in this context?
if (this.checked) {
$.post('/Admin/EnrolUser/', postData, function (data) {
});
} else {
$.post('/Admin/UnenrolUser/', postData, function (data) {
});
}
Try this
if(!$(this).is(':checked'))

Categories

Resources