简体   繁体   中英

JSON returned in AJAX call not working

I am trying to detect wither a database entry has been successfully input by sending the new inserted ID and a JSON variable to an AJAX call but it is not working in phonegAP, however it is fine in all browsers and I can see that the data is being inserted in the db successfully. All comments/ help appreciated, thanks. AJAX code -

function InsertQnA() {

          $.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", Total) + '","CaseStudy":"' + localStorage.getItem("CaseStudy") + '","UserId":"' + localStorage.getItem("UserId") + '","Attempts":"' + QnANumAttempts + '"}',
              success: function (data) {

                 alert('this alert is invoked successfully');

                  if (data.Success == true) {

                    alert('this alert is not being invoked successfully');

                      //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>");

                  }
                  else if (data.Success==false)
                  {
                 alert('this alert is not being invoked either');
                      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);
                       });

      }

mvc function

//
        // 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);

        }

Found two issues with the code:

1. localStorage.getItem("Total", Total) should be localStorage.getItem("Total")

2. dataType : "json" not explicitly mentioned.

I have posted with the relevant corrections.Try this if it helps and also share if if you get any errors.

function InsertQnA() {
   $.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('this alert is invoked successfully');

             try {

              if (data.Success == true) {

                alert('this alert is not being invoked successfully');

                  //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>");

              }
              else if (data.Success==false)
              {
             alert('this alert is not being invoked either');
                  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);
                   });

  }

Make these changes in your server side code.

       var json = "";
       try
          {   //valid database entry..send back new ResultId
                    json = Json.Encode(new { Success = true, ResultId, JsonRequestBehavior.AllowGet });
           }
                catch
           {    // no database entry
                    json = Json.Encode(new { Success = false, Message = "Error", JsonRequestBehavior.AllowGet });
            }
        Response.Write(json);

From what I have gathered (over the past two days) an MVC ActionResult does not seem to easily serve a webapp with data. I got round this by duplicating the ActionResult with a string method and it works fine now. Probably not the best solution but I have heard that its better to create two action methods instead of having one when serving a web view and a web app. Many thanks to everyone who posted.

MVC Action -

  [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);
                         });​

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM