object doesn't support this property or method using AJAX - javascript

Please see the code below:
$.ajax({
type: "POST",
url: "Results1.aspx/TableQuery",
data: JSON.stringify({
mappingid: res[i],
strCon: $("#fieldGenieConnectionString")[0].value,
strTypeSession: $("#fieldTypeSession")[0].value
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess(i, res.length),
error: OnError,
failure: function (response) {
alert('there was a failure loading the webpage')
}
});
and the code below:
function OnSuccess(i, totalrows) {
return function (response) {
//if (response.d != "") {
var strResponse = response.d;
strResponse = strResponse.toUpperCase;
if (strResponse.indexOf("<TR>") > 0) {
// alert(response.d);
document.getElementById('div' + i).innerHTML = document.getElementById('div' + i).innerHTML + '<br>' + '<br>' + response.d;
}
numSucceeded++;
var completeCalculation = (numSucceeded / totalrows) * 100
var rounded = completeCalculation.toFixed(0);
document.getElementById('ProgressIndicator').innerHTML = rounded + ' % complete';
document.getElementById('ProgressIndicator2').innerHTML = rounded + ' % complete';
if (numSucceeded === totalrows) {
var end = new Date().getTime();
var htmlResponse = "Loaded after: " + (end - start) / 1000 + " seconds"
document.getElementById('TotalTimeLabel').innerHTML = htmlResponse;
document.getElementById('TotalTime2Label').innerHTML = htmlResponse;
$("#LoadingImage").hide();
$("#LoadingImage2").hide();
}
}
}
The following line causes an error:
if (strResponse.indexOf("<TR>") > 0) {

strResponse = strResponse.toUpperCase;
There is a typo here. I think you want to write strResponse = strResponse.toUpperCase();
You are assigning a function to strResponse instead of calling the toUpperCase() on the existing strResponse

Related

AJAX call data returned from mvc function is undefined

I know this has been asked 1000 times before but I have hit a brick wall with this.^have created a web application that inserts user data and feedback for the user and the code below is basically part of the PhoneGap application. The strange thing is that the code works perfectly in a web browser but not in Phonegap (output iPad via Xcode).
Therefore would someone know why I am getting an undefined error for the following AJAX call, just after the success callback and the alert(data.ResultId). , any help is appreciated.
Thank you!
// POST: /Result/Create
[HttpPost]
public ActionResult Create(Result result)
{
if (ModelState.IsValid)
{
result.ResultDate = DateTime.Now;
repository.InsertResult(result);
repository.Save();
if (Request.IsAjaxRequest())
{
int ResultId = result.ResultId;
try
{ //valid database entry..send back new ResultId
return Json(new { Success = true, ResultId, JsonRequestBehavior.AllowGet });
}
catch
{ // no database entry
return Json(new { Success = false, Message = "Error", JsonRequestBehavior.AllowGet });
}
}
return RedirectToAction("Index");
}
return View(result);
}
Insert QnA
function InsertQnA() {
//hardcoded for testing
Q1 = 10;
Q2 = 10;
Q3 = 10;
Q4 = 10;
Q5 = 10;
Q6 = 10;
Q7 = 10;
Q8 = 10;
Q9 = 10;
Q10 = 10;
localStorage.setItem("Total",100);
localStorage.setItem("CaseStudy", 1);
localStorage.setItem("UserId",1);
Attempts = "1";
////////////////
$.ajax({
url: Domain + '/Result/Create',
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: '{"Q1":"' + Q1 + '","Q2":"' + Q2 + '","Q3":"' + Q3 + '","Q4":"' + Q4 + '","Q5":"' + Q5 + '","Q6":"' + Q6 + '","Q7":"' + Q7 + '","Q8":"' + Q8 + '","Q9":"' + Q9 + '","Q10":"' + Q10 + '","Total":"' + localStorage.getItem("Total") + '","CaseStudy":"' + localStorage.getItem("CaseStudy") + '","UserId":"' + localStorage.getItem("UserId") + '","Attempts":"' + QnANumAttempts + '"}',
// dataType : "json",
success: function (data) {
alert(data.ResultId);
if (data.Success==true) {
}
else if (data.Success==false) {
viewModel.UserId("Your entry has not been saved, please try again.");
}
},
}).fail(
function (xhr, textStatus, err) {
console.log(xhr.statusText);
console.log(textStatus);
console.log(err);
});
}
The problem was that I was tying to use the same ActionResult to serve an MVC view as well as an htlm5 cordova iOS app. I got round this by copying the ActionResult but changing the return type to a string, note the code looks a bit different in the action, however the original worked fine too. Many thanks to all who posted
[HttpPost]
public string CreateResult(Result result)
{
result.ResultDate = DateTime.Now;
repository.InsertResult(result);
repository.Save();
if (result == null)
{
// User entity does not exist in db, return 0
return JsonConvert.SerializeObject(0);
}
else
{
// Success return user
return JsonConvert.SerializeObject(result, Formatting.Indented, new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.Objects });
}
}
AJAX
$.ajax({
url: Domain + '/Result/CreateResult',
cache: false,
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: '{"Q1":"' + Q1 + '","Q2":"' + Q2 + '","Q3":"' + Q3 + '","Q4":"' + Q4 + '","Q5":"' + Q5 + '","Q6":"' + Q6 + '","Q7":"' + Q7 + '","Q8":"' + Q8 + '","Q9":"' + Q9 + '","Q10":"' + Q10 + '","Total":"' + localStorage.getItem("Total") + '","CaseStudy":"' + localStorage.getItem("CaseStudy") + '","UserId":"' + localStorage.getItem("UserId") + '","Attempts":"' + QnANumAttempts + '"}',
success: function (data) {
try {
if (data != 0) {
//result id used for feedback insertion > update result entity
localStorage.setItem("ResultId", data.ResultId);
viewModel.UserId("You have successfully completed case study " + localStorage.getItem("CaseStudy") + ", please fill out the <a href=evaluation.html target=_self>evaluation.<a/>");
//reset locals
ResetLocalStorage();
//count number of entities for User
CountUserEntitiesInResults();
}
else
{
viewModel.UserId("Your entry has not been saved, please try again.");
}
}catch(error) {
alert("This is the error which might be: "+error.message);
}
},
}).fail(
function (xhr, textStatus, err) {
console.log(xhr.statusText);
console.log(textStatus);
console.log(err);
});​

Rest API Multiple Lists in SharePoint

Because SharePoint works async i cannot store the data from multiple lists in array's and access them later.
I need to use 3 lists because they contain data from employees, holidays, and more.
See my code below for more information.
Is there no easier way to work with SharePoint and multiple lists to get the data. I tried also with executequeryasync but i cannot find a working solution for multiple lists. Or to store the value of each list in an array or variable and use it in another function because it's async.
$(function () {
$('#title').html("Inloggen verlofaanvraag");
});
function inLoggen() {
var initialen = $('#initialen').val();
var wachtwoord = $('#wachtwoord').val();
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('Lijst werknemers')/Items?$filter=wInitialen eq '" + initialen + "' and wWachtwoord eq '" + wachtwoord + "'",
type: "GET",
headers: { "accept": "application/json;odata=verbose" },
success: function (data) {
var x = data.d.results;
var werknemers = data.d.results;
for (var i = 0; i < x.length; i++) {
rInitialen = x[i].wInitialen;
rWachtwoord = x[i].wWachtwoord;
rVolledigenaam = x[i].wVolledigenaam;
}
if (i === 0) {
alert("U hebt geen toegang tot deze pagina !");
}
else {
$('#title').html("Welkom " + rVolledigenaam);
$('#inlogform').hide();
persoonlijketellers(werknemers);
}
},
error: function (xhr) {
console.log(xhr.status + ': ' + xhr.statusText);
}
});
}
function persoonlijketellers(werknemers) {
var rId = werknemers[0].ID;
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('Lijst persoonlijke tellers')/Items?$filter=pWerknemer eq '" + rId + "'",
type: "GET",
headers: { "accept": "application/json;odata=verbose" },
success: function (data) {
var x = data.d.results;
var ptellers = data.d.results;
for (var i = 0; i < x.length; i++) {
}
wettelijkeverlofdagen(werknemers, ptellers);
},
error: function (xhr) {
console.log(xhr.status + ': ' + xhr.statusText);
}
});
}
function wettelijkeverlofdagen(werknemers, ptellers) {
var rId = ptellers[0].ID;
alert(rId);
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('Lijst persoonlijke tellers')/Items?$filter=pWerknemer eq '" + rId + "'",
type: "GET",
headers: { "accept": "application/json;odata=verbose" },
success: function (data) {
var x = data.d.results;
var ptellers = data.d.results;
for (var i = 0; i < x.length; i++) {
}
},
error: function (xhr) {
console.log(xhr.status + ': ' + xhr.statusText);
}
});
}
You can store the data from multiple lists in array and access them when all of your async calls are complete, you just need to use some sort of promise pattern.
jQuery's .when method is probably the most useful in a situation like this:
function SPData() {
function getJsonDataAsync(url) {
// returning the $.ajax object is what makes the next part work...
return $.ajax({
url: url,
method: "GET",
contentType: "application/json",
headers: {
accept: "application/json;odata=verbose"
}
});
}
var requestURI1 = _spPageContextInfo.webServerRelativeUrl + "/_api/lists/..."
var requestURI2 = _spPageContextInfo.webServerRelativeUrl + "/_api/lists/..."
var requestURI3 = _spPageContextInfo.webServerRelativeUrl + "/_api/lists/..."
var req1 = getJsonDataAsync(requestURI1);
var req2 = getJsonDataAsync(requestURI2);
var req3 = getJsonDataAsync(requestURI3);
// now we can do the next line, because req1/2/3 are actually deferreds
// being returned from $.ajax
jQuery.when(req1, req2, req3).done(function(resp1, resp2, resp3) {
/* do something with all of the requests here...
resp1/2/3 correspond to the responses from each call and are each an
array that looks like: [data, statusText, jqXHR], which means that your
data is in resp1[0], resp2[0], etc. */
});
If you want, you can also just assign the returned values to variables in a higher level context, then use individual jQuery deferreds so that you can be sure all of the calls have succeeded before you start working with the data...
...
var x1, x2, x3;
// use the .then(function() { ... }) pattern because we are just returning a
// deferred/promise from $.ajax
getJsonDataAsync(requestURI1).then(function(data) {
x1 = data;
getJsonDataAsync(requestURI2).then(function(data2) {
x2 = data2;
getJsonDataAsync(requestURI3).then(function(data3) {
x3 = data3;
// do something with x1, x2, and x3
});
});
});
}

How to pass values to asp pages from javascript?

I am trying to pass a value from Javascript to ASP pages. But it can't run properly.
This is my Javscript:
function btn_upgrade_onclick() {
var dlr = document.getElementById("<%txt_sapcode.ClientID%>").value;
var dlrname = document.getElementById('<%=tex_dealername.ClientID %>').value;
var addr1 = document.getElementById('<%=txt_addr1.ClientID %>').value;
var addr2 = document.getElementById('<%=txt_addr2.ClientID %>').value;
var addr3 = document.getElementById('<%=txt_addr3.ClientID %>').value;
var mobno = document.getElementById('<%=txt_mob.ClientID %>').value;
var stat = document.getElementById('drp_state').value;
$.ajax({
async: false,
type: "POST",
url: "DealerDetails.aspx/UpdateDealer",
data: "{DlrId:'" + dealerID + "',DlrCode:'" + dlr + "',DlrName:'" + dlrname + "',Dlrad1:'" + addr1 + "',Dlrad2:'" + addr2 + "',Dlrad3:'" + addr3 + "',DlrMob:'" + mobno + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$("#drp_support").get(0).options.length = 0;
$("#drp_support").get(0).options[0] = new Option("--Select--", "0");
$("#drp_support").unbind("change");
$.each(msg.d, function (index, item) {
$("#drp_support").get(0).options[$("#drp_support").get(0).options.length] = new Option(item.Display, item.Value);
});
$("#drp_support").bind("change", function () {
sprtengId = $(this).val();
});
},
error: function () {
alert("Error");
}
});
}
And the value are passed to the function
region update
[WebMethod]
public static DataSet UpdateDealer(Int32 DlrId,Int32 DlrCode,string DlrName,string Dlrad1,string Dlrad2,string Dlrad3,Int16 Dlrddd,Int32 DlrLan,Int32 DlrMob)
{
DataSet update = new DataSet();
try
{
update=obj.UpdateDealerDetails(DlrId,DlrCode,DlrName,Dlrad1,Dlrad2,Dlrad3,DlrMob);
}
catch {}
return update;
}
#endregion
When I press the Update button, it will call the Javascript function and then it passes the value in the text boxes to the ASP code UpdateDealer();
Before am writing this function in Javascript all other functions worked properly but now it's not working properly
There is a bug in your first line of js.
var dlr = document.getElementById("**<%**txt_sapcode.ClientID%>").value;
Fix this (= missing) and check.
Where have you defined, dealerID
data: "{DlrId:'" + dealerID + "',DlrCode:'" + dlr
also, i dont' think your stat variable is initialized with following line of code just confirm.
var stat = document.getElementById('drp_state').value;
Make sure you debug and variables you have defined are initialized.
remove static from
public DataSet UpdateDealer(Int32 DlrId, Int32 DlrCode, string
DlrName, string Dlrad1, string Dlrad2, string Dlrad3, Int16 Dlrddd,
Int32 DlrLan, Int32 DlrMob)
{
DataSet update = new DataSet();
try
{
update = obj.UpdateDealerDetails(DlrId, DlrCode, DlrName, Dlrad1, Dlrad2, Dlrad3, DlrMob);
}
catch { }
return update;
}
function btn_upgrade_onclick() {
var dealerID = "1";
var dlr = "1";
var dlrname = "abc";
var addr1 = "india";
var addr2 = "delhi";
var addr3 = "delhi";
var mobno = "1234567890";
var stat = "";
var DlrLan = "123";
var Dlrddd = "1123";
$.ajax({
type: "POST",
url: "AutoComplete.asmx/UpdateDealer",
data: "{DlrId:'" + dealerID + "', DlrCode:'" + dlr + "', DlrName:'" + dlrname + "', Dlrad1:'" + addr1 + "' , Dlrad2:'" +
addr2 + "', Dlrad3:'" + addr3 + "', Dlrddd:'" + Dlrddd + "', DlrLan:'"
+ DlrLan + "', DlrMob:'" + mobno + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
$("#drp_support").get(0).options.length = 0;
$("#drp_support").get(0).options[0] = new Option("--Select--", "0");
$("#drp_support").unbind("change");
alert(data);
$.each(msg.d, function(index, item) {
$("#drp_support").get(0).options[$("#drp_support").get(0).options.length] = new Option(item.Display, item.Value);
});
$("#drp_support").bind("change", function() {
sprtengId = $(this).val();
});
},
error: function() {
alert("Error");
}
});
}

Why Page reload on SetInterval

setInterval(UpdateGroupMessages, 10000,false);
function UpdateGroupMessages() {
$.ajax({
type: "POST",
async: false,
url: "GroupNew.aspx/UpdateGroupMessages",
data: "{'groupId' : " + groups[m].GroupId + ", 'name' : " + JSON.stringify(groups[m].GroupName) + ",'count' : " + JSON.stringify(count) + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var i = 0;
n = m + 2;
while (i < data.d.length) {
var str1 = "#tabs-" + n;
var str2 = " .messagesContainer";
var str = str1 + str2;
if (data.d[i].Image == "") {
var UsernameAndMessage = BreakUsernameAndMessage(data.d[i].Message);
ViewModel.addMessage(n, UsernameAndMessage[0], UsernameAndMessage[1], null, data.d[i].Video, data.d[i].PostedTime);
}
else {
var UsernameAndMessage = BreakUsernameAndMessage(data.d[i].Message);
ViewModel.addMessage(n, UsernameAndMessage[0], UsernameAndMessage[1], "ShareImages/" + data.d[i].Image, data.d[i].Video, data.d[i].PostedTime);
}
i++;
}
},
error: function (jqXHR, textStatus, errorThrown) { }
});
m++;
k++;
}
}
My Page reloads after data updation. Why does the page reload?

populated jquery objects show as undefined when passed

In the following script, although the two weather objects are both populated with data in the ajax calls, the updateWeather call shows them both as undefined prior to that line executing. I moved the variable declarations so they would be global but they still both show undefined prior to the updateWeather call. What am I missing? Can I not set up a variable in the ajax success function and then pass it later?
Note: If you want to test this use a different url as this one won't work for you with out my credentials
function getWeatherForecastStationCode() {
var d = new Date();
var parts = d.toString().split(" ");
var dDate = parts[1] + " " + parts[2] + ", " + parts[3];
var ampm;
if (parts[4].split(":")[0] <= 12) {
ampm = "AM";
} else {
ampm = "PM";
}
var dtime = parts[4].split(":")[0] + ":" + parts[4].split(":")[1];
var datetime = dDate + " " + dtime + ampm;
alert(datetime);
var weatherStation = "KPBI"; // get from GetWeatherService.svc
var forecastFields = "&fields=periods.maxTempF%2cperiods.minTempF%2cperiods.vaildTime%2cperiods.weather%2cperiods.icon";
var currentFields = "&fields=ob.tempC%2cob.tempF%2cob.icon%2cplace.name%2cplace.state";
var forecastUrlWeatherStation = 'http://api.aerisapi.com/forecasts/' + weatherStation + '?limit=1&client_id=' + AerisClientId + '&client_secret=' + AerisWeatherApiSecret + forecastFields;
var currentUrlWeatherStation = 'http://api.aerisapi.com/observations/' + weatherStation + '?limit=1&client_id=' + AerisClientId + '&client_secret=' + AerisWeatherApiSecret + currentFields;
$.ajax({
type: "GET",
url: forecastUrlWeatherStation,
dataType: "json",
success: function (json) {
if (json.success === true) {
forecastedWeather = {
weather: json.response[0].periods[0].weather,
maxTemp: json.response[0].periods[0].maxTempF,
minTemp: json.response[0].periods[0].minTempF,
weatherIcon: json.response[0].periods[0].icon,
obsTime: datetime
};
}
else {
alert('An error occurred: ' + json.error.description);
}
}
});
var location;
$.ajax({
type: "GET",
url: currentUrlWeatherStation,
dataType: "json",
success: function (json) {
if (json.success === true) {
var place = json.response.place.name.split(" ");
if (place.length === 1) {
location = place[0].charAt(0).toUpperCase() + place[0].substr(1, place[0].length);
} else {
location = place[0].charAt(0).toUpperCase() + place[0].substr(1, place[0].length) + " " + place[1].charAt(0).toUpperCase() + place[1].substr(1, place[1].length) + ", " + json.response.place.state.toUpperCase();
}
currentWeather = {
location: location,
currentTemp: json.response.ob.tempF
};
} else {
alert('An error occurred: ' + json.error.description);
}
}
});
updateWeather(forecastedWeather,currentWeather);
}
The problem is that AJAX is Asynchronous (Thats the "A" in "AJAX"), so the call to updateWeather is executing before a response is received from your 2 ajax calls.
The way to do this then, is to wait for all ajax calls to complete before calling updateWeather.
Something like the following (untested):
$.when(getForecast(),getCurrent()).done(function(f,c){
updateWeather(forecastedWeather,currentWeather)
});
function getForecast(){
return $.ajax({
type: "GET",
url: forecastUrlWeatherStation,
dataType: "json"
....
});
};
function getCurrent(){
return $.ajax({
type: "GET",
url: currentUrlWeatherStation,
dataType: "json"
....
});
};

Categories