Fail to call a Json web service inside my asp.net mvc 4 application - asp.net-mvc

I want to call the following webservice as mentioend on this link http://dev.joget.org/community/display/KB/JSON+API#JSONAPI-web%2Fjson%2Fworkflow%2Fprocess%2Flist
So inside my asp.net mvc view i wrote the folloiwng:-
<script type="text/javascript">
$(document).ready(function () {
// Send an AJAX request
$.getJSON("http://localhost:8080/jw/web/json/workflow/process/list?j_username=kermit&hash=9449B5ABCFA9AFDA36B801351ED3DF66&loginAs=admin",
function (data) {
// On success, 'data' contains a list of products.
$.each(data, function (key, val) {
// Format the text to display.
var str = val.id + ': $' + val.packageName;
// Add a list item for the product.
$('<li/>', { text: str })
.appendTo($('#products'));
});
});
});
</script>
<h1>The Processes are</h1>
<ul id="products"/>
But when i run the above web page no processes will be displayed under the <h1>The Processes are </h1> , while if i type the following http://localhost:8080/jw/web/json/workflow/process/list?j_username=kermit&hash=9449B5ABCFA9AFDA36B801351ED3DF66&loginAs=admin directly on the address-bar of my browser then all the processes will be displayed. so what might be going wrong ?
BR
-::::UPDATED::::-
i HAVE UPDATED MY JAVASCRIPT TO BE AS FOLLOW:-
$(document).ready(function(){
$.ajax({
type: "GET",
url: "http://localhost:8080/jw/web/json/workflow/package/list?loginAs=admin",
dataType: "JSONP",
contentType: "application/json; charset=utf-8",
success: function (data) {
$.each(data, function (key, val) {
// Format the text to display.
var str = val.packageId + ': $ ' + val.packageName;
// Add a list item for the product.
$('<li/>', { text: str })
.appendTo($('#products'));
});
}});
});
but the result of the web service call is returned as
undefined: $ undefined
instead of being something such as:-
{"activityId":"","processId":"289_process1"}
So what is the problem that is preventing my code from displaying the right data ?

Try specifying the JSONP callback parameter as callback=? at the end of your query string as explained in the documentation:
var url = 'http://localhost:8080/jw/web/json/workflow/process/list?j_username=kermit&hash=9449B5ABCFA9AFDA36B801351ED3DF66&loginAs=admin&callback=?';
$.getJSON(url, function (data) {
// On success, 'data' contains a list of products.
$.each(data, function (key, val) {
// Format the text to display.
var str = val.id + ': $' + val.packageName;
// Add a list item for the product.
$('<li/>', { text: str }).appendTo('#products');
});
});
UPDATE:
After showing your JSON (at last) the list of products is contained within a data property, so you need to adapt your $.each and operate on this property and not directly on the result:
{
"data": [
{
"packageName": "CRM",
"packageI‌​d": "crm"
},
{
"packageName": "EngineersAssociation",
"packageId": "EngineersAssociation"
},
{
"packageName": "LeaveApp",
"packageId": "leaveApp"
},
{
"packageName": "Newtest",
"packageId": "Newtest"
},
{
"p‌​ackageName": "TestApp",
"packageId": "testapp"
},
{
"packageName": "test54",
"packageId": "test5"
}
]
}
So adapt your code:
var url = 'http://localhost:8080/jw/web/json/workflow/process/list?j_username=kermit&hash=9449B5ABCFA9AFDA36B801351ED3DF66&loginAs=admin&callback=?';
$.getJSON(url, function (result) {
// On success, 'result.data' contains a list of products.
$.each(result.data, function (key, val) {
// Format the text to display.
var str = val.id + ': $' + val.packageName;
// Add a list item for the product.
$('<li/>', { text: str }).appendTo('#products');
});
});

Related

Graph API for SharePoint: Update / Create ListItems with Hyperlink / Picture fields

How do I shape the payload to enable a post or patch for fields that are Hyperlink/Picture?
Getting those fields is straight forward: they come as "fieldName" : { "Description":"asdf", "Url":"asdf.com"}
This works in flow using the Send HTTP Request to SharePoint block, but I can't figure out how to make this work using the graph api. Do i need to set the odata type explicitly (SP.FieldUrlValue doesn't work) and what is it for Hyperlinks?
Somethink like this: {"fieldName#odata.type", "Complex" } - we use this with Collection(Edm.String) for multiple lookup fields for instance.
Kind regards,
Gregor
Graph API does not support create this kind of column.
https://learn.microsoft.com/en-us/graph/api/resources/columndefinition?view=graph-rest-1.0
You could try to use rest api.
Create HyperLink field:
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
$(function (){
CreateListItemWithDetails("test3")
})
function CreateListItemWithDetails(listName) {
var itemType = GetItemTypeForListName(listName);
var item = {
"__metadata": { "type": itemType },
"Title": "test",
'link':
{
'__metadata': { 'type': 'SP.FieldUrlValue' },
'Description': 'Google',
'Url': 'http://google.com'
},
};
$.ajax({
url: _spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items",
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify(item),
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function (data) {
console.log(data);
},
error: function (data) {
console.log(data);
}
});
}
// Get List Item Type metadata
function GetItemTypeForListName(name) {
return "SP.Data." + name.charAt(0).toUpperCase() + name.split(" ").join("").slice(1) + "ListItem";
}
</script>
Update Hyperlink column:
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
$(function (){
CreateListItemWithDetails("test3")
})
function CreateListItemWithDetails(listName) {
var itemType = GetItemTypeForListName(listName);
var item = {
"__metadata": { "type": itemType },
"Title": "test",
'link':
{
'__metadata': { 'type': 'SP.FieldUrlValue' },
'Description': 'Google1',
'Url': 'http://google.com'
},
};
$.ajax({
url: _spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items(41)",
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify(item),
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"X-HTTP-Method": "MERGE",
"If-Match": "*"
},
success: function (data) {
console.log(data);
},
error: function (data) {
console.log(data);
}
});
}
// Get List Item Type metadata
function GetItemTypeForListName(name) {
return "SP.Data." + name.charAt(0).toUpperCase() + name.split(" ").join("").slice(1) + "ListItem";
}
</script>

Ajax refresh in mvc div data

I am developing a MVC application, where I have a scenario to refresh a part of the page basically ajax...
<div id="ajax" style="width:10%;float:left">
#foreach (var item in #Model.SModel.Where(x=>x.StudentId==13))
{
<li>#Html.DisplayFor(score => item.StudentName)</li>
}
This is the div (part of the page) which I need to refresh on a button click. I have 2 js files, data.js and render.js...
data.js contains a template as follows:
makeAJAXCall =
function (url, params, callback) {
$.ajax({
type: "get",
timeout: 180000,
cache: false,
url: url,
dataType: "json",
data: params,
contentType: "application/json; charset=utf-8",
success: function (result) {
if (callback) {
callback(result);
}
},
error: function (req, status, error) {
}
return null;
}
});
};
getGrid = function () {
makeAJAXCall(urlCollection["getGridInfo"], "", function (result) {
renderer.renderGridInfo('ajax', result);
});
};
and render.js file is as follows:
renderGridInfo = function (area, data) {
$("#" + area).text(data);
};
return {
renderGridInfo: renderGridInfo
};
In the loading page on button click function as :
Service.addURL('getGridInfo', '#Html.Raw(#Url.Action("getGridInfo", "AjaxController"))');
Service.getGrid();
In the ajax controller, the code is :
public JsonResult getGridInfo()
{
return Json(model, JsonRequestBehavior.AllowGet);
}
But the problem I am facing is, the controller is returning the JsonResult , but the 'div' accepts the model and so the output is [object] [object] button click
Question: Is there any way to refresh this 'div' from the Jsondata returned by the controller?
I have to follow this type of design without using AjaxForm.
Look what happens:
1) you returns Json: return Json(model, JsonRequestBehavior.AllowGet);
2) you put returned Json object to the div's value: $("#" + area).text(data);
that's why you end up with json's representation inside div
You need to change it as follows:
1) assume you put html for that div to model's field called NewHtml
2) eptract html from the property of returned json: var returnedHtml = data.NewHtml;
3) use html() method instead of text(): $("#" + area).html(returnedHtml);

Select2 cannot choose elements inside input

I'am struggling with select2.
I have an ajax call that returns me a json. The json is formated like that (from server):
public function get_groups()
{
$result = array();
$sql = "SELECT * FROM auth_groups ";
foreach ($this->db->query($sql)->result() as $row){
$tmp = array("id" => $row->id ,"label" => $row->name );
array_push($result, $tmp);
}
header('Content-type: application/json');
echo json_encode($result);
}
Then from my javascript i have :
$('#group_choice').select2({
minimumInputLength: 2,
ajax: {
url: "/bonsejour/extranet/ajax/resources/get_groups",
dataType: 'json',
data: function (term, page) {
return {
term:term
};
},
results: function (data, page) {
var results = [];
$.each(data, function(index, item)
{
results.push({id:item.ID, text:item.label});
});
return {
results: results
};
}
}
});
Where #group_choice is an input text.
When i type some text inside the input box it does shows all the elements coming from the json. But when i try to select an element nothing happens. How can i select the elements inside the input ?
Thanks
Refer http://ivaynberg.github.io/select2/#documentation
formatSelection: formatSelectionMethod,
function formatSelectionMethod(row) { return row.text;}
I hope you will find it helpful.
Please refer to Select2 Ajax Method Not Selecting,
and take the correct value:
id: function(data){return {id: data.id};},
or
id: function(data){return data.id}

jquery ajax to bind dropdownlist MVC

I have a 2 dropdownlist, I have to bind the 2nd one based on the Id I got from first dropdown. in the first dropdown I added OnChange event.
function onChange() {
var variantDropDown = $('#VariantName');
$.ajax({
url: '/Admin/CustomProductPinCodesManagement/GetProductVarinats',
type: 'post',
data: { productId: $("#ProductName").data("tDropDownList").value() },
success: function (data) {
$.each(variants, function (i, variant) {
$states.append('<option value="' + variant.Id + '">' + variant.Name + '</option>');
});
},
error: function () {
alert('Error');
}
});
}
and this is the c# code .
[HttpPost]
public ActionResult GetProductVarinats(string productId)
{
var variants = _productService.GetProductVariantsByProductId(Convert.ToInt32(productId));
return Json(new { Result = true, data = variants }, JsonRequestBehavior.AllowGet);
}
but it does not work.
Use val() instead of value()
Change statement
data: { productId: $("#ProductName").data("tDropDownList").value() }
to
data: { productId: $("#ProductName").data("tDropDownList").val() }
and the success should be like
success: function (data) {
//For getting list of variants, you should access it by `data.data.variants`
//because you will get your json object in data, and for getting the value `variants`
//you should capture the `data` property of returned json object like `data.data`
$.each(data.data.variants, function (i, variant) {
$states.append('<option value="' + variant.Id + '">'+ variant.Name + '</option>');
//you can try this also for creating options
//$states.append($('<option/>').text(variant.Name).attr('value',variant.Id));
});
}
so your function should look like :
function onChange() {
var variantDropDown = $('#VariantName');
$.ajax({
url: '/Admin/CustomProductPinCodesManagement/GetProductVarinats',
type : 'post',
data: { productId: $("#ProductName").data("tDropDownList").val() },
success: function (data) {
$.each(data.data.variants, function (i, variant) {
$states.append($('<option/>').text(variant.Name).attr('value',variant.Id));
});
},
error: function () {
alert('Error');
}
});
}
AcidMedia has a library called TTControls which uses Telerik and you can use the TTControls.LinkedDropDown control which solves this problem.

JQuery Autocomplete source is a function

I'm using JQuery UI autocomplete, for different fields. To get the data i'm using a function as the source. It work great!
I was wondering if there were a way of not using the anonym function in the source, but to declare a generic one which will have a parameter to redirect to the right URL.
I'm quite new in JS and JQuery and so I have no idea of what the parameters request and response are comming from in the anonym function.
Here is what I'm trying to do:
$ac.autocomplete({
//Call the function here, but what are the parameter request and response???
source: autocomplete(),
minLength: 1
});
Here is the function I'd like to call
function autoComplete(request, response, url) {
$.ajax({
url: '/Comp/'+url,
dataType: "json",
type: "POST",
success: function (data) {
response($.map(data, function(item) {
return { label: item, value: item, id: item };
}));
}
});
}
Thanks a lot for your help.
You should use
source: autoComplete
instead of
source: autocomplete()
One more remark. The default implementation of jQuery UI Autocomplete use only value and label and not use id.
Reformatting ur question will pose as solution to the problem .:)
$ac.autocomplete({
minLength: 1 ,
source: function(request, response, url){
var searchParam = request.term;
$.ajax({
url: '/Comp/'+url,
data : searchParam,
dataType: "json",
type: "POST",
success: function (data) {
response($.map(data, function(item) {
return {
label: item.Firstname,
value: item.FirstName
};
});
}
});//ajax ends
}
}); //autocomplete ends
The request and response objects are expected by jQuery UI . The request.term will give u the text that the user types and the response method will return the label and value items to the widget factory for displaying the suggestion dropdown
P.S : assuming ur JSON string contains a FirstName key !
I will give an example of a situation that happened to me, might serve as an example:
Situation: After the user selects a keyword with Jquery Autocomplete not allow it to be listed. Taking into account that the query is executed the same, ie the unamended cat. server-side.
The code looked like this:
$( "#keyword-search" ).autocomplete({
minLength: 3 ,
source: function( request , response ) {
var param = { keyword_type: type , keyword_search: request.term } ;
$.ajax({
url: URI + 'search-to-json',
data : param,
dataType: "json",
type: "GET",
success: function (data) {
response($.map(data, function( item ) {
/* At this point I call a function, I use to decide whether to add on the list to be selected by the user. */
if ( ! is_record_selected( item ) ) {
return item;
}
}));
}
});
} ,
select: function( event , ui ) {
/* Before you add, looking if there is any cell */
/* If it exists, compare the id of each cell not to add an existing */
if ( validate_new_keyword( ui ) ) {
add_cell( ui ) ;
}
} ,
});
/* Any validation... */
function validate_new_keyword( ui ) {
var keyword_id = $.trim(ui.item.id) ;
Any condition...
if (keyword_id > 0) {
return true ;
}
return false ;
}
/* This function checks if a keyword has not been selected by the user, it checks for the keyword_array. */
function is_record_selected( item ) {
var index = jQuery.inArray( item.id , keyword_array ) ;
return index == -1 ? false : true;
}
Obs: Thus it is possible to use a function inside "source" and "select". =p

Resources