I have string to pass as a table of data from C# code behind to jQuery.
for that I am using two functions:
C#
[System.Web.Services.WebMethod(EnableSession = true)]
public static List<ListItem> GetImageArray(string AccNo)
{
string result = string.Empty;
var obj = new AccountTransaction();
DataTable dt = obj._commonobj.SearchAccNo(AccNo, "", "GETIMAGE");
List<ListItem> datas = new List<ListItem>();
if (dt.Rows.Count > 0)
{
foreach (DataRow row in dt.Rows)
{
string CustImg = Convert.ToString(row["Customer Image"]);
string SignImg = Convert.ToString(row["Sign"]);
ListItem listitem = new ListItem(CustImg, SignImg);
datas.Add(listitem);
}
}
return datas;
}
Client-side
$.ajax({
type: "POST",
url: "AccountTransaction.aspx/GetImageArray",
data: "{'AccNo':'" + col1 + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnImgSuccess,
failure: function (response) {
alert(response.d);
}
});
function OnImgSuccess(response) {
alert(response.d);
});
}
return datas; returns 2 row and alert(response.d) is not showing anythig
I tried using $.map(data, function (listitem) function but no result .
$.map(data, function (listitem) {
$('<tr> <td>' + listitem.CustImg + '</td> <td>' + listitem.SignImg + ' </td> </tr>').appendTo(".tblData");
});
Please help .!
Your array is there in the d property, so you can use the map function but using the data.d instead of just data.
Then the ListItem properties are Text and Value, so your code should look like this:
$.ajax({
type: "POST",
url: "AccountTransaction.aspx/GetImageArray",
data: "{'AccNo':'" + col1 + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: onImgSuccess,
failure: function (response) {
alert(response.d);
}
});
function onImgSuccess(data) {
$.map(data.d, function (listitem) {
$('<tr> <td>' + listitem.Text + '</td> <td>' + listitem.Value + ' </td> </tr>').appendTo(".tblData");
});
}
Use the following code.
alert($.parseJSON(response.d));
Related
I'm have an html table with modal column (see image below for your reference)
Upon click the Order modal, I can access the its ID using onclick event in JavaScript
(var customer_id = $(this).val();)
I wanted to access and used it in my Add function using ajax but I'm having an error of "customer_id is not defined" when I tried to use it. Is there a way to fix it or do it properly.
This is my script
<script>
$(document).ready(function () {
// START OPEN CART MODAL FUNCTION
$(document).on('click', '.viewCart', function (e) {
e.preventDefault();
var customer_id = 0;
var customer_id = $(this).val();
console.log(customer_id);
$.ajax({
type: "GET",
url: "/get-cart/"+customer_id,
dataType: "json",
success: function (response) {
if (response.data != null) {
console.log(response);
$('.OrderTbody').html("");
$.each(response.data, function (key, item) {
$('.OrderTbody').append('<tr>\
<td>' + item.p_name + '</td>\
<td>' + item.c_qty + '</td>\
<td class="total">' + item.p_amt + '</td>\
<td><button type="button" value="' + item.c_id + '" class="btn btn-danger deleteListBtn btn-sm">Delete</button></td>\
\</tr>');
});
}
}
});
});
// END OPEN CART MODAL FUNCTION
// START ADD DATA FUNCTION
$(document).on('click', '.addToCart', function (e) {
e.preventDefault();
var data = {
'store': $('.sel_store').val(),
'product': $('.sel_product').val(),
'quantity': $('.sel_qty').val(),
// HOW TO INPUT Customer ID here, I tried this but im having an error of
// customer_id is not defined
'customer_id': customer_id,
}
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "POST",
url: "/cart-list",
data: data,
dataType: "json",
success: function (response) {
}
});
});
// END ADD DATA FUNCTION
});
</script>
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/
This is my variable in javascript:
var dataid = dataInfo[i];
I want to pass the variable to my java controller through href:
row = row + "<tr><td>" + dataid + "</td><td>" +
schoolid + "</td><td>" +
"<td><a class='details' id='" + dataid + "' href='#{DataManagement.dataDetails(dataId)}'>Details</a></td>"+
"<td>"+
</tr>";
but controller gets null value.
I am trying this using ajax:
$.ajax({
type: "GET",
url: "#{DataManagement.dataDetails}",
data: {
id: dataId
},
success: function(data) {
console.log(data);
}
});
This is my controller:
public static void dataDetails(Long id) throws SQLException {
Logger.info("id: "+ id);
//dataId=dataId.trim();
//Long iid = Long.parseLong(dataId);
Data data = Data.findById(id);
String totalStudent = Data.getTotalStudent(1L);
Logger.info("totalStudent: " + totalStudent);
renderArgs.put("totalStudent",totalStudent);
render(data,totalStudent);
}
But after ajax call it is not render the new page.
How can I do this?
It works!!!
I changed it to :
<td><a class='details' id='" + dataid + "' href='/datamanagement/dataDetails/"+dataid+"'>Details</a></td>
You can send a json request with ajax and accept it on Controller.
Ajax Request:
$.ajax({
type: "POST",
contentType: "application/json",
data: JSON.stringify(yourObject),
url: "/path",
success: function (msg) {
console.log(msg);
window.location = "/redirectTo";
},
error : function(e) {
console.log('Error: ' + e);
}
});
On Controller:
#ResponseBody
#CrossOrigin #RequestMapping(value = "/path", method = RequestMethod.POST, consumes=MediaType.APPLICATION_JSON_VALUE)
private ResponseEntity<YourObject> someMethod(#RequestBody YourObject obj){
// do your coding here
return new ResponseEntity<YourObject>(modifiedObject, HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<YourObject>(HttpStatus.BAD_REQUEST);
}
}
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.
I have to use a AJAX call to get Json data after clicking next and previous buttons. Json data should contain blog content displayed after clicking next or previous. Any suggestions how my function should look like? So far I have only:
function getPrev() {
$.ajax({
type: "GET",
url: "../Content/test.txt",
dataType: "json"
}).success(function (data) {
$.each(data, function (key, val) {
$('#blogcont').append(key+ val);
});
return false;
});
}
And my Json file is only a test file:
{"one":"test1", "two":"test2", "three":"test3" }
Sorry I am a beginner!!!!
Thanks
Your $.ajax() syntax is incorrect
function getPrev() {
$.ajax({
type: "GET",
url: "../Content/test.txt",
dataType: "json",
success: function(data) {
var content = "";
$.each(data, function(key, val) {
content += "<p>" + key + ":" + val + "</p>";
});
$('#blogcont').html(content);
}
});
return false;
}
or
function getPrev() {
$.ajax({
type: "GET",
url: "../Content/test.txt",
dataType: "json"
}).done(function(data) {
var content = "";
$.each(data, function(key, val) {
content += "<p>" + key + ":" + val + "</p>";
});
$('#blogcont').html(content);
});
return false;
}
Try this
function getPrev() {
$.ajax({
type: "GET",
url: "../Content/test.txt",
dataType: "json"
}).done(function(data) {
var content = "";
$.each(data, function(key, val) {
content += '<p>' + key + ':' + val + '</p>';
});
$('#blogcont').html(content)
.find('p')
.hide()
.first().show();
$('button.next').click(function() {
$('#blogcont').find('p:visible')
.hide()
.next('p').show();
});
});
return false;
}
How about storing the JSON data as a variable, which you can then access using an index on click?
var jsonData;
$.ajax({
type: "GET",
url: "../Content/test.txt",
dataType: "json",
success: function (data) {
jsonData= data;
}
});
var clickIndex = 0;
$('.prev').click(function() {
if(clickIndex > 0) {
clickIndex -= 1;
}
get(clickIndex);
});
$('.next').click(function() {
clickIndex++;
get(clickIndex);
});
Your get function would then accept the index and find the JSON property:
function get(i) {
var item = jsonData[i];
}
Note that you would need to add an if statement to check whether you have reached the index limit on click of .next. Also, this is fine for a test JSON file, but a better solution would be to be able to request just one relevant item from a web service returning the JSON.