Javascript eval String + variable - javascript

I have a piece of javascript code evaluated at runtime, with the <%= %> syntax...
Now, inside the <%= %>, instead of a hard coded string, i'd like to have the value stored in a variable... How can I do this?
This is the function:
function updateDescriptionLabel(msgToParse, dataColumn, TextBoxID) {
var myData = JSON.parse(msgToParse.d);
alert(msgToParse);
alert(dataColumn);
alert(TextBoxID);
// this is the explicit call, it's ok
$('#' + '<%= this.TextBoxDES_MACCHINA.ClientID %>').val($.trim(myData["DescrMacchina"]));
// NOW i want to make the call by using the variable value
var txtDes = TextBoxID;
$('#' + '<%= this.' + txtDes.toString() + '.ClientID %>').val($.trim(myData["DescrMacch"]));
// BUT i get the error: Too many characters in character literal
}
============== EDIT ===============
I have a bunch of TextBoxID that, on lost focus, get a get a value from database, and display it on the appropriate TextBoxDESCRIPTION related to the ID...
But I have to duplicate the code for each TextBox, so I'd like to generalize it...
I post the entire code.
<script language="javascript" type="text/javascript">
/* ==> JSON */
//Ajax Request
function SendAjaxRequest(urlMethod, jsonData, returnFunction) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: urlMethod,
data: jsonData,
dataType: "json",
success: function (msg) {
// Do something interesting here.
if (msg != null) {
returnFunction(msg);
}
},
error: function (xhr, status, error) {
// Boil the ASP.NET AJAX error down to JSON.
var err = eval("(" + xhr.responseText + ")");
// Display the specific error raised by the server
alert(err.Message);
}
});
}
// I'd like to generalize it ...
function SendComplexAjaxRequest(urlMethod, jsonData, returnFunction, dataColumn, TextBoxID) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: urlMethod,
data: jsonData,
dataType: "json",
success: function (msg) {
// Do something interesting here.
if (msg != null) {
returnFunction(msg, dataColumn, TextBoxID);
}
},
error: function (xhr, status, error) {
// Boil the ASP.NET AJAX error down to JSON.
var err = eval("(" + xhr.responseText + ")");
// Display the specific error raised by the server
alert(err.Message);
}
});
}
// ONE function for each textBox
function callUpdateGuastoAttributes(code) {
var urlMethod = '<% = ResolveClientUrl("~/Services/ws_Attributes.asmx/OdLGetMacchinaAttributes") %>';
var jsonData = "{'COD_MACCHINA':'" + code + "'}";
var successFunction = updateLabelsGuastoAttributs;
SendAjaxRequest(urlMethod, jsonData, successFunction);
}
function callUpdateCausaGuastoAttributes(code) {
var urlMethod = '<% = ResolveClientUrl("~/Services/ws_Attributes.asmx/OdLGetMacchinaAttributes") %>';
var jsonData = "{'COD_MACCHINA':'" + code + "'}";
var successFunction = updateLabelsCausaGuastoAttributs;
SendAjaxRequest(urlMethod, jsonData, successFunction);
}
// I can have only one function:
function callUpdateMacchinaAttributes(code) {
var urlMethod = '<% = ResolveClientUrl("~/Services/ws_Attributes.asmx/OdLGetMacchinaAttributes") %>';
var jsonData = "{'COD_MACCHINA':'" + code + "'}";
var successFunction = updateDescriptionLabel;
SendComplexAjaxRequest(urlMethod, jsonData, successFunction, 'DescrMacchina', 'TextBoxDES_MACCHINA');
}
/* <== CALLBACK */
function updateLabelsMacchinaAttributs(msg) {
var myData = JSON.parse(msg.d);
$('#' + '<%= this.TextBoxDES_MACCHINA.ClientID %>').val($.trim(myData["DescrMacchina"]));
}
function updateLabelsGuastoAttributs(msg) {
var myData = JSON.parse(msg.d);
$('#' + '<%= this.TextBoxDES_GUASTO.ClientID %>').val($.trim(myData["description"]));
}
function updateLabelsCausaGuastoAttributs(msg) {
var myData = JSON.parse(msg.d);
$('#' + '<%= this.TextBoxDES_CAUSA_GUASTO.ClientID %>').val($.trim(myData["description"]));
}
// BUT I have to generalize it...
function updateDescriptionLabel(msgToParse, dataColumn, TextBoxID) {
var myData = JSON.parse(msgToParse.d);
alert(msgToParse);
alert(dataColumn);
alert(TextBoxID);
// this is the explicit call
$('#' + '<%= this.TextBoxDES_MACCHINA.ClientID %>').val($.trim(myData["DescrMacchina"]));
// i want to make the call by using the variables values
var dCol = dataColumn;
var txtDes = TextBoxID;
$('#' + '<%= this.' + txtDes.toString() + '.ClientID %>').val($.trim(myData[dCol]));
// i get the error: Too many characters in character literal
}

I propose such solution (depending on your other code...) :
function updateDescriptionLabel(msgToParse, dataColumn, TextBoxID) {
var myData = JSON.parse(msgToParse.d);
alert(msgToParse);
alert(dataColumn);
alert(TextBoxID);
// this is the explicit call, it's ok
$('#' + '<%= this.TextBoxDES_MACCHINA.ClientID %>').val($.trim(myData["DescrMacchina"]));
// NOW i want to make the call by using the variable value
$('#' + TextBoxID).val($.trim(myData["DescrMacch"]));
}
and then when you call this function do this :
updateDescriptionLabel("your message", <yourcolumn>, <%= this.TextBoxDES_MACCHINA.ClientID %>);

Related

How can i check User Role in javascript (without razor or controller)

I'm trying to use User.IsInRole() with javascript like on the razor page. I don't want use Controller, if this can be done, How can i do this in MVC5?
Edit: I want to display button by user role. I can do this with the razor page. There are fields in javascript where I add elements to the table, I will try to use them here.
You can do like below as shown below in for price
#{var price=20;}
<html>
<body>
#if (price>30)
{
<p>The price is too high.</p>
}
else
{
<p>The price is OK.</p>
}
</body>
</html>
try like this:
//Check login User has 'System Administrator' role
function CheckUserRole() {
var currentUserRoles = Xrm.Page.context.getUserRoles();
for (var i = 0; i < currentUserRoles.length; i++) {
var userRoleId = currentUserRoles[i];
var userRoleName = GetRoleName(userRoleId);
if (userRoleName == "System Administrator") {
return true;
}
}
return false;
}
//Get Rolename based on RoleId
function GetRoleName(roleId) {
//var serverUrl = Xrm.Page.context.getServerUrl();
var serverUrl = location.protocol + "//" + location.host + "/" + Xrm.Page.context.getOrgUniqueName();
var odataSelect = serverUrl + "/XRMServices/2011/OrganizationData.svc" + "/" + "RoleSet?$filter=RoleId eq guid'" + roleId + "'";
var roleName = null;
$.ajax(
{
type: "GET",
async: false,
contentType: "application/json; charset=utf-8",
datatype: "json",
url: odataSelect,
beforeSend: function (XMLHttpRequest) { XMLHttpRequest.setRequestHeader("Accept", "application/json"); },
success: function (data, textStatus, XmlHttpRequest) {
roleName = data.d.results[0].Name;
},
error: function (XmlHttpRequest, textStatus, errorThrown) { alert('OData Select Failed: ' + textStatus + errorThrown + odataSelect); }
}
);
return roleName;
}
https://msdynamicscrmblog.wordpress.com/2013/03/10/get-login-user-role-names-in-javascript-in-dynamics-crm-2011/

Returning Response in jquery ajax function

Getting problems in Response.d , based on the result which is returning by the checkusers() function I am saving the values. If the entered name is in already in database it should say "User already exists", if it is not in database it should create a new record.
But I am not getting the correct value from (response), I observed that Console.log(response.d) giving me correct values like 'true' or 'false'. I tried everything I know like-
changing async:"false"
var jqXHR = $.ajax({ and returning jqXHR.responseText
But none of they worked for me . Please help me with this.
submitHandler: function (form) {
var txtName = $("#txtName").val();
var txtEmail = $("#txtEmail").val();
var txtSurName = $("#txtSurName").val();
var txtMobile = $("#txtMobile").val();
var txtAddress = $("#txtAddress").val();
var obj = CheckUser();
if (obj == false) {
$.ajax({
type: "POST",
url: location.pathname + "/saveData",
data: "{Name:'" + txtName + "',SurName:'" + txtSurName + "',Email:'" + txtEmail + "',Mobile:'" + txtMobile + "',Address:'" + txtAddress + "'}",
contentType: "application/json; charset=utf-8",
datatype: "jsondata",
async: "true",
success: function (response) {
$(".errMsg ul").remove();
var myObject = eval('(' + response.d + ')');
if (myObject > 0) {
bindData();
$(".errMsg").append("<ul><li>Data saved successfully</li></ul>");
}
else {
$(".errMsg").append("<ul><li>Opppps something went wrong.</li></ul>");
}
$(".errMsg").show("slow");
clear();
},
error: function (response) {
alert(response.status + ' ' + response.statusText);
}
});
}
else {
$(".errMsg").append("<ul><li>User Already Exists </li></ul>");
$(".errMsg").show("slow");
}
}
});
$("#btnSave").click(function () {
$("#form1").submit()
});
});
checkusers function is:
function CheckUser() {
var EmpName = $("#txtName").val();
$.ajax({
type: "POST",
url: location.pathname + "/UserExist",
data: "{Name:'" + EmpName + "'}",
contentType: "application/json; charset=utf-8",
datatype: "jsondata",
async: "true",
success: function (response) {
console.log(response.d);
},
error: function (response) {
alert(response.status + ' ' + response.statusText);
}
});
}
Just because your database returns true or false doesn't mean this also gets returned by your CheckUser().
There are several options here:
Either you make a local variable in your CheckUser, Make your Ajax call synchronous, set the local variable to response.d in the success function and then return that local variable.
Another option is to work with Deferred objects and make your submithandler Ajax call wait for the Checkuser Ajax call to return;
A third option is to call your create ajax call from your success callback in your CheckUser Ajax call if the user isn't created yet.
I would recommend either option 2 or 3, because option 1 is not userfriendly.

Getting this in ajax result

im trying to make a script that changes P lines to input fields, let user edit them and then revert back to p lines after a check in an external php document through ajax. However the problem seems to be that I cant use this within the ajax part, it breaks the code. How can I solve that? Do I need to post the HTML?
$(document).ready(function () {
function changeshit(result, that) {
if (result == "success") {
$(that).closest('div').find('input').each(function () {
var el_naam = $(that).attr("name");
var el_id = $(that).attr("id");
var el_content = $(that).attr("value");
$(that).replaceWith("<p name='" + el_naam + "' id='" + el_id + "'>" + el_content + "</p>");
});
$(".editlink").replaceWith("Bewerken");
} else {
alert(result);
}
}
$(".editinv").on('click', 'a', function () {
var editid = $(this).attr("id");
var edit_or_text = $(this).attr("name");
if (edit_or_text == "edit") {
$(this).closest('div').find('p').each(function () {
var el_naam = $(this).attr("name");
var el_id = $(this).attr("id");
var el_content = $(this).text();
$(this).replaceWith("<input type='text' name='" + el_naam + "' id='" + el_id + "' value='" + el_content + "' />");
});
$(".editlink").replaceWith("Klaar");
} else if (edit_or_text == "done") {
var poststring = "";
$(this).closest('div').find('input').each(function () {
var el_naam = $(this).attr("name");
var el_id = $(this).attr("id");
var el_content = $(this).attr("value");
poststring = poststring + '' + el_naam + '=' + el_content + '&';
});
poststring = poststring + 'end=end'
$.ajax({
url: 'http://' + document.domain + '/klanten/updateaddress.php',
type: 'post',
data: poststring,
success: function (result, this) {
changeshit(result, this);
}
});
}
});
});
Yes, the common solutions is declare a var example self = this and use that variable
var self = this;
$.ajax({
url: 'http://'+document.domain+'/klanten/updateaddress.php',
type: 'post',
data: poststring,
success: function(result) {
changeshit(result, self);
}
});
}
In that way, the this context is save in the variable.
Try the following:
Right under $(".editinv").on('click', 'a', function () { add
$(".editinv").on('click', 'a', function () {
var element = this;
And then change this to:
$.ajax({
url: 'http://' + document.domain + '/klanten/updateaddress.php',
type: 'post',
data: poststring,
success: function (result) {
changeshit(result, element);
}
});
That is if I am understanding correctly what you are trying to do
If you simply add:
context: this
to the $.ajax options then the success handler will automatically be called with the correct value of this, so you won't need the that parameter.
You'll then also no longer need the extra function wrapper around the success callback, so you can just use:
$.ajax({
url: 'http://' + document.domain + '/klanten/updateaddress.php',
type: 'post',
data: poststring,
context: this, // propagate "this"
success: changeshit // just pass the func ref
});
There are a few ways you can achieve this
1) If you read the docs (jQuery.ajax) you'll see that you can supply a context to the ajax method
context
Type: PlainObject This object will be made the context of all Ajax-related callbacks. By default, the context is an object that
represents the ajax settings used in the call ($.ajaxSettings merged
with the settings passed to $.ajax).
$.ajax({
url: 'http://'+document.domain+'/klanten/updateaddress.php',
type: 'post',
data: poststring,
context: this,
success: function(result) {
// the context sent above would become the context of this function when called by jquery
changeshit(result, this);
}
});
Using it this way you could even do it like the bellow code
function changeshit (result) {
var $that = $(this);
if (result == "success") {
$that.closest('div')... // cool ha ?
};
$.ajax({
url: 'http://'+document.domain+'/klanten/updateaddress.php',
type: 'post',
data: poststring,
context: this,
success: changeshit
});
2) You can take advantage of closures ( read more here or search google ), so your code would become
var context = this;
$.ajax({
url: 'http://'+document.domain+'/klanten/updateaddress.php',
type: 'post',
data: poststring,
success: function(result) {
// here you can use any variable you declared before the call
changeshit(result, context);
}
});
As a side note, i would recommend you use variable/object caching, so declare var $this = $(this) at the top of the function and use it thruought your function, instead of calling $(this) each time you need it.

ajax success event doesn't work after being called

After searching here on SO and google, didn't find an answer to my problem.
The animation doesn't seem to trigger, tried a simple alert, didn't work either.
The function works as it is supposed (almost) as it does what i need to, excluding the success part.
Why isn't the success event being called?
$(function() {
$(".seguinte").click(function() {
var fnome = $('.fnome').val();
var fmorada = $('.fmorada').val();
var flocalidade = $('.flocalidade').val();
var fcodigopostal = $('.fcodigopostal').val();
var ftelemovel = $('.ftelemovel').val();
var femail = $('.femail').val();
var fnif = $('.fnif').val();
var fempresa = $('.fempresa').val();
var dataString = 'fnome='+ fnome + '&fmorada=' + fmorada + '&flocalidade=' + flocalidade + '&fcodigopostal=' + fcodigopostal + '&ftelemovel=' + ftelemovel + '&femail=' + femail + '&fnif=' + fnif + '&fempresa=' + fempresa;
$.ajax({
type: "GET",
url: "/ajaxload/editclient.php",
data: dataString,
success: function() {
$('.primeirosector').animate({ "left": "+=768px" }, "fast" );
}
});
return false;
});
});
you are trying to pass query string in data it should be json data.
Does your method edit client has all the parameters you are passing?
A simple way to test this is doing the following:
change this line to be like this
url: "/ajaxload/editclient.php" + "?" + dataString;
and remove this line
data: dataString
The correct way of doing it should be, create a javascript object and send it in the data like so:
var sendData ={
fnome: $('.fnome').val(),
fmorada: $('.fmorada').val(),
flocalidade: $('.flocalidade').val(),
fcodigopostal: $('.fcodigopostal').val(),
ftelemovel: $('.ftelemovel').val(),
femail: $('.femail').val(),
fnif: $('.fnif').val(),
fempresa: $('.fempresa').val()
}
$.ajax({
url: "/ajaxload/editclient.php",
dataType: 'json',
data: sendData,
success: function() {
$('.primeirosector').animate({ "left": "+=768px" }, "fast" );
}
});
Another thing shouldn't this be a post request?
Hope it helps

How Can I Do to my textbox autocomplete, works

I'm trying to do an autocomplete to my textbox, but it doesn't work. Follow my code.
$(function () {
var credenciada = '<%= credenciadaId %>';
xml_NomeCompleto = "";
var Nomes = "";
var retorno = '';
var count = 0;
var t = '';
$.ajax({
url: "../Xml/AcessoExterno.aspx?Credenciada=" + credenciada,
type: "get",
dataType: 'xml',
async: false,
success: function (data) {
$(data).find("REGISTRO").each(function () {
t = $(this).find("NOMECOMPLETOUSUARIO").text();
Nomes += ["\"" + t + "\","];
});
}
});
$("#ctl00_contentConteudo_txtNome").autocomplete({ source: Nomes });
});
The variable 't' receives all the names of my users, normally, but the autocomplete don't work.
Wait for ajax response to complete and then initialize the autocomplete because before you initialize the plugin data is not available. Also the way you are creating Nomes(source) is wrong. Declare it as an array and use push method to populate it.
Try this
var Nomes = [];
$.ajax({
url: "../Xml/AcessoExterno.aspx?Credenciada=" + credenciada,
type: "get",
dataType: 'xml',
async: false,
success: function (data) {
$(data).find("REGISTRO").each(function () {
Nomes.push($(this).find("NOMECOMPLETOUSUARIO").text());
});
$("#ctl00_contentConteudo_txtNome").autocomplete({ source: Nomes });
}
});

Categories

Resources