Returning error from controller to AJAX jQuery - ajax

I works with ASP.net MVC and I have get "Error" from belowe my JavaScript code:
This is my AJAX jQuery code:
$(document).ready(function () {
var dataId;
$(".item2 .small-img").click(function () {
dataId = $(this).data("id");
var url = '#Url.Action("DecorationTest", "Carpet")' + "?Id=" + dataId + "&title=" + '#Url.ToFriendlyUrl(Model.Title.ToString())';
$('#dateLink').prop('href', url);
$.ajax({
url: '/Carpet/CheckCarpet',
type: 'POST',
dataType: 'Json',
data: '{"CarpetImageid":"' + dataId + '"}',
contentType: 'application/json; charset=utf-8',
success: function (data) {
if (data.Success == false)
$('#dateLink').hide();
else
$('#dateLink').show();
alert("Success");
},
error: function (errorThrown) {
alert("Error");
}
});
and this is a controller code:
[HttpPost]
public ActionResult CheckCarpet(int CarpetImageid)
{
bool DecorShow = false;
DecorShow = db.Images.Where(x => x.Id == CarpetImageid).FirstOrDefault().DecorTest;
return Json(new JsonData { Success= DecorShow });
}
what's the reason? Someone knows?

I found the solution.i change url to #Url.Action("CheckCarpet", "Carpet") and fixed.
$(".small-img").click(function () {
dataId = $(this).data("id");
var url = '#Url.Action("DecorationTest", "Carpet")' + "?Id=" + dataId + "&title=" + '#Url.ToFriendlyUrl(Model.Title.ToString())';
$('#dateLink').attr('href', url);
$.ajax({
url:'#Url.Action("CheckCarpet", "Carpet")',
type: 'Post',
dataType: 'Json',
data: '{"CarpetImageid":"' + dataId + '"}',
contentType: 'application/json; charset=utf-8',
success: function (result) {
if (result.Success == false) {
$('#dateLink').hide();
$('.p2').hide();
}
else {
$('#dateLink').show();
$('.p2').show();
}
},
error: function (error) {
alert(error.d);
}
});
});

Related

I can't pass the request value to controller laravel

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');
}
});

Web Api Error 500

I have got a ajax call through which I am calling my Web Api.My code is as follows-
function DataFrame() {
var abc = {};
abc.Country = countryName;
abc.Month = monthName;
abc.SampleData = selectedStores;
var datatoSend = JSON.stringify(abc);
jQuery.support.cors = true;
$.ajax({
url: URL + '/api/Sample/AddSampleToFrame/',
type: "Post",
data: JSON.stringify(datatoSend),
contentType: 'application/json; charset=utf-8',
success: function (result) {
if (result.length > 0) {
_sampletabledata = $.parseJSON(result);
PoplulateListSample();
PopulateSampleCheckBox();
BindSampleGrid();
BindBoxesWithSet();
}
}, //success of ajax
return false;
}
This code is returning error 500.Need your suggestions

display values returned by json

I have simple question to display data on html page. Following code displays array of json data on screen. but, I want to display it by each element such as "url", "img_url" and so on.
could you please let me know who to do it ?
ajax code
var dataString = 'url=' + pathname + '&img_name=' + img_name + "&tag=" + tag;
$.ajax({
type: "POST",
url: "image_finder.php",
data: dataString,
dataType: 'json',
complete: function (xhr, status) {
if (status === 'error' || !xhr.responseText) {
//handleError();
alert("error");
} else {
var data = xhr.responseText;
$('#tt').html("<div id='message'></div>");
$('#message').html(data);
}
}
});
json return
{"cid":"14","url":"http:\/\/localhost\/","img_url":"http:\/\/static.naver.net\/www\/up\/2013\/0305\/mat_173330634c.jpg","img_name":"mat_173317134c.jpg","html":"<div id=\"hotspot-19\" class=\"hs-wrap hs-loading\">\r\n<img src=\"http:\/\/static.naver.net\/www\/up\/2013\/0305\/mat_173330634c.jpg\">\r\n<div class=\"hs-spot-object\" data-type=\"spot\" data-x=\"95\" data-y=\"64\" data-width=\"30\" data-height=\"30\" data-popup-position=\"left\" data-visible=\"visible\" data-tooltip-width=\"200\" data-tooltip-auto-width=\"true\">\r\nasdf\r\n<\/div>\r\n<div class=\"hs-spot-object\" data-type=\"spot\" data-x=\"168\" data-y=\"53\" data-width=\"30\" data-height=\"30\" data-popup-position=\"left\" data-visible=\"visible\" data-tooltip-width=\"200\" data-tooltip-auto-width=\"true\">\r\nrere\r\n<\/div>\r\n<\/div>\r\n","jscript":""}
$.ajax({
type: "POST",
url: "image_finder.php",
data: dataString,
dataType: 'json',
success: function (data) {
for(var item in data){
console.info(item);//print key
console.info(data[item]);//print value
}
}
});
I hope this is what you need.

asp.net mvc 3 json does not work

This is my jquery with json
$('#btnVerificationOk').click(function () {
var verId = $('#trans_verification_id').val();
var verCode = $('#trans_verification_code').val();
$.ajax({
url: '/Profile/CompleteTransactions',
type: 'POST',
data: { },
dataType: 'json',
success: function (result) {
alert(result);
},
error: function () {
alert('ERROR ERROR !!!!!!!!!!!!');
}
});
});
And My C# method:
[Authorize]
[HttpPost]
private JsonResult CompleteTransactions()
{
return Json("Done");
}
Its always alerts 'ERROR ERROR !!!!!!!!!!!!' i tried debugging but CompleteTransactions method is not firing
And this is my second json which is bellow and works good
$('#btnTransfareOk').click(function () {
var userName = $('#transfare_username').val();
var amount = $('#transfare_amount').val();
if (userName == '' || amount == '') {
$('#transfare_error_list').html('Please fill boxes.');
} else {
$.ajax({
url: '/Profile/TranfareMoney',
type: 'POST',
data: { ToUsername: userName, Amount: amount },
dataType: 'json',
success: function (result) {
$('#transfare_error_list').html(result.text);
$('#trans_verification_id').val(result.id);
$('#transfare_username').val("");
$('#transfare_amount').val("");
},
error: function () {
$('#transfare_error_list').html('Oops... Error.');
}
});
}
});
I'm not 100% sure, but shouldn't you controller action handler be public ?

ajax jquery pass null value

I get null values in the controller when I process the request using jquery ajax
Controller
[HttpPost]
public ActionResult UpdateAnswers(string answers, string question, string controlid, int eventid)
{
var replacetext=string.Empty;
if (answers.Length>0)
replacetext = answers.Replace("\n", ",");
_service.UpdateAnswers(eventid, replacetext, controlid);
return PartialView("CustomizedQuestions");
}
Jquery - Ajax Code
var test = "{ answers: '" + $("#answerlist").val() + "', question: '" + title + "', controlid: '" + controlid + "', eventid: '" + eventid + "' }";
$.ajax({
url: '#Url.Action("UpdateAnswers")',
type: 'POST',
dataType: 'html',
contentType: 'application/html; charset=utf-8',
context: $(this),
// data: "{ answers: '"+$("#answerlist").val()+"' ,question: '"+ title +"', controlid:'"+ controlid +"',eventid:'"+ eventid+"'}",
data: JSON.stringify(test),
success: function (result) {
$(this).dialog("close");
},
error: function () {
//xhr, ajaxOptions, thrownError
alert('there was a problem saving the new answers, please try again');
}
});
Your contentType is wrong. Why did you set it to application/html when you pass JSON? Try like this:
var test = { answers: $('#answerlist').val(), question: title, controlid: controlid, eventid: eventid };
$.ajax({
url: '#Url.Action("UpdateAnswers")',
type: 'POST',
dataType: 'html',
contentType: 'application/json; charset=utf-8',
context: $(this),
data: JSON.stringify(test),
success: function (result) {
$(this).dialog("close");
},
error: function () {
//xhr, ajaxOptions, thrownError
alert('there was a problem saving the new answers, please try again');
}
});
or using application/x-www-form-urlencoded which is the default:
var test = { answers: $('#answerlist').val(), question: title, controlid: controlid, eventid: eventid };
$.ajax({
url: '#Url.Action("UpdateAnswers")',
type: 'POST',
dataType: 'html',
context: $(this),
data: test,
success: function (result) {
$(this).dialog('close');
},
error: function () {
//xhr, ajaxOptions, thrownError
alert('there was a problem saving the new answers, please try again');
}
});

Resources