Jquery Ajax Call always returns error - javascript

I have a javascript code as below
var xReg = '<region><width>' + $("#txtWidth").val() + '</width> <height>' + $("#txtHeight").val() + '</height><float>' + $("#floats").val() + '</float><contenttype>' + $("#contenttype").val() + '</contenttype><style>' + rgnStyle + '</style></region>';
$.ajax({
type: "POST",
url: "myurl/addRegion",
data: "{pubId: '" + Number($("#pubs").val()) + "',section: '" + $("#sections option:selected").text() + "',layoutW: '" + Number($("#txtLayoutW").val()) + "',layoutH: '" + Number($("#txtLayoutH").val()) + "',bSubReg: '" + Boolean($("#chkSubRegion").is(':checked')) + "',parentRegId: '" + Number(parentRgn) + "',sXmlRegion: '" + xReg.toString() + "'}",
contentType: "application/json; charset=utf-8",
async: false,
dataType: "json",
success: function (result) {
document.body.style.cursor = 'pointer';
if (result.d == -1) {
$("#errMsg").text("Failed to create new region");
}
else {
if ($("#chkSubRegion").is(':checked')) {
$("#regions").append("<option class='ddindent' value='" + result.d + "'>REGION-" + result.d.toString() + "</option>");
} else {
$("#subregions").append("<option class='ddindent' value='" + result.d + "'>SUBREGION-" + result.d.toString() + "</option>");
}
}
},
error: function (result) {
if (result.status == 200 && result.statusText == 'OK') {
if ($("#chkSubRegion").is(':checked')) {
$("#regions").append("<option class='ddindent' value='" + result.d + "'>REGION-" + result.d.toString() + "</option>");
} else {
$("#subregions").append("<option class='ddindent' value='" + result.d + "'>SUBREGION-" + result.d.toString() + "</option>");
}
}
else {
alert("FAILED : " + result.status + ' ' + result.statusText);
}
},
async: true
});
Server code as below
[WebMethod]
public int addRegion(int pubId, string section, int layoutW, int layoutH, bool bSubReg, int parentRegId, string sXmlRegion)
{
string path = Server.MapPath("~");
path = Path.Combine(path, "Published");
path = Path.Combine(path, pubId.ToString());
path = Path.Combine(path, section);
XmlDocument doc = new XmlDocument();
int rgnCount = 0;
try
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
path = Path.Combine(path, "layout.xml");
if (!File.Exists(path))
{
XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
doc.AppendChild(docNode);
XmlNode templateNode = doc.CreateElement("layout");
doc.AppendChild(templateNode);
XmlNode xNodeW = doc.CreateElement("width");
xNodeW.AppendChild(doc.CreateTextNode(layoutW.ToString()));
XmlNode xNodeH = doc.CreateElement("height");
xNodeH.AppendChild(doc.CreateTextNode(layoutH.ToString()));
}
else
{
doc.Load(path);
doc.DocumentElement.SelectSingleNode("/layout/width").InnerText = layoutW.ToString();
doc.DocumentElement.SelectSingleNode("/layout/height").InnerText = layoutH.ToString();
}
XmlElement root = doc.DocumentElement;
XmlNode xParent = root;
if (bSubReg)
{
xParent = root.SelectSingleNode("/layout/region[id='" + parentRegId.ToString() + "']");
rgnCount = xParent.SelectNodes("/region").Count;
}
else
{
rgnCount = root.SelectNodes("/Layout/region").Count;
}
rgnCount++;
XmlDocumentFragment docFragment = doc.CreateDocumentFragment();
docFragment.InnerXml = sXmlRegion;
XmlNode xID = doc.CreateElement("id");
xID.AppendChild(doc.CreateTextNode(rgnCount.ToString()));
docFragment.FirstChild.AppendChild(xID);
xParent.AppendChild(docFragment);
doc.Save(path);
return rgnCount;
}
catch (Exception eX)
{
return -1;
}
}
The call is going to server from client. And no issues I could find in server code till last return statement while I debugged it. In the javascript debugging I found that after ajax call is always going to error callback function. Can anyone suggest whats wrong with the code.
Thanks & Appreciate Your Time.

I found the bug in my code there is issue with below lines of code
},
async: true
at the end of error: callback function
I removed the line async: true and it worked

Related

Uncaught ReferenceError: Error not defined

I have this jqgrid code below and I have a picture inside it and at the same time its function that I am using. But clicking the button inside my jqgrid it says Uncaught ReferenceError: clickmeapproved is not defined. Is there anything wrong with my code or the way that I am using them?. Same error with the disapproved button.
afterInsertRow: function (rowid) {
var obj = jQuery("#FiTATimeCorrectionV2List").getRowData(rowid);
var FADTLSID = obj.FitaAssignDtlID;
if (FADTLSID !== undefined) {
if (FADTLSID !== "") {
var btnApprove = "<input type = 'image' img alt='' src='../../Content/Images/newimages/check.png' style='height:20px;width:20px;' style ='width: 90px' id='btnApproved" + rowid + "' onclick='clickmeapproved(" + rowid + " )' />"
var btnDisApprove = "<input type = 'image' img alt='' src='../../Content/Images/newimages/delete.png' style='height:20px;width:20px;' style ='width: 90px' id='btnDisApproved" + rowid + "' onclick='clickmedisapproved(" + rowid + " )' />"
jQuery("#FiTATimeCorrectionV2List").setRowData(rowid, { FitaCorForApproval: btnApprove });
jQuery("#FiTATimeCorrectionV2List").setRowData(rowid, { FitaCorForDisApproval: btnDisApprove });
var temp = obj.FitaStatus;
if (temp == "Approved") {
$("#btnApproved" + rowid).hide();
$("#btnDisApproved" + rowid).hide();
}
else if (temp == "Disapproved") {
$("#btnApproved" + rowid).hide();
$("#btnDisApproved" + rowid).hide();
} else {
$("#btnApproved" + rowid).show();
$("#btnDisApproved" + rowid).show();
}
}
}
},
function clickmeapproved(rowid) {
var ans = confirm("Are you sure you want to approve the request of "+ globalFitaCorName +"?");
if (ans) {
$.ajax({
type: "POST",
url: '../Request/SaveFitaApproval?FAID=' + rowid,
dataType: 'json',
success: function (response) {
alert("Successfully approve!");
$("#FiTATimeCorrectionV2List").trigger("reloadGrid");
FiTATimeCorrectionV2(0);
globalFitaCorName = "";
$("#loader").hide();
},
error: function (reponse) {
$("#FiTATimeCorrectionV2List").trigger("reloadGrid");
FiTATimeCorrectionV2(0);
globalFitaCorName = "";
$("#loader").hide();
}
});
}
}
Your "clickmeapproved" function does not have global scope. Check by typing "window.clickmeapproved" in the web inspector.
Here is the code that I use to solve my issue.
var btnApprove = "<input type = 'image' img alt='' src='../../Content/Images/newimages/check.png' style='height:20px;width:20px;' style ='width: 90px' id='btnApproved" + rowid + "' />"
var btnDisApprove = "<input type = 'image' img alt='' src='../../Content/Images/newimages/delete.png' style='height:20px;width:20px;' style ='width: 90px' id='btnDisApproved" + rowid + "' />"
I exclude the button click from it.
$("#btnApproved" + rowid + "").click(function(){
clickmeapproved(rowid);
});
$("#btnDisApproved" + rowid + "").click(function(){
clickmedisapproved(rowid);
});

Incrementally load a webpage: Where can I put: $("#LoadingImage").Hide();

I am not very experienced with JavaScript. Please see the code below:
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.1.min.js"></script>
<script type = "text/javascript">
function GetSQLTable() {
//alert($("#<%=fieldGroupReferences.ClientID%>")[0].value)
var str = $("#<%=fieldGroupReferences.ClientID%>")[0].value
var res = str.split(",");
for (var i = 0; i < res.length; i++) {
$("#LoadingImage").show();
var div = document.createElement('div');
div.id = "div" + i
document.body.appendChild(div);
//alert(res[i]);
$.ajax({
type: "POST",
url: "Default3.aspx/GetSQLTable",
data: '{username: "' + $("#<%=fieldUserName.ClientID%>")[0].value + '", terminalname: "' + $("#<%=fieldTerminalName.ClientID%>")[0].value + '", terminalip: "' + $("#<%=fieldTerminalIP.ClientID%>")[0].value + '", mappingid: "' + res[i] + '", usergroup: "' + $("#<%=fieldUserGroup.ClientID%>")[0].value + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess(i,res.length),
failure: function (response) {
//alert(response.d);
alert('there was an error loading the webpage')
}
});
}
function OnSuccess(i,totalrows) {
return function (response) {
if (response.d != "") {
document.getElementById('div' + i).innerHTML = document.getElementById('div' + i).innerHTML + '<br>' + '<br>' + response.d;
}
}
}
}
window.onload = GetSQLTable
</script>
The code incrementally builds a webpage i.e. x number of HTML tables are obtained and displayed to the webpage as and when they become ready. This works.
The problem is I don't know how to remove the LoadingImage once the webpage is complete i.e. $("#LoadingImage").hide();. OnSuccess is called x number of times depending on how many tables are returned so I cannot put it in there.
One way would be to count the number of successful onSuccess() calls, and hide your loading image when they are all complete:
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.1.min.js"></script>
<script type = "text/javascript">
function GetSQLTable() {
//alert($("#<%=fieldGroupReferences.ClientID%>")[0].value)
var str = $("#<%=fieldGroupReferences.ClientID%>")[0].value
var res = str.split(",");
var numSucceeded = 0;
for (var i = 0; i < res.length; i++) {
$("#LoadingImage").show();
var div = document.createElement('div');
div.id = "div" + i
document.body.appendChild(div);
//alert(res[i]);
$.ajax({
type: "POST",
url: "Default3.aspx/GetSQLTable",
data: '{username: "' + $("#<%=fieldUserName.ClientID%>")[0].value + '", terminalname: "' + $("#<%=fieldTerminalName.ClientID%>")[0].value + '", terminalip: "' + $("#<%=fieldTerminalIP.ClientID%>")[0].value + '", mappingid: "' + res[i] + '", usergroup: "' + $("#<%=fieldUserGroup.ClientID%>")[0].value + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess(i,res.length),
failure: function (response) {
//alert(response.d);
alert('there was an error loading the webpage')
}
});
}
function OnSuccess(i,totalrows) {
return function (response) {
if (response.d != "") {
document.getElementById('div' + i).innerHTML = document.getElementById('div' + i).innerHTML + '<br>' + '<br>' + response.d;
numSucceeded++;
if (numSucceeded === totalrows) {
$("#LoadingImage").hide();
}
}
}
}
}
window.onload = GetSQLTable
</script>
Try using .when with an array of your ajax calls. Something like this (simplified to remove the irrelevant bits):
function GetSQLTable() {
//...
var calls = [];
for (var i = 0; i < res.length; i++) {
//..
calls.push($.ajax({
type: "POST",
//..
}));
}
$.when(calls).then(function(d) {
// all done!!!
});

JQuery access some JSON data

I've been working on this for like an hour now, but can't seem to figure it out.
The JSON response:
{"lastDate":"2013-11-22 00:00:35",
"lastId":"42460",
"response":[
{
"class":"rowgreen",
"id":"42460","date":"22 November 2013, 00:00:35\\u0026nbsp;",
"player":"\\u003Ca href=\\u0027logpersonal.php?playerName=skiwi2\\u0027\\u003Eskiwi2\\u003C\/a\\u003E\\u0026nbsp;",
"target":"\\u003Ca href=\\u0027logpersonal.php?playerName=UnholiestElite\\u0027\\u003EUnholiestElite\\u003C\/a\\u003E\\u0026nbsp;",
"weapon":"M1014 (\\u003Cb\\u003EHeadshot\\u003C\/b\\u003E)\\u0026nbsp;",
"server":"Test\\u0026nbsp;"
}
]}
This seems to be correct, now the jquery:
function longPolling() {
if (!longPollingAllowed) {
return;
}
console.log("Long polling started.");
$.ajax({
url: "logpersonal_ajax.php",
data: {
serverId: serverId,
playerName: playerName,
lastDate: lastDate,
lastId: lastId
},
cache: false,
dataType: "json",
beforeSend: function() {
longPollingBusy = true;
},
success: function(json) {
console.log("success");
$(json).each(function() {
console.log("this.lastDate = " + this.lastDate);
console.log("this.lastId = " + this.lastId)
console.log("this.response = " + this.response);
console.log(this.response);
this.lastDate = this.lastDate;
this.lastId = this.lastId;
if (this.response != "") {
this.response.each(new function() {
console.log(this);
var clazz = this.class;
console.log("clazz = " + clazz);
var id = this.id;
var date = this.date;
var player = this.player;
var target = this.target;
var weapon = this.weapon;
var server = this.server;
var string = "\t\t\t<tr class='" + clazz + "' id='" + id + "'><td>" + date + "</td><td>" + player + "</td><td>" + target + "</td><td>" + weapon + "</td><td>" + server + "</td></tr>\n";
console.log("string = " + string);
$(string).insertBefore($("#list tr.header").next());
});
}
});
if (lastDate != "" && lastId != "") {
//longPolling(serverId, playerName, lastDate);
}
longPollingBusy = false;
},
error: function(json, message) {
console.log("fail: " + message);
longPollingBusy = false;
}
});
}
The console.log("this.lastDate = " + this.lastDate); works, so does the one for this.lastId. this.response also works and nicely shows an array starting with index 0 and when expanded it you can see all elements in the developer view.
Now comes the part I cannot seem to understand: At the foreach over this.response it does not print anything useful (except Prototype skeleton) for this.
How can I access the values?
this.response.each(new function() {
This line is wrong. It should be:
this.response.forEach(function() {
P.S. I suggest doing $.each(json, function(){ instead of $(json).each(function() {.

Synchronous AJAX...I know that sounds crazy

I have web methods that are called via AJAX in a .Net 4.0 web app. In many cases, the AJAX calls are made repeatedly in a for loop. My problem is, the information the web method is syncing to my server is time stamped and therefore must be synced in the order in which I am sending it to AJAX. Unfortunately, it seems whatever finishes first, simply finishes first and the time stamps are all out of order. I need to basically queue up my AJAX requests so that they execute in order rather than Asynchronously, which I know is the A in AJAX so this might be a totally dumb question.
How do I force the order of execution for AJAX calls done in a for loop?
Edit: Some code
for (var i = 0; i < itemCnt - 1; i++) {
try {
key = items[i];
item = localStorage.getItem(key);
vals = item.split(",");
type = getType(key);
if (type == "Status") {
var Call = key.substring(7, 17);
var OldStat = vals[0];
var NewStat = vals[1];
var Date1 = vals[2];
var Time1 = vals[3];
var miles = vals[4];
try {
stat(Call, OldStat, NewStat, Date1, Time1, miles, key);
}
catch (e) {
alert("Status " + e);
return;
}
}
else if (type == "Notes") {
var Call = key.substring(6, 16);
var Notes = item;
try {
addNotes(Call, Notes);
}
catch (e) {
alert("Notes " + e);
return;
}
}
else if (key == "StartNCTime" || key == "EndNCTime") {
var TechID = vals[0];
var Date = vals[1];
var Time = vals[2];
var Activity = vals[3];
var Location = vals[4];
var Type = vals[5];
try {
logTime(TechID, Date, Time, Activity, Location, Type,
}
catch (e) {
alert(key + ' ' + e);
return;
}
}
}
catch (e) {
alert(key + ' ' + e);
return;
}
}
function stat(Call, OldStat, NewStat, Date1, Time1, miles, key) {
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
url: "Service.asmx/update_Stat",
data: '{ CallNumber:"' + Call + '", OldStat:"' + OldStat + '", NewStat:"' + NewStat + '", Date1:"' + Date1 + '", Time1:"' + Time1 + '", Miles: "' + miles + '"}',
success: function (data) { },
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert("Sync Update Stat: " + err.Message);
location = location;
}
});
}
function logTime(TechID, Date, Time, Activity, Location, Type, key) {
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
url: "Service.asmx/nonCallTime",
data: '{ TechID:"' + TechID + '", Date1:"' + Date + '", Time1:"' + Time + '", Activity:"' + Activity + '", Location:"' + Location + '", Type: "' + Type + '"}',
success: function (data) { },
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert("Sync Non Call Time: " + err.Message);
location = location;
}
});
}
function addNotes(Call, Notes) {
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
url: "Service.asmx/addNote",
data: '{ Call:"' + Call + '", Notes:"' + Notes + '"}',
success: function (data) { },
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert("Sync Notes: " + err.Message);
location = location;
}
});
}
You have to use callbacks.
function ajax1(){
//..some code
//on ajax success:
ajax2();
}
//etcetera...
Or might I suggest using a javascript library like jQuery to synchronize your ajax requests for you.
set the third parameter in xmlhttp object's open method to false to make it synchronous.
http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp
A general pattern for making actions serial would be such:
function doAjax(data, cb) {
...
// when ready call cb
}
(function (next) {
var xhr = doAjax(data, next);
})(function (next) {
var xhr = doAjax(data, next);
})(function (next) {
doAjax(data);
});
Doing so in a for loop would require recursion.
(function next() {
if ( i < n ) {
doAjax(data[i++], next);
}
})();

Passing JSON to controller action issue

I have the following javascript.
Problem is if I enter one row in the table "ingredients" but I am getting 2 rows in the resulting pass to controller action after seralising into my C# object. But the second object is null?
I checked the javascript and the variable "cnt" is 1 not 2.
Why would that be?
Malcolm
[code]
$("#Save").click(function () {
var title = $("#recipetitle").val();
var category = $("#category").val();
var preptime = $("#prepTime").val();
var preptimeperiod = $("#lstPrepTime").val();
var cooktime = $("#cookTime").val();
var cooktimeperiod = $("#lstCookTime").val();
var rating = $("#rating").val();
var method = $("#method").val();
var jsontext = '{ "RecipeTitle": "' + title + '",';
jsontext += '"CategoryID":' + category + ',';
jsontext += '"PrepTime":' + preptime + ',';
jsontext += '"PrepTimePeriod":"' + preptimeperiod + '",';
jsontext += '"CookTime":' + cooktime + ',';
jsontext += '"CookTimePeriod":"' + cooktimeperiod + '",';
jsontext += '"Rating":' + rating + ',';
jsontext += '"Method":"' + method + '",';
var ing = "";
var cnt = 0;
$("#ingredients tr.ingredientdata").each(function () {
if ($("td.ingredient", this).text() != "") {
ing += '{ "IngredientName": "' + $("td.ingredient", this).text() + '",';
ing += '"Units": ' + $("td.units", this).text() + ',';
ing += '"Measure": "' + $("td.measure", this).text() + '"} ,';
}
cnt = cnt + 1;
});
alert(cnt);
if (ing != "") {
jsontext += '"Ingredients": [';
ing = ing.substring(0, jsontext.length - 1);
jsontext = jsontext + ing;
jsontext += ']';
}
jsontext += '}';
var json = eval('(' + jsontext + ')');
//var json = { Field: 1 };
$.ajax({
url: "/Recipe/Save",
type: "POST",
dataType: 'json',
data: JSON.stringify(json),
contentType: "application/json; charset=utf-8",
success: function () {
//alert("DONE!!");
}
});
});
[/code]
I would recommend a refactoring of your javascript as it would help you identify the errors more easily. Also checkout with FireBug the actual JSON request being sent to the controller:
$("#Save").click(function () {
var ingredients = $('#ingredients tr.ingredientdata').map(function(index, element) {
return {
ingredientName: $('td.ingredient', element).text(),
units: $('td.units', element).text(),
measure: $('td.measure', element).text()
};
});
var json = {
RecipeTitle: $('#recipetitle').val(),
CategoryID: $('#category').val(),
PrepTime: $('#prepTime').val(),
PrepTimePeriod: $('#lstPrepTime').val(),
CookTime: $('#cookTime').val(),
CookTimePeriod: $('#lstCookTime').val(),
Rating: $('#rating').val(),
Method: $('#method').val(),
Ingredients: ingredients
};
$.ajax({
url: '/Recipe/Save',
type: 'POST',
dataType: 'json',
data: JSON.stringify(json),
contentType: 'application/json; charset=utf-8',
success: function () {
//alert("DONE!!");
}
});
});

Categories

Resources