Ajax POST to MVC Controller always erroring - ajax

I have the following Ajax request:
$.ajax({
url: '/Projects/Index',
type: 'POST',
data: data,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
error: xhr => { swal('From Error!', 'We\'ve saved your hours, thanks for your input!', 'success'); console.log(xhr) },
success: result => swal('From Success!', 'We\'ve saved your hours, thanks for your input!', 'success')
});
Which, even when the status code is 200, always errors. My controller receives the data and does stuff with it, and then returns View().
Here's my controller action in full:
[HttpPost, ActionName("Index")]
public ActionResult SetHours(HourPostRequest[] data)
{
foreach(var item in data)
{
var correctModel = item.ToEngineerHours(db);
db.EngineerHours.Add(correctModel);
db.SaveChanges();
}
var eng = db.Engineers.FirstOrDefault(e => e.DomainUsername == User.Identity.Name).ID;
var test = db.EngineerHours.Where(e => e.EngineerID == eng).ToList();
return View(test);
}
The data is always intact, received fine and View always returns. I've added in a random test collection to return which is the model of my View:
#model IList<Timesheet.Models.EngineerHours>
I've gone into the Chrome Dev-Tools Network view and the payload is correct, response is 200 and the controller has received the data and returned View.
This means that my SweetAlert2 alerts are always erroring regardless of the success status.
Can anybody spot why this might be happening?

You are returning the View(), which is an HTML string at the end of the day. However in your request you specify:
dataType: 'json'
which tells jQuery to expect response as a json formatted string. jQuery sees HTML and is not able to recognize it as a valid json, hence the error.

Related

ASP.NET Core 2.2 Razor Pages - AJAX Call to page model not returning data

I am new to AJAX and cant even get the basics to function correctly.
I run an AJAX call from within a function in the javascript section from razor page but I cannot get the required string value to be returned.
The result I get in the alert box simply shows the HTML layout of the razor page as the message, as opposed to the actual string I want to return. I've spent hours trying to incorporate a X-CSRF-TOKEN in the header, but this makes no difference. I'm not sure the anti forgery token is required here and therefore the issue is before this step.
Razor Page:
$.ajax({
type: "GET",
url: "/Maps?handler=CanvasBackgroundImage",
contentType: 'application/json',
success: function (result) {
alert(result);
}
});
Page Model:
public JsonResult OnGetCanvasBackgroundImage()
{
var result = "test message";
return new JsonResult(result);
}
Below is the code that is now working for me. Thanks for everyone's input.
Razor Page (script section):
function getMapBackgroundImagePath() {
// Get the image path from AJAX Query to page model server side.
$.ajax({
type: "GET",
url: "/Maps/Create?handler=MapBackgroundImagePath",
contentType: "application/json",
data: { imageId: imageId, }, // Pass the imageId as a string variable to the server side method.
dataType: "json",
success: function (response) {
copyText = response;
// Run the function below with the value returned from the server.
renderCanvasWithBackgroundImage();
},
});
}
Page model:
public JsonResult OnGetMapBackgroundImagePath(string imageId)
{
// Get the image full path where the id = imageId string
int id = Convert.ToInt32(imageId);
var imagePath = _context.Image.Where(a => a.ID == id)
.Select(i => i.ImageSchedule);
// return the full image path back to js query in razor page script.
return new JsonResult(imagePath);
}

How to fetch ajax request data in cakephp 2 controller?

I'm trying to send some data from my view to my controller via ajax. How do I retrieve this data in my action?
I've tried jQuery's $.ajax and $.post methods, providing the url and data, but using $this->data, $this->request->data, $_POST, $_GET or $_REQUEST doesn't work (all return as empty arrays).
$.ajax({
url: "<?php echo Router::url( array("controller" => "Progression", "action" => "submit", $user['User']['id']) ); ?>",
type: 'post',
data: { name: "John" }
}).done( function(data) {
console.log(data);
});
function submit() {
$this->request->allowMethod('ajax');
$this->autoRender = false;
$data = array();
$data['answer'] = $this->request->data; // or any of $_POST, $_GET, etc.
return json_encode($data);
}
My console always keeps printing {"answer":[]}. I checked the network tab of my devtools and the data is successfully listed under Form data, yet I can't seem to get hold of the data in the action.
EDIT:
Thanks to Greg Schmidt I found out that my request indeed got redirected: first it gives me a 302, then it makes a new request without the post data and returns a 200. I just can't find what the critical difference is between the two requests (URLs look the same, no case difference or anything). Can anybody help me with that?
First request:
Second request:

Return a a json object from an ajax call to a django view

Am trying to return a json object to render to a grid in my template.
This is how i do it.
views.py
def ajax_up(request):
history_data=Upload_history.objects.all()
history=serializers.serialize("json",history_data)
return HttpResponse( history, mimetype='application/json' )
html
$(".reply").click(function(){
$.ajax({
url: "/ajax_up/",
type: 'GET', //this is the default though, you don't actually need to always mention it
dataType: "json",
success: function(data) {
alert("awasome"+ data)
},
failure: function(data) {
alert('Got an error');
}
});
so i declare an object to hold the data as
var data = {{history|safe}};
where history is returned from the ajax call as in view above
but when i do alert(data), i get [object object],[object object].....
can any one help please?
Sounds like it's working, but alert just displays a string. Since your data is not a string, it'll show [object Object].
Either serialize the data with JSON.stringify or use console.log instead of alert to see the data in your browser javascript console.

Retrieve post value in the controller sent by ajax call

I am unable to retrieve value sent as a post through ajax call in cake php controller file
$.ajax({
type: "POST",
url: "share",
data: country,
dataType: "json",
success: function (response) {
if (response.success) {
// Success!
} else {
console.log(response.data, response.code);
}
}
});
I have tried with the below ways of retrieving the data sent in the above code through POST. But none of them worked.
$this->params
$this->data
$_POST[]
$this->request
The url points to the function in the controller page.
Please can any of you let me know how the value can be retrieved.
When submitting data via ajax and you want cake to pick it up in the usual way just use $('whatever').serialize().
if you don't have an actual form to serialize you can fake it by submitting the data as follows:
$.ajax({
...
data: {
data: country
},
...
});
Note how cake generates fields like data[Model][field]. you don't need the Model part but the data part is important.

406 Error when returning JSON object – Unexpected content

A few colleagues and I have a problem whereby the response from an ajax call returns some unexpected content. Rather than getting a simple JSON object back with various properties, the value of result.responseText is the HTML markup of a generic 406 status error page, saying the MIME type is not accepted by the browser.
The call is made like so:
$.ajax({
url: '/promociones/cincogratis/canjear-codigo-promocional',
type: this.method,
data: $(this).serialize(),
success: function (result) {
$('.promotion_banner .loader').hide();
$('.promotion_banner').html(result);
},
error: function (result) {
var obj = result.responseText;
if (obj.isRedirect) {
document.location = obj.redirectUrl;
}
else {
$('.promotion_banner .loader').hide();
$(".error-wrapper").removeClass("hidden");
var generic_error = document.getElementById('generic_error').value;
$(".error-wrapper p").html(generic_error);
}
},
beforeSend: function() {
$('.promotion_banner .loader').show();
}
});
The controller response to the call is like so:
Response.StatusCode = (int)HttpStatusCode.NotAcceptable; // 406
return Json(new { errorMessage = LocalErrorMessages.Website_Promotions_FreeFiver_General_Problem, isRedirect = false } );
We would expect result.responseText to contain key values for errorMessage and isRedirect, but they’re not there.
It’s worth pointing out that this code is multi-tenanted, shared by the current application and another one, where it works absolutely fine.
We’ve tried:
- Configuring IIS to show detailed error responses rather than a custom page for more detail – gives us nothing extra towards solving the problem.
- Allowing all response content types to the call
- Changing the culture of our site (which is currently es-ES)
- Various web.config tweaks
Has anyone ever had this problem?
Simplify your request. Maybe something like:
$.ajax({
url: '/promociones/cincogratis/canjear-codigo-promocional',
type: 'GET',
data: {foo:'bar', one:'two'},
dataType: 'json',
success: function (result) {
console.dir(result);
},
error: function (xhr) {
console.dir(xhr)
}
});
And post the response from the server. This kind of error seems a request problem rather than server configuration issue

Resources