Send AJAX return error when data is string

ajax datatype
jquery ajax error
jquery ajax get example
jquery ajax post example
jquery ajax post json
ajax success: function
asynchronous ajax call jquery example
jquery ajax post json response example

I have a simple code that sends data to the action and returns the same data to AJAX. Here is my jQuery code:

  $('.calculateField').on('input', function (e) {

    var requestData = $('.calculateField').val();

    $.ajax({
        url: '/InsurancePolicyContract/CalculatePurePrice',
        type: 'POST',
        data: JSON.stringify(requestData),
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        success: function (response) {
            $('#test1').text(response);
        },
        error: function (response) {
            alert(response.responseText);
        },
        failure: function (response) {
            alert(response.responseText);
        }
    });
});

and here is my backend code:

    [HttpPost]
    public IActionResult CalculatePurePrice([FromBody]string TotalPrice)
    {
        return Ok(TotalPrice);
    }

the problem is when I change my send-data (requestData) to string (ex: "test") it says "parse error" and run error function in AJAX body! but when it was an integer(ex:548) it works to find and success method runs! Why?


You can modify your Action method like

[HttpPost]
public ActionResult CalculatePurePrice([FromBody]string TotalPrice)
{
    return Json(TotalPrice, JsonRequestBehavior.AllowGet);
}

jQuery.post(), jQuery.post( url [, data ] [, success ] [, dataType ] )Returns: jqXHR A plain object or string that is sent to the server with the request. This is a shorthand Ajax function, which is equivalent to: The jqXHR.done() (for success), jqXHR.fail() (​for error), and jqXHR.always() (for completion, whether success or error; added in​  @mtizziani I tried to remove the return from the ajax function but I still need to return the color hexa string from this method anyway :) .. May I ask you if you can write a simple example for that ? – Ahmed Elbatt Mar 9 '17 at 3:51


You need to add Accept header in your ajax request. Then your backend will give proper json or it will return plain text.

$('.calculateField').on('input', function (e) {

var requestData = $('.calculateField').val();

$.ajax({
    url: '/InsurancePolicyContract/CalculatePurePrice',
    type: 'POST',
    data: JSON.stringify(requestData),
    headers: {
      "Accept": "application/json"
    },
    dataType: 'json',
    contentType: 'application/json; charset=utf-8',
    success: function (response) {
        $('#test1').text(response);
    },
    error: function (response) {
        alert(response.responseText);
    },
    failure: function (response) {
        alert(response.responseText);
    }
});

});

jQuery.ajax(), A string containing the URL to which the request is sent. settings Deferred ) is deprecated; you must use the success/error/complete callback options instead of the A function to be used to handle the raw response data of XMLHttpRequest. When we do post using ajax, i can return boolean type of value using ActionResult type in controller method after success but I cannot return string like 'Success' or other message. Can you guys tell me how can i do that kind of stuff? Any help would be appreciated. What I have tried: I tried something like this this goes for ajax call in jquery


For your issue, it is caused by dataType: 'json' which is telling jQuery what kind of response to expect. For plain test without "", it will fail to convert to json. If you enter "test" in the input, it will work, but if you enter test directly, it will fail since there is no extra "".

For a workaround, you could remove dataType: 'json' like

    $.ajax({
            url: '/api/movie/CalculatePurePrice',
            type: 'POST',
            data: JSON.stringify(requestData),
            //dataType: 'json',
            contentType: 'application/json; charset=utf-8',
            success: function (response) {
                    $('#test1').text(response);
            },
            error: function (response) {
                    alert(response.responseText);
            },
            failure: function (response) {
                    alert(response.responseText);
            }
    });

Can't get a JSON object in response to an Ajax request with wp_ajax , In the example below I was storing the Ajax response results in a variable. In a such way the object/array with get_posts() results is returned correctly and not as a string: posts = $.ajax({ type: 'GET', url: ajaxurl, async: false, dataType: 'json', data: wp-admin/admin-ajax.php", type: "POST", data: "action=myAjaxFunc",  So I'm currently working on a ASP.NET Webforms site and I've run in to a small problem. Been searching around for 2 hours now and I got a deadline, so


AJAX & Deferreds, AJAX — "asynchronous JavaScript and XML" — is a means of loading data from a below will return data before it is defined, causing the code to throw an error. For a GET request, this data will be appended to the URL as a query string;  Handling Ajax errors with jQuery. This is a tutorial on how to handle errors when making Ajax requests via the jQuery library . A lot of developers seem to assume that their Ajax requests will always succeed.


Jquery continue another ajax function after the first ajax function call , What happens when one Ajax call is still running and you send an another Ajax call before the data of first AJAX call comes back? I know that I can return errors with PHP - and I do that, but if I want my errors to show up in a different way than my other messages returned by my script, how could I do that with the ajax function?


How to return data from ajax success function?, This tutorial shows how to send ajax request using jQuery ajax() method. url: A string URL to which you want to submit or retrieve the data; options: Configuration options for Ajax request. error, A callback function to be executed when the request fails. The ajax() method returns an object of jQuery XMLHttpRequest. Type: Boolean or String When sending data to the server, use this content type. Default is "application/x-www-form-urlencoded; charset=UTF-8", which is fine for most cases. If you explicitly pass in a content-type to $.ajax (), then it is always sent to the server (even if no data is sent).