[javascript] Ajax - 500 Internal Server Error

I am trying to learn AJAX for this project at work. I have a site that loads medications that a patient is taking.

I call this AJAX function up recursively so that it will append a new table containing a single medication and 7 days worth of history. I am having issues getting the code to execute in FF and IE. Works perfectly fine in chrome. I had alerts displaying the xmlhttp.status and this is what I got:

xmlhttp.status==500 (internal server error).

I commented out all of my recursion so it is narrowed down to this tid bit of code. ( x keeps track of the number of meds so i know when to stop)

function LoadMeds()


  if ( x == MaxMedCount )
  {
      document.getElementById("the_day").value = parseInt(document.getElementById("the_day").value)+7; 
  }
  if ( x == (MaxMedCount - 1) )
  {
      document.getElementById("x").value = x + 1;
      show();
  }
  else
  { 

      if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
          xmlhttp=new XMLHttpRequest();
      }
      else
      {// code for IE6, IE5
          xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
      xmlhttp.onreadystatechange=function()
      {
          try 
          {      
              if (xmlhttp.readyState==4 && xmlhttp.status==200)
              {     
                  var div = document.createElement('div');
                  div.innerHTML= xmlhttp.responseText;
                  document.getElementById('MedTable').appendChild(div);
                  document.getElementById("the_med_").value = the_med_;

              }

          }
          catch(e)
          {
              alert("Error");  
          }
      }
      xmlhttp.open("GET","URL with variables passed",true);
      xmlhttp.send();     
      document.getElementById("x").value = x + 1;
  } 

if more code is needed just let me know.

This question is related to javascript ajax xmlhttprequest

The answer is


I think your return string data is very long. so the JSON format has been corrupted. You should change the max size for JSON data in this way :

Open the Web.Config file and paste these lines into the configuration section

<system.web.extensions>
  <scripting>
    <webServices>
      <jsonSerialization maxJsonLength="50000000"/>
    </webServices>
  </scripting>
</system.web.extensions>

I fixed an error like this changing the places of the routes in routes.php, for example i had something like this:

Route::resource('Mensajes', 'MensajeriaController');
Route::get('Mensajes/modificar', 'MensajeriaController@modificarEstado');

and then I put it like this:

Route::get('Mensajes/modificar', 'MensajeriaController@modificarEstado');
Route::resource('Mensajes', 'MensajeriaController');

I had the same error. It turns out that the cause was that the back end method was expecting different json data. In my Ajax call i had something like this:

$.ajax({
        async: false,
        type: "POST",
        url: "http://13.82.13.196/api.aspx/PostAjax",
        data: '{"url":"test"}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
    });

Now in my WebMethod, inside my C# backend code i had declared my endpoint like this:

public static string PostAjax(AjaxSettings settings)

Where AjaxSettings was declared:

public class AjaxSettings
{
    public string url { get; set; }
}

The problem then was that the mapping between my ajax call and my back-end endpoint was not the same. As soon as i changed my ajax call to the following, it all worked well!

var data ='{"url":"test"}';    
$.ajax({
    async: false,
    type: "POST",
    url: "http://13.82.13.196/api.aspx/PostAjax",
    data: '{"settings":'+data+'}',
    contentType: "application/json; charset=utf-8",
    dataType: "json"
});

I had to change the data variable inside the Ajax call in order to match the method signature exactly.


Uncomment the following line : [System.Web.Script.Services.ScriptService]

Service will start working fine.

[WebService(Namespace = "http://tempuri.org/")]


 [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]


To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.

[System.Web.Script.Services.ScriptService]

public class WebService : System.Web.Services.WebService 
{

One must use behavior: JsonRequestBehavior.AllowGet in Post Json Return in C#


This may be an incorrect parameter to your SOAP call; look at the format of the parameter(s) in the 'data:' json section - this is the payload you are passing over - parameter and data wrapped in JSON format.

Google Chrome's debugging toolbar has some good tools to verify parameters and look at error messages - for example, start with the Console tab and click on the URL which errors or click on the network tab. You will want to view the message's headers, response etc...


Had the very same problem, then I remembered that for security reasons ASP doesn't expose the entire error or stack trace when accessing your site/service remotely, same as not being able to test a .asmx web service remotely, so I remoted into the sever and monitored my dev tools, and only then did I get the notorious message "Could not load file or assembly 'Newtonsoft.Json, Version=3.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dep...".

So log on the server and debug from there.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to ajax

Getting all files in directory with ajax Cross-Origin Read Blocking (CORB) Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource Fetch API request timeout? How do I post form data with fetch api? Ajax LARAVEL 419 POST error Laravel 5.5 ajax call 419 (unknown status) How to allow CORS in react.js? Angular 2: How to access an HTTP response body? How to post a file from a form with Axios

Examples related to xmlhttprequest

What is difference between Axios and Fetch? Basic Authentication Using JavaScript XMLHttpRequest module not defined/found loading json data from local file into React JS AngularJS: No "Access-Control-Allow-Origin" header is present on the requested resource Edit and replay XHR chrome/firefox etc? AngularJS Error: Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, https jQuery has deprecated synchronous XMLHTTPRequest Keep getting No 'Access-Control-Allow-Origin' error with XMLHttpRequest Sending a JSON to server and retrieving a JSON in return, without JQuery