Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught SyntaxError: Unexpected token B on live but not local server

So i am making some ajax post and it seems to work fine on the localhost, but when I publish it to ec2 server on amazon, I get Uncaught SyntaxError: Unexpected token B. Which seems to point to JSON parsing failure. Exact same database, same browser, and same methods being called. Why would it work on local and not on the server.

$.ajax({
                url: '@Url.Action("Action")',
                type: "POST",
                data: ko.toJSON(viewModel),
                dataType: "json",
                contentType: "application/json; charset:utf-8",
                success: function (result) {

                },
                error: function (xhr, textStatus, errorThrown) {
                    var errorData = $.parseJSON(xhr.responseText);
                    var errorMessages = [];

                    for (var key in errorData)
                    {
                        errorMessages.push(errorData[key]);
                    }
                    toastr.error(errorMessages.join("<br />"), 'Uh oh');
                }
            });

Here is the basic layout on the server side:

[HttpPost]
        public JsonResult Action(ViewModel model)
        {
            try
            {

                Response.StatusCode = (int)HttpStatusCode.OK;
                return Json("Successfull");
            }
            catch (Exception ex)
            {
                logger.Log(LogLevel.Error, string.Format("{0} \n {1}", ex.Message, ex.StackTrace));
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                List<string> errors = new List<string>();
                errors.Add(ex.Message);
                return Json(errors);
            }

        }

Within the try statement, I do a couple of queries to the database and post some calculations on Authorize.Net (https://api.authorize.net/soap/v1/Service.asmx)

If there are any error with Authorize.net web service calls then I return errors like this:

if (profile.resultCode == MessageTypeEnum.Error)
{
     logger.Log(LogLevel.Error, string.Join(",", profile.messages.Select(x => x.text)));
     Response.StatusCode = (int)HttpStatusCode.BadRequest;
     List<string> errors = new List<string>();
     profile.messages.ToList().ForEach(x => errors.Add(x.text));
     db.SaveChanges();
     return Json(errors);
}

This error that I am logging:

    A public action method 'AddPromoCode' was not found on controller 'Flazingo.Controllers.PositionController'. at 
System.Web.Mvc.Controller.HandleUnknownAction(String actionName) at 
System.Web.Mvc.Controller.ExecuteCore() at 
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) at
System.Web.Mvc.MvcHandler.<>c__DisplayClass6.<>c__DisplayClassb.b__5() at 
System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass1.b__0() at 
System.Web.Mvc.MvcHandler.<>c__DisplayClasse.b__d() at 
System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at 
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& 

completedSynchronously)

like image 720
jmogera Avatar asked Apr 17 '13 20:04

jmogera


1 Answers

You have another post at can't find action only on live server, works fine in local server, so I'm guessing that this post is specifically related to the javascript pieces, not the server-side pieces.

It sounds like something bad happens on the server, the server sends back some type of error, and the your error handler (in javascript) dies when trying to handle that response.

I get Uncaught SyntaxError: Unexpected token B. Which seems to point to JSON parsing failure.

That sounds quite reasonable. Let's look at the code:

.ajax({
  ...
  error: function (xhr, textStatus, errorThrown) {
      var errorData = $.parseJSON(xhr.responseText);
      var errorMessages = [];
      ...
  },
  ...
});

I would highly recommend taking a look at what xhr.responseText is. My guess it that it does not contain valid JSON, so the parseJSON method throws the 'Unexpected token B' error.

To look at this value, you could put console.log(xhr.responseText); or you could use a tool like the javascript debugger in your web browser or fiddler to see what is there.

My guess is that the server is sending back a string with something like There was an error on the server instead of JSON like you are expecting. I see that you have error handling built in - my guess is that there is an error within your error handling, and there is nothing to catch it. I would recommend doing debugging on the server side to see if there is an error somewhere that you are not expecting.

Perhaps profile.messages is something that can only be enumerated once, and when you try to do it again it throws an error. Or maybe DB.SaveChanges is throwing an error for some reason. Either of these would result in the logged message that you see with the behavior you see on the client side.

like image 114
CodeThug Avatar answered Sep 30 '22 12:09

CodeThug