0

I have some problems with an ajax call.

Here is the function:

    function jsFunction(value) {
    var selectedCompany = document.getElementById("CompanyId");
    var selectedCompanyId = selectedCompany.options[selectedCompany.selectedIndex].value;

    $.ajax({
        type: "POST",
        data: { companyId: selectedCompanyId, supplierId: value },
        url:  "@Url.Action("CheckContract", "PaidWork")",
        dataType: 'json',
        traditional: true,
        contentType: 'application/json; charset=utf-8',
        processData: false,
        success: function (response) {
            if (response != null && response.success) {
                document.getElementById("errorMessage").style.display = 'hidden';
                alert(response.responseText);
            } else {
                // DoSomethingElse()
                document.getElementById("errorMessage").style.display = 'visible';
                alert(response.responseText);
            }
        },
        error: function (response) {
            alert("error!");  //
        }

    });
}

This is the div for the message

 <div id="errorMessage" style="display:none"><strong class="alert-danger">@ViewBag.MessageContractNotExist</strong></div>

In my view I have a message which I want to display or not, depends on what response Json send me from controller. This is the method in controller:

 public ActionResult CheckContract(int companyId, int supplierId)
 {
        bool result = true;
        if (!spService.ContractExists(companyId, supplierId, ContractType.SupplierSilviPrio))
        {
            result = false;
        }
        if(!result)
        {
           ViewBag.MessageContractNotExist = "Not exist!!!";

           return Json(new { success = false, responseText = "The attached file is not supported." }, JsonRequestBehavior.AllowGet);              

        }          
         return Json(new { success = true, responseText = "Your message successfuly sent!" }, JsonRequestBehavior.AllowGet);            
    }

The problem is that I keep getting this error: invalid json primitive object Can you please help me what I miss here? Thanks

Orsi
  • 545
  • 2
  • 10
  • 27
  • Meanwhile I managed to resolve the problem by changing data to: data: JSON.stringify({ 'companyId': selectedCompanyId, 'supplierId': value }), – Orsi Oct 17 '17 at 07:11
  • Try removing the `traditional: true, contentType: 'application/json; charset=utf-8', processData: false`. As a side note, there is no point in setting `ViewBag.anything` from a method that returns json and is called via ajax. – GSerg Oct 17 '17 at 07:12
  • Possible duplicate of ["Invalid JSON primitive" in Ajax processing](https://stackoverflow.com/questions/2445874/invalid-json-primitive-in-ajax-processing) – GSerg Oct 17 '17 at 07:23

0 Answers0