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.
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.
I am trying to set a fallback function dynamically from an ajax jsonp call, but it doesn't seem to work - I am actually not quite sure if it is even possible - at least I believe I am doing it wrong.
I have this
var GetFacebookData = function (data) {
var dates = [{ "date_from": data.date_from, "date_to": data.date_to }]
$.each(data.datatypes, function (i, index) {
this.fbcallback[data.datatypes[i]["id"]] = function () {
LoadFacebookData(dates, data.datatypes["id"]);
}
$.ajax({
url: 'http://localhost:59380/' + data.datatypes[i]["urlfile"] + '.php?jsonp=fbcallback' + data.datatypes[i]["id"],
method: 'GET',
dataType: 'jsonp',
jsonp: 'fbcallback',
data: { "lpage": _bankArea, "hashed_token": CryptoJS.MD5("454545").toString(), "date_from": data.date_from, "date_to": data.date_to },
});
});
}
And I am calling the function with this
GetFacebookData({ date_from: _datefrom, date_to: _dateto, datatypes: [{ id: "moedsparnord", urlfile: "index" }, { id: "studiepakken", urlfile: "fb_studiedata" }] });
I am just getting
Uncaught TypeError: Cannot set property 'moedsparnord' of undefined
The whole concept is that I will need to run GetFacebookData multiple times with difference data to be executed.
/*** LOAD FETCHED DATA AS JSON ***/
var LoadFacebookData = function (dates, id) {
_dateLoader.hide();
$('.date-box form').slideUp(750, 'easeOutBack');
var pages = [];
this.loadcallback = function (data) {
var len = data["campaignData"].length;
$.each(data["campaignData"], function (index, value) {
$('#' + id + '-' + value["campaign"]["campaignId"]).find(".facebook").text(AddDecimal(value["campaign"]["campaignReach"]));
$('#' + id + '-' + value["campaign"]["campaignId"]).find(".facebook").attr("data-spend", value["campaign"]["campaignSpend"]);
if (index != len) {
pages[index] = [value["campaign"]["campaignId"], value["campaign"]["campaignSpend"]];
}
});
var string = $('#' + id + ' .total-facebook').text().replace(/,/g, '');
$("#" + id + " .total-facebook").countTo({
from: parseFloat(string),
to: data["totalReach"],
decimals: 0,
formatter: function (value, options) {
return value.toFixed(options.decimals).replace(/\B(?=(\d{3})+(?!\d))/g, ".");
},
});
MSNLeadData([{ date_from: dates[0]["date_from"], date_to: dates[0]["date_to"] }, pages]);
StudieLeadData([{ date_from: dates[0]["date_from"], date_to: dates[0]["date_to"], pages }]);
}
$.ajax({
url: 'http://localhost:59380/loaddata.php?jsonp=loadcallback',
method: 'GET',
dataType: 'jsonp',
jsonp: 'loadcallback',
data: { "lpage": _bankArea, "hashed_token": CryptoJS.MD5("454545").toString(), "datatype": id },
});
}
Functions fbcallback['...'] should be global.
Try to use this code inside the loop.
...
var callbackName = 'fbcallback-' + data.datatypes[i]["id"];
window[callbackName] = function () {
LoadFacebookData(dates, data.datatypes["id"]);
}
...
$.ajax({
url: 'http://localhost:59380/' + data.datatypes[i]["urlfile"] + '.php',
method: 'GET',
dataType: 'jsonp',
jsonp: callbackName,
data: { "lpage": _bankArea, "hashed_token": CryptoJS.MD5("454545").toString(), "date_from": data.date_from, "date_to": data.date_to },
});
And inside of LoadFacebookData callback method should also be global (window.loadcallback).
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.
I was given this code earlier but am having a hard time parsing the correct data.
I have the following JSON
{
flavors: [{
"image": "images/bbtv.jpg",
"desc": "BioBusiness.TV",
"id": "1"
}, {
"image": "images/grow.jpg",
"desc": "Grow Staffing",
"id": "2"
}]
}
and I want to only show id:1 or id:2.
I have the following code for Ajax
$.ajax({
type: "POST",
url: "foodservice/all.js",
dataType: "json",
cache: false,
data: {"flavors": filterId(flavors, 'a')},
contentType: "application/json",
success: function(data) {
$('#flavor-detail').html("<div/>");
$.each(data.flavors, function(i,item){
$('#flavor-detail div').append('<ul><li><p>' + item.desc + '</p></li></ul>');
});
}
});
and the following function to filter through the JSON object
function filterId(obj, filteredId) {
var resultObj = $.extend({},obj);
for (var i in obj) {
if ( obj.hasOwnProperty(i) ) {
if ( obj[i].id && obj[i].id !== filteredId ) {
delete obj[i];
}
}
}
return resultObj;
}
However, this code does not return anything.
Can someone tell me what I am missing?
Im pretty new to JSON, Ajax so any help would be greatly appreciated.
Thanks!
Why not just check in the "each" code?
$.each(data.flavors, function(i,item){
if (item.id > 2) return;
$('#flavor-detail div').append('<ul><li><p>' + item.desc + '</p></li></ul>');
});
I changed the following code to make it filterable
$.ajax({
type: "GET",
url: "foodservice/all.js",
dataType: "json",
cache: false,
contentType: "application/json",
success: function(data) {
$('#flavor-detail').html("<div/>");
$.each(data.flavors, function(i, item) {
if (item.id != flavorid) return;
$('#flavor-detail div').append('<ul><li><p>' + item.desc + '</p></li></ul>');
});
}
});
and for each link to change the output,
$('#amare').click(function() {
flavorid = "1";
});
$('#sec').click(function() {
flavorid = "2";
})