Naga
Naga

Reputation: 2555

Ajax call returns 200 OK but not calling the web method

I have ajax call as below

$.ajax({
  type: "POST",
  url: "MainPortal/VirtualRoomService.asmx/SaveJunit",
  data: JSON.stringify({
    xjunit: junit,
    data: editor.getData().trim()
  }),
  contentType: "application/json; charset=utf-8",
  async: false,
  dataType: "json",
  success: function(result) {
    if (result.d.split('|')[0] != "-1") {
      $("#<%=lblMessage.ClientID%>").text("Junit saved successfully");
    } else {
      $("#<%=lblMessage.ClientID%>").text(result.d.split('|')[1]);
    }
  },
  error: function(result) {
    if (result.status == 200 && result.statusText == 'OK') {} else {
      alert("FAILED : " + result.status + ' ' + result.statusText);
    }
  }

});

Below is SaveJunit code defined in .asmx web service

[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string SaveJunit(string xjunit, string data)
{
    try
    {
        #region JunitInformation
        XmlDocument doc = new XmlDocument();
        doc.LoadXml(xjunit);
        XmlElement xRoot = doc.DocumentElement;
        XmlNode xmlJunit = xRoot.SelectSingleNode("/junit");
        XmlNode xType = xRoot.SelectSingleNode("/junit/type");
        XmlNode xInfo = xRoot.SelectSingleNode("/junit/info");

        MJunitList mJunitList = MJunitList.GetNewInstance;
        mJunitList.JunitTypeId = Convert.ToInt32(xType["id"].InnerText);
        mJunitList.JunitLabelId = Convert.ToInt32(xmlJunit["label"].InnerText);
        mJunitList.Deck = xmlJunit["deck"].InnerText;
        mJunitList.HasGalleryList = false;
        mJunitList.IntroText = xmlJunit["intro"].InnerText;
        if (string.IsNullOrEmpty(xmlJunit["status"].InnerText))
        {
            mJunitList.JunitStatusId = (int)JunitStatus.New;
        }
        else
        {
            mJunitList.JunitStatusId = Convert.ToInt32(xmlJunit["status"].InnerText, CultureInfo.CurrentCulture);
        }
        mJunitList.JunitSlug =
            CommonUtility.EncodeChar(xmlJunit["slug"].InnerText);
        if(!string.IsNullOrEmpty(xmlJunit["byline"].InnerText))
        {
            MInternalUser mInternalUser = MInternalUser.GetNewInstance;
            mInternalUser.PublicationIds = xmlJunit["publication"].InnerText;
            Collection<MInternalUser> objUsers =
                BllInternalUser.GetActiveInternalUserByPublicationId(mInternalUser, GeneralMethods.IsServiceRequired()).InternalUsers;
            var objByLine = new Collection<MByLine>();

            string[] juniByline = xmlJunit["byline"].InnerText.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < juniByline.Length; i++)
            {
                MByLine mByLine = MByLine.GetNewInstance;
                mByLine.Byline = juniByline[i];
                mByLine.UserId = objUsers.Where(n => n.ByLineName.ToLower().Equals(juniByline[i].ToLower())).First().InternalUserId;
                objByLine.Add(mByLine);
            }
            mJunitList.Bylines = objByLine;
        }

        if(!string.IsNullOrEmpty(xInfo["infodate"].InnerText))
            mJunitList.InfoBoxDate = CommonUtility.EncodeChar(xInfo["infodate"].InnerText);
        if(!string.IsNullOrEmpty(xInfo["infotime"].InnerText))
            mJunitList.InfoBoxTime = CommonUtility.EncodeChar(xInfo["infotime"].InnerText);
        if(!string.IsNullOrEmpty(xInfo["infoloc"].InnerText))
            mJunitList.InfoBoxLocation = CommonUtility.EncodeChar(xInfo["infoloc"].InnerText);
        if(!string.IsNullOrEmpty(xInfo["infotext"].InnerText))
            mJunitList.InfoBoxText = CommonUtility.EncodeChar(xInfo["infotext"].InnerText.Trim());

        #endregion

        if (string.IsNullOrEmpty(xmlJunit["id"].InnerText))
        {
            mJunitList.CapsuleId = int.Parse(xmlJunit["capid"].InnerText);
            mJunitList.PublicationIds = xmlJunit["publication"].InnerText;
            mJunitList.CreatedBy = Convert.ToInt32(xmlJunit["createdby"].InnerText);
            if (!string.IsNullOrEmpty(xmlJunit["tags"].InnerText.Trim()))
            {
                mJunitList.Tags = xmlJunit["tags"].InnerText.Trim().Trim(',');
            }
            mJunitList = BllJunitList.UpdateJunitList(mJunitList, Statement.Insert, GeneralMethods.IsServiceRequired());

            if (mJunitList.JunitId > 0)
            {
     //           return mJunitList.JunitId.ToString();
            }

            if (mJunitList.EffectedRows == (int)QueryStatus.Duplicate)
            {
                return string.Format("-1|Error duplicate record");
            }
            else
            {
                return string.Format("-1|Error transaction failed");
            }
        }
        else
        {
            //if (imbSave.Visible)
            //{
                mJunitList.JunitId = Convert.ToInt32(xmlJunit["id"].InnerText, CultureInfo.CurrentCulture);
                mJunitList.PublicationIds = xmlJunit["publication"].InnerText;
                mJunitList.UpdatedBy = Convert.ToInt32(xmlJunit["createdby"].InnerText);
                #region Tag Information

                //mJunitList.DeleteTags = DeleteJunitTags();
                //mJunitList.JunitTags = InsertJunitTags();
                if (!string.IsNullOrEmpty(xmlJunit["tags"].InnerText.Trim()))
                {
                    mJunitList.Tags = xmlJunit["tags"].InnerText.Trim().Trim(',');
                }

                #endregion

                int effectedRows =
                    BllJunitList.UpdateJunitList(mJunitList, Statement.Update, GeneralMethods.IsServiceRequired()).EffectedRows;
                if (effectedRows == (int)QueryStatus.Success)
                {
                    //                            return mJunitList.JunitId.ToString();
                }
                else
                {
                    return string.Format("-1|Error transaction failed");
                }
            //}
        }

        string path = Path.Combine(Server.MapPath(ApplicationConstants.CONTENTLIBRARY_VARIABLE),
                                     xmlJunit["publication"].InnerText);
        if (!Directory.Exists(path))
            Directory.CreateDirectory(path);

        string fullpath = Path.Combine(path, mJunitList.JunitId.ToString());
        Directory.CreateDirectory(fullpath);
        if (data.Length > 0)
        {
            string htmlfile = string.Format("{0}\\{1}.html", fullpath, DateTime.Now.ToString("MMddyyHHmmss"));

            // var ajxFileUpload = htmlEditorExtender.AjaxFileUpload;
            // ajxFileUpload.SaveAs(Server.MapPath(string.Format("{0}/{1}/{2}/{3}.html", ApplicationConstants.COMMONLIBRARY_VARIABLE, hdnPublicationId.Value, hdnJunitId.Value, DateTime.Now.ToString("MMddyy"))));
            using (FileStream fS = new FileStream(htmlfile, FileMode.Create))
            {
                using (StreamWriter fStrm = new StreamWriter(fS, Encoding.UTF8))
                {
                    fStrm.Write(HttpUtility.HtmlDecode(data));
                    //fStrm.Write(htmlEditorTextBox.Text.Replace("&lt;", "<").Replace("&gt;", ">"));
                    fStrm.Close();
                }
                fS.Close();
            }
        }
        var directory = new DirectoryInfo(path);
        if (directory.GetFiles().Count() > 0)
        {
            var files = (from f in directory.GetFiles()
                         orderby f.LastWriteTime descending
                         select f).ToList();
            if (files != null)
            {
                for (int i = 0; i < files.Count(); i++)
                {
                    files[i].MoveTo(string.Format("{0}\\{1}", fullpath, files[i].Name));
                }
            }
        }
        return mJunitList.JunitId.ToString();
    }
    catch (Exception eX)
    {
        return string.Format("-1|{0}", eX.Message);
    }
}

The ajax call always returns 200 OK but the function is never invoked Below the request data captured from client debugger (chrome)

 {"xjunit":"<?xml version=\"1.0\" encoding=\"utf-8\"?><junit><byline>Mohan</byline><id></id><capid>102</capid><status></status><slug> 17</slug><tags>tags</tags><publication>21</publication><type><id>17</id><name>Text</name></type><label>21</label><deck>deck1</deck><intro>intro</intro><info><infodate></infodate><infotime></infotime><infoloc>loc</infoloc><infotext>info</infotext></info><createdby>7</createdby></junit>","data":"<p>content</p>"}

UPDATE

I have changed

error: function(result) {

to

error: function (jqXHR, textStatus, errorThrown) {

to know about error. textStatus is showing as parsererror and in the errorThrown is showing unexpected end of input

Upvotes: 0

Views: 1328

Answers (2)

Naga
Naga

Reputation: 2555

Actually the URL

MainPortal/VirtualRoomService.asmx 

is not pointing to the right location. That is the main issue. Pointing URL to the right location has fixed the issue not sure why response is 200 OK for a bad URL? Hope this answer would would help some one with similar issue.

Upvotes: 0

Morilog
Morilog

Reputation: 3045

change this line:

data: JSON.stringify({xjunit: junit, data: editor.getData().trim()}),

to:

data: {xjunit: junit, data: editor.getData().trim()},

Upvotes: 0

Related Questions