API Controller Action
[HttpPost]
public string FetchPayeeDetails(string strDetails)
{
try
{
// PayeeDetails is a class
PayeeDetails objDetails = JsonConvert.DeserializeObject<PayeeDetails>(strDetails);
string AccNo = objDetails.AccNo;
string ChequeNo = objDetails.ChequeNo;
string Amount = objDetails.Amount;
// rest of the code
return "something"; // string is returned
}
catch(Exception ex){
return ex.Message;
}
}
Ajax Call Code
var Ac = $('#AccNo').val();
var Ch = $('#ChequeNo').val();
var Am = $('#Amount').val();
var API_URI = "http://IP:Port/api/contollerName"
var objData = {};
objData.AccNo = Ac;
objData.ChequeNo = Ch;
objData.Amount = Am;
$.ajax({
url: API_URI,
type: "POST",
data: {strDetails:JSON.stringify(objData)},
async: false,
contentType: "application/json;",
mode: 'cors',
success: function (Data) {
$('#PayeeName').val(Data);
},
error: function (xhr, ajaxOptions, thrownError) {
$('#PayeeName').val("Error at Ajax!");
}
});
Error at Ajax:
Console: Failed to load resource: the server responded with a status of 400 (Bad Request)
responseJSON: {type: 'https://tools.ietf.org/html/rfc7231#section-6.5.1', title: 'One or more validation errors occurred.', status: 400, traceId: '00-35e7f6bbc2a7d7952564f2644721eaa9-fa7b6123403222bf-00', errors: {…}}
responseText: "{\"type\":\"https://tools.ietf.org/html/rfc7231#section-6.5.1\",\"title\":\"One or more validation errors occurred.\",\"status\":400,\"traceId\":\"00-35e7f6bbc2a7d7952564f2644721eaa9-fa7b6123403222bf-00\",\"errors\":{\"strDetails\":[\"The strDetails field is required.\"]}}"
Related
Hi I'm new to Laravel and I'm having problem in passing the request properly in my controller which is a resource for update function I'm using Laravel 8. there is no error with the syntax it just return the request is empty. I paste my code for references.
my AJAX Request
let url = '/companystructure/1';
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: url,
type: "PATCH",
data: {
'fullname' : 'albert'
},
processData: false,
contentType: false,
success: function(response) {
console.log(response);
//alert(response);
//location.reload();
},
error: function (xhr, ajaxOptions, thrownError) {
var error = $.parseJSON(xhr.responseText) || thrownError;
var errorMsg = error['message'] || thrownError;
var errorObj = error.errors || [];
if (errorObj) {
Object.keys(errorObj).forEach(function (key){
if (errorObj[key][0].length <= 1 ) {
errorMsg = errorMsg + '<br/>' + errorObj[key];
} else {
errorMsg = errorMsg + '<br/>' + errorObj[key][0];
}
});
}
md.showNotification(errorMsg, 'danger');
}
});
and here is controller
public function update(Request $request, $id)
{
return response()->json($request);
}
and here is my Route
Route::resource('companystructure', CompanyStructureController::class);
this is the return I receive from my controller
type: 'PATCH' does not exists on HTTP methods thus will not be recognized by Laravel.
Try this:
let url = '/companystructure/1';
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: url,
type: "POST", /// UPDATE
data: {
'fullname' : 'albert',
'_method': 'PATCH', /// UPDATE
},
processData: false,
contentType: false,
success: function(response) {
console.log(response);
//alert(response);
//location.reload();
},
error: function (xhr, ajaxOptions, thrownError) {
var error = $.parseJSON(xhr.responseText) || thrownError;
var errorMsg = error['message'] || thrownError;
var errorObj = error.errors || [];
if (errorObj) {
Object.keys(errorObj).forEach(function (key){
if (errorObj[key][0].length <= 1 ) {
errorMsg = errorMsg + '<br/>' + errorObj[key];
} else {
errorMsg = errorMsg + '<br/>' + errorObj[key][0];
}
});
}
md.showNotification(errorMsg, 'danger');
}
});
I have the following controller:
[HttpPost]
[OutputCache(Duration=3600, VaryByParam="*", Location=OutputCacheLocation.Server)]
public JsonResult FreeTextQuery(SearchFiltersQuery filters)
{
Trace.TraceInformation("Entering method SearchController.FreeTextQuery");
SearchResults aResults = new SearchResults();
if (ModelState.IsValid)
{
try
{
ClaimsPrincipal user = User as ClaimsPrincipal;
aResults = _objectRepository.GetFullTextResults(filters, user);
}
catch (Exception ex)
{
if (!(#Url == null))
{
return Json(new { redirectUrl = #Url.Action("ShowError", "Error", new { message = ex.Message }), isRedirect = true });
}
}
}
Trace.TraceInformation("Exiting method SearchController.FreeTextQuery");
return Json(aResults);
}
which is called by the following ajax function
function GetResults(aFilters) {
var aEndPointUrl = "/Search/FreeTextQuery";
var jSonString = JSON.stringify(aFilters);
$.ajax({
type: 'POST',
url: aEndPointUrl,
traditional: true,
contentType: 'application/json; charset=utf-8',
data: jSonString,
success: function (data) {
// omitted for brevity
},
error: function (xhr, ajaxOptions, error) {
window.location.href = "/Error/ShowError?message=" + encodeURIComponent("Onbekende fout bij het zoeken.");
}
});
This code works fine without the OutputCache attribute on the controller. With it it always hits the error function of the ajax call and I see that the response is not JSON but HTML content (error is a parser error therefore).
What could be going wrong with the outputcaching and how do I get it working correctly? I've tried many ways of supplying VaryByParams but they all have the same result.
This post revealed the answer. The problem was outputting the trace to the page: page outputcache not working with trace
Here is my ajax call function on button click
document.getElementById("btnSubmit").onclick = function ()
{
var txtImageName = $('#txtImageName').val();
var CategoryId = $('#cmbCategory').val();
var ImageURL = $('#txtImageURL').val();
var ImageSource = $('#textEditor').val();
var value = CKEDITOR.instances['textEditor'].getData()
alert
$.ajax({
url: "UrlwebService.asmx/InsertImage",
type: 'POST',
data: { ImageName: txtImageName, ImageUrl3x:ImageURL,ImageSource:value,CategoryId:parseInt(CategoryId) },
dataType: 'json',
contentType: "application/x-www-form-urlencoded",
success: function (Categories) {
// states is your JSON array
alert(Categories);
},
error: function (xhr, err) {
alert("I'm in terror");
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
}
});
};
I change content type to application/json it will also throwing me error
and here I'm calling this method.....
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
public void InsertImage(string ImageName, string ImageUrl3x, string ImageSource, int CategoryId)
{
var result = ImageRepo.InsertImage(ImageName,ImageUrl3x,ImageSource,CategoryId);
var js = new System.Web.Script.Serialization.JavaScriptSerializer();
Context.Response.Write(js.Serialize(result));
}
Hello I have a ajax call:
$.ajax({
url: "/Orders/CheckIfExists",
type: "GET",
contentType: "application/json; charset=utf-8",
data: {
catalogNumber: viewModel.catalogNumber,
quantity: viewModel.quantity
},
error: function (data) {
alert("wystąpił nieokreślony błąd " + data);
},
success: function (data) {
if(data.ok)
{
alert(data.quantity)
}
}
})
});
and here's controller method:
public JsonResult CheckIfExists(string catalogNumber, int quantity)
{
List<Expression<Func<DeviceInstance, bool>>> where = new List<Expression<Func<DeviceInstance, bool>>>();
where.Add(w=>w.DeviceUsage.UserId==1);
where.Add(w => w.Project == null);
where.Add(w => w.Device.CatalogNo == catalogNumber);
var result = unitOfWork.deviceInstanceRepository.Get(where)
.GroupBy(w => new
{
DeviceId = w.DeviceId,
CatalogName = w.Device.CatalogNo,
})
.Select(s => new
{
Quantity = s.Sum(x => x.Quantity),
}).First();
if (result.Quantity >= quantity)
{
return Json(new { ok = true, quantity = result.Quantity});
}
return Json(new { ok = false });
}
But I'm always getting Internal 500 error.
Data is received by method and all calculations are ok. I compose return JSON as in example.
Where I made a mistake?
By default ASP.NET MVC rejects ajax GET requests, you have to allow it by explicitly setting JsonRequestBehavior to AllowGet:
return Json(new { ok = true, quantity = result.Quantity},
JsonRequestBehavior.AllowGet);
I have the following $.ajax post call. It would go through the action being called but then it would trigger the "error" block of the function even before the actionresult finishes. Also, it seems to reload the whole page after every pass.
var pnameVal = '<%: this.ModelCodeValueHelper().ModelCode%>';
var eidVal = '<%: ViewBag.EventId %>';
var dataV = $('input[ name = "__RequestVerificationToken"]').val();
var urlVal = '<%: Url.Action("New") %>';
alert('url > ' + urlVal);
alert('pname - ' + pnameVal + ' eid - ' + eidVal + ' dataV = ' + dataV);
$.ajax({
url: urlVal,
//dataType: "JSONP",
//contentType: "application/json; charset=utf-8",
type: "POST",
async: true,
data: { __RequestVerificationToken: dataV, pname: pnameVal, eId: eidVal },
success: function (data) {
alert('successssesss');
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest);
alert(textStatus);
alert(errorThrown);
alert('dammit');
}
})
.done(function (result) {
if (result.Success) {
alert(result.Message);
}
else if (result.Message) {
alert(' alert' + result.Message);
}
alert('done final');
//$('#search-btn').text('SEARCH');
waitOff();
});
This is the action
[HttpPost]
public ActionResult New(string pname, int eid)
{
var response = new ChangeResults { }; // this is a viewmodel class
Mat newMat = new Mat { "some stuff properties" };
Event eve = context.Events.FirstOrDefault(e => e.Id == eid);
List<Mat> mats = new List<Mat>();
try
{
eve.Mats.Add(newMat);
icdb.SaveChanges();
mats = icdb.Mats.Where(m => m.EventId == eid).ToList();
response.Success = true;
response.Message = "YES! Success!";
response.Content = mats; // this is an object type
}
catch (Exception ex)
{
response.Success = false;
response.Message = ex.Message;
response.Content = ex.Message; // this is an object type
}
return Json(response);
}
Btw, on fiddler the raw data would return the following message:
{"Success":true,"Message":"Added new Mat.","Content":[]}
And then it would reload the whole page again. I want to do an ajax call to just show added mats without having to load the whole thing. But it's not happening atm.
Thoughts?
You probably need to add e.preventDefault() in your handler, at the beginning (I am guessing that this ajax call is made on click, which is handled somewhere, that is the handler I am talking about).