problem with jQuery ajax

Asked

Viewed 164 times

2

I am facing a problem when using google Charts, where it is working perfectly in Internet Explorer, but when running the same page in google Chrome or firefox, graphics are not shown

my action

[OutputCache(Location = OutputCacheLocation.None)]
        public string TopClientes(int top, DateTime dataInicio, DateTime dataFim)
        {
            using (BindContext context = new BindContext())
            {
                var dados = from l in context.LogEntity
                            where l.Date >= dataInicio && l.Date <= dataFim
                            group l.LogId by new { HostName = l.HostName } into bg
                            select new TopClientsViewModel()
                            {
                                Client = bg.Key.HostName,
                                Count = bg.Count()
                            };

                var logs = dados.OrderByDescending(a => a.Count).Take(top).ToList();

                DataTable dt = new DataTable();

                //Act -----------------
                dt.AddColumn(new Column(ColumnType.String, "Cliente"));
                dt.AddColumn(new Column(ColumnType.Number, "Consultas"));

                foreach (var log in logs)
                {
                    var row1 = dt.NewRow();
                    row1.AddCellRange(new[] { new Cell(log.Client, null), new Cell(log.Count, null) });
                    dt.AddRow(row1);
                }

                var json = dt.GetJson();

                return json;
            }
        }

my view

@model Deltacompy.SSH.BindWeb.Models.BindLogGraficosViewModel
@{
    ViewBag.Title = "Reports";
}

<h2>Reports</h2>


@using (Html.BeginForm())
{
    <div class="row form-group">

        <div class="col-md-3 col-sm-3">
            @Html.LabelFor(a => a.Top, htmlAttributes: new { @class = "control-label" })
            @Html.EditorFor(a => a.Top, new { htmlAttributes = new { @class = "form-control" } })
        </div>

        <div class="col-md-3 col-sm-3">
            @Html.LabelFor(a => a.DataInicio, htmlAttributes: new { @class = "control-label" })
            @Html.EditorFor(a => a.DataInicio, new { htmlAttributes = new { @class = "form-control" } })
        </div>
        <div class="col-md-3 col-sm-3">
            @Html.LabelFor(a => a.DataFim, htmlAttributes: new { @class = "control-label" })
            @Html.EditorFor(a => a.DataFim, new { htmlAttributes = new { @class = "form-control" } })
        </div>
    </div>

    <div class="row form-group">
        <div class="col-md-12">
            <div class="btn-group">
                <button type="submit" class="btn btn-primary" id="btnPesquisar">
                    <i class="fa fa-search"></i>
                </button>
            </div>
        </div>
    </div>
}



<div class="row">
    <div class="col-md-12"><div id="TopClientes"></div></div>
</div>


@section styles {
    <link href="@Url.Content("~/Content/googlechart.css")" rel="stylesheet" />
    <link rel="stylesheet" href="@Url.Content("~/Content/bootstrap-datetimepicker.css")" />
}

@section scripts {

    <script type="text/javascript" src="https://www.google.com/jsapi?autoload={'modules':[{'name':'visualization','version':'1.1','packages':['orgchart']}]}"></script>

    <script src="@Url.Content("~/Scripts/moment-with-locales.js")"></script>
    <script type="text/javascript" src="@Url.Content("~/scripts/bootstrap-datetimepicker.js")"></script>
    <script src="@Url.Content("~/Scripts/devcompy.js")"></script>

    <script src="@Url.Content("~/Scripts/graficos/topclientes.js")"></script>

    <script type="text/javascript">

        var top = $("#Top").val();
        var dataInicio = $("#DataInicio").val();
        var dataFim = $("#DataFim").val();

        topClientes('@Url.Action("TopClientes")', top, dataInicio, dataFim, 'Top ' + top + ' Clientes de ' + dataInicio + ' a ' + dataFim, 'TopClientes');                       

    </script>
}

my js

function topClientes(url, top, dataInicio, dataFim, title, container) {
    // Load the Visualization API and the piechart package.    
    google.load('visualization', '1.0', { 'packages': ['corechart'] });

    // Set a callback to run when the Google Visualization API is loaded.
    google.setOnLoadCallback(drawChart);

    function drawChart() {        

        var jsonData = $.ajax({
            type: 'POST',
            dataType: 'json',
            contentType: 'application/json',
            url: url,
            data: "{ top: " + top + ", dataInicio: '" + dataInicio + "', dataFim: '" + dataFim + "'}",
            async: false
        }).responseText;

        // Create our data table out of JSON data loaded from server.
        var data = new google.visualization.DataTable(jsonData);

        var options = {
            'title': title,
            bar: { groupWidth: "95%" },
            animation: {"startup": true},
            'height': 300,
            'width': '100%',
        };

        // Instantiate and draw our chart, passing in some options
        var chart = new google.visualization.ColumnChart(document.getElementById(container));
        chart.draw(data, options);
    }
}

Chrome Console Error

Uncaught Error: Invalid JSON string: <!DOCTYPE html>
<html>
    <head>
        <title>JSON primitivo inv&#225;lido: object.</title>
        <meta name="viewport" content="width=device-width" />
        <style>
         body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;} 
         p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px}
         b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px}
         H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red }
         H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon }
         pre {font-family:"Consolas","Lucida Console",Monospace;font-size:11pt;margin:0;padding:0.5em;line-height:14pt}
         .marker {font-weight: bold; color: black;text-decoration: none;}
         .version {color: gray;}
         .error {margin-bottom: 10px;}
         .expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; }
         @media screen and (max-width: 639px) {
          pre { width: 440px; overflow: auto; white-space: pre-wrap; word-wrap: break-word; }
         }
         @media screen and (max-width: 479px) {
          pre { width: 280px; }
         }
        </style>
    </head>

    <body bgcolor="white">

            <span><H1>Erro de Servidor no Aplicativo '/'.<hr width=100% size=1 color=silver></H1>

            <h2> <i>JSON primitivo inv&#225;lido: object.</i> </h2></span>

            <font face="Arial, Helvetica, Geneva, SunSans-Regular, sans-serif ">

            <b> Descrição: </b>Ocorreu uma exceção sem tratamento durante a execução da atual solicitação da Web. Examine o rastreamento de pilha para obter mais informações sobre o erro e onde foi originado no código.

            <br><br>

            <b> Detalhes da Exceção: </b>System.ArgumentException: JSON primitivo inv&#225;lido: object.<br><br>

            <b>Erro de Origem:</b> <br><br>

            <table width=100% bgcolor="#ffffcc">
               <tr>
                  <td>
                      <code>

Exce&#231;&#227;o sem tratamento foi gerada durante a execu&#231;&#227;o da atual solicita&#231;&#227;o da Web. As informa&#231;&#245;es relacionadas &#224; origem e ao local da exce&#231;&#227;o podem ser identificadas usando-se o rastreamento de pilha de exce&#231;&#227;o abaixo.</code>

                  </td>
               </tr>
            </table>

            <br>

            <b>Rastreamento de Pilha:</b> <br><br>

            <table width=100% bgcolor="#ffffcc">
               <tr>
                  <td>
                      <code><pre>

[ArgumentException: JSON primitivo inv&#225;lido: object.]
   System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject() +874
   System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth) +438
   System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeList(Int32 depth) +466
   System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth) +378
   System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeDictionary(Int32 depth) +1462
   System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth) +277
   System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer) +103
   System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit) +206
   System.Web.Script.Serialization.JavaScriptSerializer.DeserializeObject(String input) +86
   System.Web.Mvc.JsonValueProviderFactory.GetDeserializedObject(ControllerContext controllerContext) +298
   System.Web.Mvc.JsonValueProviderFactory.GetValueProvider(ControllerContext controllerContext) +123
   System.Web.Mvc.ValueProviderFactoryCollection.GetValueProvider(ControllerContext controllerContext) +160
   System.Web.Mvc.ControllerBase.get_ValueProvider() +85
   System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) +154
   System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +199
   System.Web.Mvc.Async.&lt;&gt;c__DisplayClass21.&lt;BeginInvokeAction&gt;b__19(AsyncCallback asyncCallback, Object asyncState) +1680
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +59
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +151
   System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate`1 endDelegate, Object tag, Int32 timeout) +94
   System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state) +574
   System.Web.Mvc.Controller.&lt;BeginExecuteCore&gt;b__1c(AsyncCallback asyncCallback, Object asyncState, ExecuteCoreState innerState) +82
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +73
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +151
   System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object callbackState, BeginInvokeDelegate`1 beginDelegate, EndInvokeVoidDelegate`1 endDelegate, TState invokeState, Object tag, Int32 timeout, SynchronizationContext callbackSyncContext) +105
   System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +588
   System.Web.Mvc.Controller.&lt;BeginExecute&gt;b__14(AsyncCallback asyncCallback, Object callbackState, Controller controller) +47
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +65
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +151
   System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object callbackState, BeginInvokeDelegate`1 beginDelegate, EndInvokeVoidDelegate`1 endDelegate, TState invokeState, Object tag, Int32 timeout, SynchronizationContext callbackSyncContext) +139
   System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +604
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +50
   System.Web.Mvc.MvcHandler.&lt;BeginProcessRequest&gt;b__4(AsyncCallback asyncCallback, Object asyncState, ProcessRequestState innerState) +98
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +73
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +151
   System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object callbackState, BeginInvokeDelegate`1 beginDelegate, EndInvokeVoidDelegate`1 endDelegate, TState invokeState, Object tag, Int32 timeout, SynchronizationContext callbackSyncContext) +106
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +551
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +88
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +50
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +103
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean&amp; completedSynchronously) +155
</pre></code>

                  </td>
               </tr>
            </table>

            <br>

            <hr width=100% size=1 color=silver>

            <b>Informações sobre a Versão:</b>&nbsp;Microsoft .NET Framework Versão:4.0.30319; Versão do ASP.NET:4.6.79.0

            </font>

    </body>
</html>
<!-- 
[ArgumentException]: JSON primitivo inv&#225;lido: object.
   em System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject()
   em System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)
   em System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeList(Int32 depth)
   em System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)
   em System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeDictionary(Int32 depth)
   em System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)
   em System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer)
   em System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit)
   em System.Web.Script.Serialization.JavaScriptSerializer.DeserializeObject(String input)
   em System.Web.Mvc.JsonValueProviderFactory.GetDeserializedObject(ControllerContext controllerContext)
   em System.Web.Mvc.JsonValueProviderFactory.GetValueProvider(ControllerContext controllerContext)
   em System.Web.Mvc.ValueProviderFactoryCollection.GetValueProvider(ControllerContext controllerContext)
   em System.Web.Mvc.ControllerBase.get_ValueProvider()
   em System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor)
   em System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
   em System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass21.<BeginInvokeAction>b__19(AsyncCallback asyncCallback, Object asyncState)
   em System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.CallBeginDelegate(AsyncCallback callback, Object callbackState)
   em System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout)
   em System.Web.Mvc.Async.AsyncResultWrapper.Begin[TResult](AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate`1 endDelegate, Object tag, Int32 timeout)
   em System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state)
   em System.Web.Mvc.Controller.<BeginExecuteCore>b__1c(AsyncCallback asyncCallback, Object asyncState, ExecuteCoreState innerState)
   em System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState)
   em System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout)
   em System.Web.Mvc.Async.AsyncResultWrapper.Begin[TState](AsyncCallback callback, Object callbackState, BeginInvokeDelegate`1 beginDelegate, EndInvokeVoidDelegate`1 endDelegate, TState invokeState, Object tag, Int32 timeout, SynchronizationContext callbackSyncContext)
   em System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state)
   em System.Web.Mvc.Controller.<BeginExecute>b__14(AsyncCallback asyncCallback, Object callbackState, Controller controller)
   em System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState)
   em System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout)
   em System.Web.Mvc.Async.AsyncResultWrapper.Begin[TState](AsyncCallback callback, Object callbackState, BeginInvokeDelegate`1 beginDelegate, EndInvokeVoidDelegate`1 endDelegate, TState invokeState, Object tag, Int32 timeout, SynchronizationContext callbackSyncContext)
   em System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state)
   em System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state)
   em System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__4(AsyncCallback asyncCallback, Object asyncState, ProcessRequestState innerState)
   em System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState)
   em System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout)
   em System.Web.Mvc.Async.AsyncResultWrapper.Begin[TState](AsyncCallback callback, Object callbackState, BeginInvokeDelegate`1 beginDelegate, EndInvokeVoidDelegate`1 endDelegate, TState invokeState, Object tag, Int32 timeout, SynchronizationContext callbackSyncContext)
   em System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state)
   em System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state)
   em System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData)
   em System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
   em System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
-->

1 answer

1


This is not how you mount a JSON to send the request:

var jsonData = $.ajax({
        type: 'POST',
        dataType: 'json',
        contentType: 'application/json',
        url: url,
        data: "{ top: " + top + ", dataInicio: '" + dataInicio + "', dataFim: '" + dataFim + "'}",
        async: false
    }).responseText;

The error message shows this clear: that JSON is not in the correct formatting.

Use the Javascript function $.toJSON() for that reason:

var meuJson = { top: top, dataInicio: dataInicio, dataFim: datafim };
var jsonData = $.ajax({
        type: 'POST',
        dataType: 'json',
        contentType: 'application/json',
        url: url,
        data: $.toJSON(meuJson),
        async: false
    }).responseText;
  • the problem was actually the statement in my top variable script, and when running top on the console it returns me Window {top: Window, location: Location, document: document, window: Window, external: Object…}, this being the problem, I changed the variable name and solved my problems.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.