MVC4 #Html.Checkboxfor issue with Ajax call - ajax

I was working with MVC CheckBox for.
#Html.CheckBoxFor(m=>m.IsActive, new { #id = "IsActive",#checked = "checked" })
if ($('#frmmenu').valid())
{
//alert("MenuTitle=" + $("#MenuTitle").val() + "&OrderNumber=" + $("#OrderNumber").val() + "&IsActive=" + $("#IsActive").val());
alert("MenuTitle=" + $("#MenuTitle").val() + "&OrderNumber=" + $("#OrderNumber").val() + "&IsActive=" + $("#IsActive").val());
$.ajax({
type: 'POST',
url: '/api/MenuWebApi/SetMenu',
data: "MenuTitle=" + $("#MenuTitle").val() + "&OrderNumber=" + $("#OrderNumber").val() + "&IsActive=" + $("#IsActive").val(),
success: function (data)
{
if (data.Success == true)
{
//window.location = '/Profile/UserProfile';
}
},
error: function (xhr, textStatus, errorThrown)
{
//window.location = JsErrorAction;
},
dataType: "json",
headers:
{
'RequestVerificationToken': JsTokenHeaderValue
}
});
}
return false;
with passing data when checkbox is checked it is giving true value, but if unchecked then it will give true value not false, how could i do?
please help me anyone.
Regards

Try with this:
var isActive = ($('#IsActive').attr('checked') == 'checked');
// $('#IsActive').attr('checked') will return
// 'checked' or undefined - if not checked/not containing 'checked' attribute

Related

Returning error from controller to AJAX jQuery

I works with ASP.net MVC and I have get "Error" from belowe my JavaScript code:
This is my AJAX jQuery code:
$(document).ready(function () {
var dataId;
$(".item2 .small-img").click(function () {
dataId = $(this).data("id");
var url = '#Url.Action("DecorationTest", "Carpet")' + "?Id=" + dataId + "&title=" + '#Url.ToFriendlyUrl(Model.Title.ToString())';
$('#dateLink').prop('href', url);
$.ajax({
url: '/Carpet/CheckCarpet',
type: 'POST',
dataType: 'Json',
data: '{"CarpetImageid":"' + dataId + '"}',
contentType: 'application/json; charset=utf-8',
success: function (data) {
if (data.Success == false)
$('#dateLink').hide();
else
$('#dateLink').show();
alert("Success");
},
error: function (errorThrown) {
alert("Error");
}
});
and this is a controller code:
[HttpPost]
public ActionResult CheckCarpet(int CarpetImageid)
{
bool DecorShow = false;
DecorShow = db.Images.Where(x => x.Id == CarpetImageid).FirstOrDefault().DecorTest;
return Json(new JsonData { Success= DecorShow });
}
what's the reason? Someone knows?
I found the solution.i change url to #Url.Action("CheckCarpet", "Carpet") and fixed.
$(".small-img").click(function () {
dataId = $(this).data("id");
var url = '#Url.Action("DecorationTest", "Carpet")' + "?Id=" + dataId + "&title=" + '#Url.ToFriendlyUrl(Model.Title.ToString())';
$('#dateLink').attr('href', url);
$.ajax({
url:'#Url.Action("CheckCarpet", "Carpet")',
type: 'Post',
dataType: 'Json',
data: '{"CarpetImageid":"' + dataId + '"}',
contentType: 'application/json; charset=utf-8',
success: function (result) {
if (result.Success == false) {
$('#dateLink').hide();
$('.p2').hide();
}
else {
$('#dateLink').show();
$('.p2').show();
}
},
error: function (error) {
alert(error.d);
}
});
});

Error In Ajax Call In html

If I Run The Following Code It's Directly Go To Error:Ajax Failed And Error Show on Fire Bug [Reference Error: Ajax Failed is not defined"].
Plz Tell Where I Make Mistake....?
Its My base 64 Encode Value For Name,Email,Gender,Password
var encodeRname = Base64.encode(name);
var encodeRemail = Base64.encode(email);
var encodeRgender = Base64.encode(lookingfor);
var encodeRpwd = Base64.encode(Pword);
var test = '.1!qkr*';
var decodertr = Base64.decode(test);
IT's My AJAX Call For Post
$.ajax({
//https://www.xxxxxxxxx.com/yyyyyyyyy/zzzzzzzzzzzz.svc/InsertRegistrationDetailsoverHTTPS?AuthToken={AUTHTOKEN}&RegName={REGNAME}&selGender={SELGENDER}&UserName={USERNAME}&UserPass={USERPASS}
url: "https://www.XXXXXXX/YYYYYY/ZZZZZZZZ.svc /InsertRegistrationDetailsoverHTTPS?AuthToken=" + decodertr + "&RegName=" + encodeRname + "&selGender=" + encodeRgender + "&UserName=" + encodeRemail + "&UserPass=" + encodeRpwd,
type: "POST",
contentType: "application/javascript",
dataType: "jsonp",
success: function (msg) {
},
error: AjaxFailed
});
function AjaxSucceeded(result) {
alert("success");
}
function AjaxFailed(result) {
alert('Error is : ' + result.status + ' ' + result.statusText);
}
Your error handling function must be defined like the following:
$.ajax({
//https://www.xxxxxxxxx.com/yyyyyyyyy/zzzzzzzzzzzz.svc/InsertRegistrationDetailsoverHTTPS?AuthToken={AUTHTOKEN}&RegName={REGNAME}&selGender={SELGENDER}&UserName={USERNAME}&UserPass={USERPASS}
url: "https://www.XXXXXXX/YYYYYY/ZZZZZZZZ.svc /InsertRegistrationDetailsoverHTTPS?AuthToken=" + decodertr + "&RegName=" + encodeRname + "&selGender=" + encodeRgender + "&UserName=" + encodeRemail + "&UserPass=" + encodeRpwd,
type: "POST",
contentType: "application/javascript",
dataType: "jsonp",
success: function (msg) {
},
error: function (error) {
// your error handling
}
});

processing return from ajax call

I'm using the twitter-bootstrap's typeahead to do autocompletion on an input field.
What I have so far:
$(".airportSearch").typeahead({
source: function(typeahead, query) {
$.ajax({
url: url_,
dataType: "json",
data: {
n: 12,
q: typeahead
},
success: function(data) {
var return_list = [], i = data.length;
while(i--) {
return_list[i] = {
type: data[i].type,
id: data[i].iata,
value: data[i].city,
returnvalue: data[i].type == 'city' ? data[i].city + ' [' + data[i].iata + ']' :
data[i].city + ' (' + data[i].iata + ')'
};
}
}
});
}
});
example of output:
[{"type":"airport","city":"Quebec","airport":"Quebec","iata":"YQB","country":"Canada","locationId":"airport_YQB"},
{"type":"airport","city":"Queenstown","airport":"Queenstown","iata":"ZQN","country":"New Zealand","locationId":"airport_ZQN"},
{"type":"city","city":"Setif","airport":"All Airports","iata":"QSF","country":"Algeria","locationId":"DZ_city_QSF"},
{"type":"airport","city":"Setif","airport":"Setif","iata":"QSF","country":"Algeria","locationId":"airport_QSF"},
{"type":"airport","city":"QachaS Nek","airport":"QachaS Nek","iata":"UNE","country":"Lesotho","locationId":"airport_UNE"},
{"type":"airport","city":"Qaisumah","airport":"Qaisumah","iata":"AQI","country":"Saudi Arabia","locationId":"airport_AQI"}]
I have logged the return_list variable that I create and have confirmed that it is the expected list of objects I have created. I want to populate the autocomplete options with the returnvalue strings in the list of objects.
Could anyone tell me how, or point me to somewhere that tells me how?
Try this:
$(".airportSearch").typeahead({
source: function(typeahead, process) {
return $.ajax({ // return ajax result
url: url_,
dataType: "json",
data: {
n: 12,
q: typeahead
},
success: function(data) {
var return_list = [], i = data.length, data_vals = []; // add data_vals array for typeahead
while(i--) {
return_list[i] = {
type: data[i].type,
id: data[i].iata,
value: data[i].city,
returnvalue: data[i].type == 'city' ? data[i].city + ' [' + data[i].iata + ']' :
data[i].city + ' (' + data[i].iata + ')'
};
data_vals.push(return_list[i].returnvalue); // populate the needed values
}
return process(data_vals); // and return to typeahead
}
});
}
});
Normally I would populate the data_vals for typeahead only but you did it your way for your reason I guess.
Hope it helps.

Trying to access Instagram API using jQuery

I'm trying to use the Instagram API and I'm making AJAX requests in a do-while loop until the next_url is null. All I want this code to do is to fetch all the followers by making continuous requests until it's done. What is wrong in this code?
When I remove the do-while loop it doesn't gives me an error, but as soon as a I use the AJAX request within a loop, it never stops. Clearly the $next_url string is not changing to the newly fetched next_url - why? What is wrong?
$(document).ready(function(e) {
$('#fetch_followers').click(function(e) {
var $next_url = 'https://api.instagram.com/v1/users/{user-id}/followed-by?access_token={access-token}&count=100';
var $access_token = '{access-token}';
var $is_busy = false;
var $count = 0;
do {
while($is_busy) {}
$.ajax({
method: "GET",
url: $next_url,
dataType: "jsonp",
jsonp : "callback",
jsonpCallback: "jsonpcallback",
success: function(data) {
$is_busy = true;
$.each(data.data, function(i, item) {
$("#log").val($("#log").val() + item.id + '\n');
});
$("#log").val($("#log").val() + data.pagination.next_url + '\n');
$next_url = data.pagination.next_url;
},
error: function(jqXHR, textStatus, errorThrown) {
$is_busy = true;
//alert("Check you internet Connection");
$("#log").val($("#log").val() + 'Error\n');
},
complete: function() {
++$count;
$is_busy = false;
}
});
} while($next_url !== '' || $count <= 50);
});
});
After I failed in my logic, I added the $count variable that can break the do-while loop, because the do-while loop was running infinitely. After adding it, it still runs infinitely, and I have no idea why.
Have the function call itself in the ajax success callback with the new url as a parameter:
$(document).ready(function() {
$('#fetch_followers').click(function() {
var $access_token = '{access-token}';
pollInstagram('https://api.instagram.com/v1/users/{user-id}/followed-by?access_token={access-token}&count=100');
});
});
function pollInstagram(next_url, count) {
$.ajax({
method: "GET",
url: next_url,
dataType: "jsonp",
jsonp: "callback",
jsonpCallback: "jsonpcallback",
success: function(data) {
$.each(data.data, function(i, item) {
$("#log").val($("#log").val() + item.id + '\n');
});
$("#log").val($("#log").val() + data.pagination.next_url + '\n');
// If the next url is not null or blank:
if( data.pagination.next_url && count <=50 ) {
pollInstagram(data.pagination.next_url, ++count);
}
},
error: function(jqXHR, textStatus, errorThrown) {
//alert("Check you internet Connection");
$("#log").val($("#log").val() + 'Error\n');
}
});
}​

How do I update foreign key with odata json

Expected behavior: User clicks on Register button and record is created in related entity. This has worked up til now but now we have requirement to update the foreign key based on a lookup on the current form. How do I accomplish this? The pasted code below throws error in browser "Error on the creation of record; Error – Bad Request"
// JScript source code
CreateButton = function () {
var fieldTable = crmForm.all.new_registerbutton_d;
var html = "<TABLE border=0 cellSpacing=0 cellPadding=0><TBODY><TR><TD width=0px>" + fieldTable.innerHTML + "</TD><TD width=200><INPUT style='BACKGROUND-COLOR: #d8e8ff' onclick=Button_OnClick() value='Register' type=button></TD></TR></TBODY></TABLE>";
fieldTable.innerHTML = html;
document.all.new_registerbutton.style.display = 'none';
crmForm.all.new_registerbutton_c.innerText = "";
}
Button_OnClick = function () {
//var new_se_registration = new Object();
var invitationName = Xrm.Page.getAttribute("new_name").getValue();
//new_se_registration.new_name = invitationName;
var invitationGUID = Xrm.Page.data.entity.getId().replace('{', '').replace('}', '');
alert(invitationGUID);
var value = new Array();
value[0] = new Object();
value[0].id = invitationGUID;
value[0].name = invitationName;
//var invitation = {
//id: invitationGUID, name: invitationName, entityType: "new_se_registration"
//};
//var invitation= { Id: invitationGUID, LogicalName: "new_se_registration", Name: invitationName };
//value[0].entityType = Xrm.Page.data.entity.getEntityType();
//new_se_registration.new_new_se_invitation_new_se_registid.setValue([{ id: invitationGUID, name: invitationName, entityType: "new_se_registration"}]);
//new_se_registration.new_new_se_invitation_new_se_registid = invitation;
//new_se_registration.new_eventname= Xrm.Page.getAttribute("new_eventname").getValue();
//new_invitationid is the Event id
var lookupItem = new Array;
lookupItem = crmForm.all.new_invitationid.DataValue;
var eventname = lookupItem[0].name;
//new_se_registration.new_eventname = eventname;
lookupItem = crmForm.all.new_invitationid.DataValue;
var new_se_registration = {
new_new_se_invitation_new_se_registid: {
__metadata: { type: "Microsoft.Crm.Sdk.Data.Services.EntityReference" },
Id: invitationGUID,
LogicalName: invitationName
},
new_name: invitationName,
new_eventname: eventname
};
//alert ( eventname);
// end Ek - adding event name
//deleteRecord(new_se_registration.new_name, "new_se_registrationSet");
var reg = Xrm.Page.getAttribute("new_registered").getValue();
if (reg == null) {
reg = "N";
}
if (reg != "Y") {
//Xrm.Page.getAttribute("new_registered").setValue("Y");
//alert(reg);
//return;
createRecord(new_se_registration, "new_se_registrationSet", RegisterCompleted, null);
Xrm.Page.getAttribute("new_registered").setValue("Y");
//Xrm.Page.data.entity.attributes.get("new_registered").setSubmitMode("always");
//Xrm.Page.data.entity.save();
}
else {
alert("\"" + Xrm.Page.getAttribute("new_name").getValue() + "\" has been registered already.");
}
}
function RegisterCompleted(data, textStatus, XmlHttpRequest) {
var new_se_registration = data;
Xrm.Page.data.entity.save();
alert("\"" + Xrm.Page.getAttribute("new_name").getValue() + "\" has been registered successfully.");
}
function checkDuplicate() {
alert("test");
}
function deleteRecord(id, odataSetName) {
var serverUrl = Xrm.Page.context.getServerUrl();
var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: serverUrl + ODATA_ENDPOINT + "/" + odataSetName + "(guid'" + id + "')",
beforeSend: function (XMLHttpRequest) {
//XMLHttpRequest.setRequestHeader("Accept", "application/json");
XMLHttpRequest.setRequestHeader("X-HTTP-Method", "DELETE");
},
success: function (data, textStatus, XmlHttpRequest) {
alert("Record deleted successfully!");
},
error: function (XmlHttpRequest, textStatus, errorThrown) {
alert("Error while deletion – " + errorThrown);
}
});
}
function createRecord(entityObject, odataSetName, successCallback, errorCallback) {
var jsonEntity = window.JSON.stringify(entityObject);
var serverUrl = Xrm.Page.context.getServerUrl();
var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: serverUrl + ODATA_ENDPOINT + "/" + odataSetName,
data: jsonEntity,
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data, textStatus, XmlHttpRequest) {
if (successCallback) {
successCallback(data.d, textStatus, XmlHttpRequest);
}
},
error: function (XmlHttpRequest, textStatus, errorThrown) {
if (errorCallback)
errorCallback(XmlHttpRequest, textStatus, errorThrown);
else
alert("Error on the creation of record; Error – " + errorThrown);
}
});
}
Solved. Case sensitivity. Was using wrong case for new_new_se_invitation_new_se_registId.
var new_se_registration = {
new_new_se_invitation_new_se_regist**I**d: {
__metadata: { type: "Microsoft.Crm.Sdk.Data.Services.EntityReference" },
Id: invitationGUID,
LogicalName: invitationName
},
new_name: invitationName,
new_eventname: eventname
};

Resources