Issue with ajax and toastr.js - javascript

I'm using toast.js in an Asp.Net Core 2.0 application. Right now I have a problem with an ajax call. It seems that all works fine but my ajax doesn't execute success or error function.
The request finish with status 200 in chrome and the response actually show me the data that I return from my method.
The thing that I don't know why happens is that Chrome say that the Initiator is toastr.js instead of my function.
This is just an example of my function in javascript
function callAjax() {
var row = "1";
var json = "{'TwitterId':'" + row + "'}";
var token = $('input[name="__RequestVerificationToken"]').val();
var headers = {};
$.ajax({
type: 'POST',
url: "/Accesos/Index?handler=Example",
contentType: 'application/json',
async: false,
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: JSON.stringify({
Test: 'test'
}),
dataType: "json",
success: function () {
alert("It's works");
},
error: function (xhr) {
alert("There is a problem");
}
});
}
And this is the method in codebehind
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<JsonResult> OnPostExample(string Test)
{
var respuesta = new List<string> { "1", "string1", "string2" };
return new JsonResult(true);
}
This is the result that shows the debug in Chrome

This issue was solved in NToastNotify version 5.0.0

Related

Jquery, 405 error from Ajax call but the item is created

I keep getting a 405 error upon a POST method
$.ajax({
url: mistergoUrl,
type: "POST",
dataType: "json",
data: body,
crossDomain: true,
contentType: "application/json",
success: function () {
// TODO: find a cleaner way to get the last route
$.getJSON(mistergoUrl)
.done(function (data) {
data = resolveReferences(data);
window.location.replace("Route.html?id=" + data.last().RouteId);
});
},
error: function (httpObj, result) {
Console.log(result);
Console.log(httpObj);
}
});
On the server, the request is valid, is processed and returned as expected, but the Ajax function keeps giving back a 405 error...
This is the asp.net code
[HttpPost]
public IHttpActionResult Post(RoutePostModel postdata)
{
if (!ModelState.IsValid)
{
return BadRequest();
}
_routeService.Add(postdata);
var route = _routeService.GetAll().Last();
var url = Url.Route("DefaultApi", new {controller = "Routes", id = route.RouteId});
return Created(url, route);
}
Does anybody know why and how this could happen? any help is appreciated!

Web service receiving null with jQuery post JSON

The web service on http://localhost:57501/api/addDatabase has the following code.
[System.Web.Mvc.HttpPost]
public ActionResult Post(addDatabase pNuevaConeccion)
{
pNuevaConeccion.insertarMetaData();
return null;
}
The Ajax function is on a javascript that creates the JSON from the give values on http://localhost:1161/CreateServer.
$(document).ready(function ()
{
$("#createServer").click(function (e) {
e.preventDefault(); //Prevent the normal submission action
var frm = $("#CreateServerID");
var dataa = JSON.stringify(frm.serializeJSON());
console.log(dataa);
$.ajax({
type: 'POST',
url: 'http://localhost:57501/api/addDatabase/',
contentType: 'application/json; charset=utf-8',
crossDomain: true,
//ContentLength: dataa.length,
data: dataa,
datatype: 'json',
error: function (response)
{
alert(response.responseText);
},
success: function (response)
{
alert(response);
if (response == "Database successfully connected") {
var pagina = "/CreateServer"
location.href = pagina
}
}
});
});
});
When I run this code an alert pops up saying "undefined" but if I delete the contentType the alert doesn't show up. The problem is that the variables that the function Post (from the web service) receives are NULL even though I know that the JSON named dataa is not NULL since I did a console.log.
I have seen various examples and pretty much all of them say that I should use a relative URL but the problem is that since there are 2 different domains and when I tried it, it couldn't find the URL since it's not in the same localhost.
Web service should return a JSON format instead of null. like below example.
public JsonResult Post()
{
string output = pNuevaConeccion.insertarMetaData();
return Json(output, JsonRequestBehavior.AllowGet);
}
try to use this code for calling the web method
$.ajax({
method: "POST",
contentType: "application/json; charset=utf-8",
data: dataa,
url: 'http://localhost:57501/api/addDatabase/',
success: function (data) {
console.log(data);
},
error: function (error) {
console.log(error);
}
});
its my old code.(ensure action parameter variable name and post variable name are same)
$('#ConnectionAddres_ZonesId').change(function () {
var optionSelected = $(this).find("option:selected");
var id = { id: optionSelected.val() };
$.ajax({
type: "POST",
url: '#Url.Action("GetParetArea", "Customers")',
contentType: "application/json;charset=utf-8",
data: JSON.stringify(id),
dataType: "json",
success: function (data) {
$('#ConnectionAddres_ParentAreaId').empty().append('<option value="">Select parent area</option>');
$.each(data, function (index, value) {
$('#ConnectionAddres_ParentAreaId').append($('<option />', {
value: value.Id,
text: value.Area
}));
});
},
});
});
public ActionResult GetParetArea(int id)
{
var parents="";
return Json(parents, JsonRequestBehavior.AllowGet);
}

Jquery Ajax success wont firing instead complete event works

I am using Angular Js with JQuery in a noodles way. See my code below.
Code
app.controller('ClassController', function ($scope) {
$scope.ShowHideNoRecords = false;
var credentials = new Object();
credentials.SourceName = "###";
credentials.SourcePassword = "###";
credentials.UserName = "###";
credentials.UserPassword = "##";
credentials.SiteId = [-99];
var locationIds = [1];
var startDate = Date.today();
var endDate = startDate;
var dto = { credentials: credentials, startDate: startDate, endDate: endDate, locationId: locationIds };
$.ajax({
type: "POST",
url: 'MbApiConnector.asmx/GetAllClasses',
data: JSON.stringify(dto),
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
success: function (response) {
alert(response.d);
},
complete: function (msg) {
$scope.$apply(function () {
$scope.Classes = JSON.parse(JSON.parse(msg.responseText).d);
if ($scope.Classes.length > 0) {
$scope.checkin = function (id) {
dto = { credentials: credentials, classId: id };
$.ajax({
type: "POST",
url: 'MbApiConnector.asmx/Checkin',
data: JSON.stringify(dto),
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
complete: function (msg) {
alert(msg.responseText);
}
});
}
}
else {
$scope.ShowHideNoRecords = true;
}
});
}
});
});
Everything is working fine with this code. I knew its a bad idea mixing the two but my app was already developed in Jquery Ajax and we are upgrading with Angular JS but with lesser changes. So I came up with this solution.
Anyways, my issues is that jquery ajax success function is not get called. I am able to receive data from the webservice , but inside the complete method, as you can see in the code above.
Can you explain me why its behaving so?
May be Jquery fails to parse it as the result may not be in JSON format, try to find the error using error callback function. You could try with dataType : 'json'.
error: function (err) { alert(err) }

MVC jQuery Ajax Post - can only get it to work with hard-coded values

So I have a basic controller accepting a post..
[HttpPost]
public ActionResult Submit(string postCost)
{
//Do stuff here before sending back redirect details...
return Json(new { result = "Redirect", url = Url.Action("Index", "Confirm") });
}
And I'm posting via jquery ajax method:
$.ajax({
url: partyURL,
dataType: 'json',
contentType: 'application/json', //charset=utf-8',
type: 'POST',
data: { postCost: postageCost}, //**This fails!**
//data: "{'postCost':'3.50'}", //**This works**
success: function (response) {
if (response.result == 'SoldOut') {
$("#soldOut").show();
}
else if (response.result == 'Redirect') {
//All good, onward to confirmation page
window.location = response.url;
}
},
error: function (xhr, status, error) {
// Error handling here
}
});
where the postageCost variable sent in when it fails returning status 500:
postageCost = '3.50';
postageCost = JSON.stringify(postageCost); //also fails with this
but if I hard-code the data definition as
data: "{'postCost':'3.50'}",
It works fine.
The key must therefore lie in what I'm doing with the data element?
you need to do
var datum = {'postCost': '3.50'};
data: JSON.stringify(datum), //Ajax call data

How to call MVC Api controllers HttpResponseMessage Post action using javascript as client?

I am calling this action of api from client. The client code also see below.
API Action:
public class StudentTestController : ApiController
{
[HttpPost]
public HttpResponseMessage GetLessonInfo(int request)
{
HttpResponseMessage result = null;
result = Request.CreateResponse(HttpStatusCode.OK,StudentTest.GetLessonInfo(request));
return result;
}
}
JavaScript client script:
function SendRequest() {
var url = "http://localhost:1938/api/StudentTest/GetLessonInfo";
var data1 = "request=293";
$.ajax({
type: 'POST',
url: url,
data: data1,
contentType: 'application/json; charset=utf-8',
dataType: 'jsonp',
success: function (data) {
$('#txtResponce').val(JSON.stringify(data.Data));
},
error: function (xhr, status, error) {
var errorText = xhr.status + "\r\n" + status + "\r\n" + error;
$('#txtResponce').val(errorText);
}
});
}
When i am trying to call Action with the above snippet it will not calling the controller action. How to solve this?
Pavan.
Have you tried this instead:
var url = "/api/StudentTest/GetLessonInfo";
var data1 = "293";
Maybe "request=293" can be considered as a string and not the "int" expected as parameter.
And since the int parameter is not nullable, maybe it's giving you a Bad Request response.
Check with Fiddler what is being sent to the server.

Categories

Resources