I have implemented a process to show my data from database in a #showdata div with the following method.
function UserCntrl($scope) {
getUser();
$scope.save = function () {
$.ajax({
type: "POST",
url: "UserService.asmx/InsertUser",
data: "{'Username':'" + $scope.Name + "','Email':'" + $scope.Mail + "','Password':'" + $scope.Password + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
$("#showdata").append("Username: " + $scope.Name + "<br />" + "Email:" + $scope.Mail + "<br />");
},
error: function (msg) {
alert(msg.d);
}
});
};
function getUser() {
$.ajax({
type: "POST",
url: "UserService.asmx/GetUserDetails",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var parsed = $.parseJSON(data.d);
$.each(parsed, function (i, jsondata) {
$("#showdata").append("Username: " + jsondata.Name + "<br />" + "Email:" + jsondata.Mail + "<br />");
});
},
error: function (XHR, errStatus, errorThrown) {
var err = JSON.parse(XHR.responseText);
errorMessage = err.Message;
alert(errorMessage);
}
});
};
}
Everything working just fine and all data showing properly in #showdata div. But now I want to do the same thing but by using the ng-repeat directive.
How can I achieve this?
as RGraham said, it's not the "angular way" to work with HTTP request but as a starting point, here's a working example:
js:
function EntryCtrl ($scope, $http) {
$scope.rootEntry = [];
$http.get('https://api.github.com/users/mralexgray/repos').success(function(root) {
$scope.rootEntry = root;
});
}
html:
<div ng-controller="EntryCtrl">
<ul>
<li ng-repeat="root in rootEntry">{{root.name}}</li>
</ul>
</div>
Live example: http://plnkr.co/edit/Grlgfob6tjE63JizWdCD?p=preview
$scope.data = object
<tr ng-repeat="(key, value) in data">
<td> {{key}} </td> <td> {{ value }} </td>
</tr>
Assuming 'parsed' is in your controller's $scope property
<div id="showdata">
<div ng-repeat="(i, jsondata) in parsed" >{{"Username: " + jsondata.Name + "<br />" + "Email:" + jsondata.Mail + "<br />"}}</div>
</div>
Related
I have a code in JS like this:
$.ajax({
url: $("body").data("url") + "/Documents/CheckDoc",
data: {
docID: id
},
dataType: 'text',
}).success(function (json) {
if (json.status) {
if (json.result) { // word template format
window.open($("body").data("url") + '/Case/OpenEnforcementDocument?DocID=' + id + '&RRcode=' + RR);
}
else { //html template format
window.open($("body").data("url") + '/EnforcementPrintout/Printout?DocID=' + id + '©s=' + copys, "_blank");
}
}
else {
toastr.error(json.message);
}
});
toastr.error("error");
It refers to the CheckDoc function on the server
And there it works great but when it comes back to JavaScript
It does not return to .success and does not reach the last row of the function: toastr.error
Which had to be carried out anyway
It is as if flying from this function and not returning to it again
Someone might know what the problem might be
Will help me a lot
Thank you
It's look like there is some mistake in your code, you closed your code after dataType: 'text', by }) , please try this and let us know:
$.ajax({
type: "POST",
url: $("body").data("url") + "/Documents/CheckDoc",
data: { docID: id },
contentType: "application/json; charset=utf-8",
dataType: 'text',
success: function (json) {
if (json.status) {
if (json.result) { // word template format
window.open($("body").data("url") + '/Case/OpenEnforcementDocument?DocID=' + id + '&RRcode=' + RR);
}
else { //html template format
window.open($("body").data("url") + '/EnforcementPrintout/Printout?DocID=' + id + '©s=' + copys, "_blank");
}
}
else {
toastr.error(json.message);
}
},
failure: function (response) {
alert("failure");
},
error: function (xhr, ex) {
alert('error')
}
});
I am trying to update a sp list with the following javascript/ajax. It succeeds until it gets to the ajax function, which is where it fails. It says the ItemID is not defined, when it is defined as:
var ItemId=item.ID
Any help appreciated.
<script type="text/javascript">
function updateMultipleListItems(){
var listName="Address Validation";
//CustomerNumber.val("16");
var CustomerNumber="CustNum";
$.ajax({
url: _spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items?$select=ID&$filter=Cust_x0020_Number eq 17",
type: "GET",
headers: {
"Accept": "application/json;odata=verbose",
},
success: function (data) {
for (var i = 0; i < data.d.results.length; i++) {
var item = data.d.results[i];
alert("1");
var itemType = GetItemTypeForListName(listName);
alert("2");
var itemId = item.ID;
alert("3");
var item = {
"__metadata": {
"type": 'SP.Data.Address%20ValidationListItem'
},
"assign": "testinput"
};
alert("4");
$.ajax({
url:_spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items('" + ItemId + "')",
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('Update Success');
alert("Success");
},
// error: function(xhr, status, error) {
// var err = eval("(" + xhr.responseText + ")");
// alert(err.Message);
//}
});
}
},
error: function (data) {
alert("Error");
}
});
}
function GetItemTypeForListName(name) {
return "SP.Data." + name.charAt(0).toUpperCase() + name.split(" ").join("").slice(1) + "ListItem";
}
</script>
What I'm trying to do:
I am trying to update all records in a list where the cust_number (a column in the list) field is 17 so that assign (another column) = "testinput".
eg:
Cust Number| Assign
17 | testinput
1 |
17 | testinput
I'm afraid you made a simple typo.
On a certain point in your code you declare the following:
var itemId = item.ID;
Later on you try to acces that same variable
url:_spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items('" + ItemId + "')",
However itemId != ItemId
Javascript is case sensitive.
Jquery autocomplete for textbox search is not working ,webservice is called but the value is not binded to the textbox .please let me know what's wrong in this code.
.aspx page:
<asp:TextBox ID="tbStudentName" runat="server" class="tbStudentName" />
<asp:Button ID="btnStudentSearch" runat="server" meta:resourcekey="btnSearch" OnClick="btnStudentSearch_Clicked" />
Script:
function AutoCompleteName(target) {
var xhr;
$j("." + target.className).autocomplete({
source: function (request, response) {
if (xhr && xhr.readystate != 4) {
xhr.abort();
}
xhr = $j.ajax({
url: "../ServiceInterface/StudentLookupService.asmx/StudentSearch",
data: "{'pStudentId': '', 'pStudentName': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($j.map(data.d, function (item) {
return {
label: item.StudentId + ' : ' + item.LastName + ', ' + item.FirstName + ' ' + item.MiddleName,
value: item.FirstName + ' ' + item.LastName
}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
response([]);
}
});
},
select: function (event, ui)
{
$j("." + target.className).val = ui.item.firstName + ' ' + ui.item.lastName;
return true;
},
minLength: 1
});
}
Also when i enter two character in search box am getting error function,for 3 or more characters only the web service is called.
Please let me know your suggestions to make it work
I have tried searching all possible matches of my problem and also have tried a couple of solutions but unfortunately none worked
My backend code:
Person p;
foreach(DataRow dr in dt.Rows)
{
p = new Person();
p.id = Convert.ToInt16(dr["Id"]);
p.name = dr["Name"].ToString();
p.phone = Convert.ToInt64(dr["Phone"]);
pList.Add(p);
}
string ans = JsonConvert.SerializeObject(pList, Formatting.Indented);
jQuery.ajax
function ShowData() {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/Data",
data: "{}",
dataType: "json",
success: function (data) {
alert(data.d);
var list = { "Person": +data };
for (i = 0; i < list.Person.length; i++) {
alert('Id: ' + list.Person[i].Id + '/nName: ' + list.Person[i].Name + '/nPhone: ' + list.Person[i].Phone);
console.log('Id: ' + list.Person[i].Id + '/nName: ' + list.Person[i].Name + '/nPhone: ' + list.Person[i].Phone);
}
console.log(list.Person.length);
},
error: function (result) {
alert("Error");
}
});
}
Alert output
[
{
"id": 1,
"name": "Bhavik",
"phone": 9601109585
},
{
"id": 2,
"name": "Xyz",
"phone": 1234567890
},
{
"id": 3,
"name": "Abc",
"phone": 9876543210
}
]
console.log(list.Person.length); returns undefined and hence does not enters the for loop.. So to work out with it.. and why is it necessary to specify contentType while dataType already exist.. Also can I use $.getJSON instead of $.ajax.
You should change your code to be var list = {"Person": data.d}; to reflect what you're alerting.
function ShowData() {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/Data",
data: "{}",
dataType: "json",
success: function (data) {
alert(data.d);
var list = { "Person": +data.d };
for (i = 0; i < list.Person.length; i++) {
alert('Id: ' + list.Person[i].Id + '/nName: ' + list.Person[i].Name + '/nPhone: ' + list.Person[i].Phone);
console.log('Id: ' + list.Person[i].Id + '/nName: ' + list.Person[i].Name + '/nPhone: ' + list.Person[i].Phone);
}
console.log(list.Person.length);
},
error: function (result) {
alert("Error");
}
});
}
Also this should be a GET request not a post, then you would be able to use $.getJSON.
Ok what I want to achieve is that it creates this automatically for each record I got back from my webservice.
<label for="ZAALID_1">Zaal 1</label>
<input id="ZAALID_1" type="radio" name="RESERVATIE.ZAALID" value="1" MSGCHECKED="~IF(CHKPROP(#RESERVATIE.ZAALID,'1'),CHECKED,)~" />
I am calling this webservice with an ajax call. There is nothing wrong with this call. I tested it with printing down the values.
$.ajax({
url: "~SYSTEM.URL~~CAMPAIGN.URL~/SelligentMobile/Webservice/WebService.asmx/getReservaties",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{'DATUM_BEGIN':'2012-05-09 10:10:36','DATUM_EINDE':'2012-05-09 12:10:45'}",
success: function (response) {
var zalen = response.d;
if (zalen.length > 0) {
$.each(zalen, function (index, zaal) {
createRadioElement(zaal.zaalId);
createLabel(zaal.zaalNaam,zaal.zaalId);
});
}
}
});
So I think there is an mistake in CreateRadioElement and createLabel.
Here are these two functions.
function createRadioElement( id ) {
var radioInput;
try {
var radioHtml = '<input id="ZAALID_' + id + '" type="radio" name="RESERVATION.ZAALID" value="' + id + '" MSGCHECKED="~IF(CHKPROP(#RESERVATIE.ZAALID,' + 1 + '),CHECKED,)~ ';
radioHtml += '/>';
radioInput = document.createElement(radioHtml);
} catch( err ) {
radioInput = document.createElement('input');
radioInput.setAttribute('type', 'radio');
radioInput.setAttribute('name', 'RESERVATION.ZAALID');
}
return radioInput;
}
function createLabel(name,id) {
var label;
var labelHTML = '<label for="ZAALID_' + id + '">'+ name +'</label>';
label = document.createElement(labelHTML);
return label;
}
Now another thing that I want to do is that is places these radiobuttons inside the div with id=zaalField
here is the HTML of that div
<div id=ZaalField data-role="fieldcontain" class="knoppen_boven">
<LABEL for=zaal>Zalen ter beschikking: </LABEL>
//Here should go the radiobuttons and labels.
</div>
Can anybody help ?
Kind regards
---EDIT---
function getZalen()
{
var dateB = $("#DATUM_BEGIN").val();
var dateE = $("#DATUM_EINDE").val();
console.log(dateB);
$.ajax({
url: "~SYSTEM.URL~~CAMPAIGN.URL~/SelligentMobile/Webservice/WebService.asmx/getReservaties",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{'DATUM_BEGIN':'2012-05-09 10:10:36','DATUM_EINDE':'2012-05-09 12:10:45'}",
success: function (response) {
var zalen = response.d;
alert(JSON.stringify(zalen));
if (zalen.length > 0) {
$.each(zalen, function (i, entity) {
$('ZaalField ').append(
$('<label />', { 'for': 'ZAALID_' + entity.zaalId, 'text': entity.zaalNaam }),
$('<input />', { 'id': 'ZAALID_' + entity.zaalId, 'type': 'radio', 'name': 'RESERVATION.ZAALID', 'value': entity.zaalId, 'MSGCHECKED': '~IF(CHKPROP(#RESERVATIE.ZAALID,' + 1 + '),CHECKED,)~ ' }), $('<br />'));
});
}
}
});
}
$(document).ready(function () {
var data = { "d": [{ "__type": "Reservatie", "zaalId": 2, "opmerking": null, "zaalNaam": "Zaal 2" }, { "__type": "Reservatie", "zaalId": 3, "opmerking": null, "zaalNaam": "Zaal 3"}] };
// $.ajax({
// url: "/SelligentMobile/Webservice/WebService.asmx/getReservaties",
// type: "POST", contentType: "application/json; charset=utf-8",
// dataType: "json", data: { 'DATUM_BEGIN': '2012-05-09 10:10:36', 'DATUM_EINDE': '2012-05-09 12:10:45' },
// success: function (data) {
if (data.d.length > 0) {
$.each(data.d, function (i, entity) {
$('body').append(
$('<label />', { 'for': 'ZAALID_' + entity.zaalId, 'text': entity.zaalNaam }),
$('<input />', { 'id': 'ZAALID_' + entity.zaalId, 'type': 'radio', 'name': 'RESERVATION.ZAALID', 'value': entity.zaalId, 'MSGCHECKED': '~IF(CHKPROP(#RESERVATIE.ZAALID,' + 1 + '),CHECKED,)~ ' }), $('<br />'));
});
}
// }
// });
});
function createLabel(id, name){
var name = "Zaal 2";
var label = document.createElement("label");
label.setAttribute("for","RANDOM"+id);
label.innerHTML = name;
return label;
}
var label = createLabel(2, "Zaal 2");
$(document.body).append(label); //add it to the body, or to whatever else you want to add it to.
This code works for me, while the code you have written doesn't.