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

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!

Related

Laravel $request->all() is returning nothing in response to an ajax request

My ajax request shown below sends a json object to a backend function which is supposed to return $request->all() but instead returns nothing if i send the json cordinates that i'm currently sending but if i send a simple JSON it returns just fine.
AJAX
var JSONObj = {"test" : "test1"};
var PointsOnCanvas = [{"PX":486,"PY":447,"CX":485,"CY":447},{"PX":485,"PY":447,"CX":487,"CY":443},{"PX":487,"PY":443,"CX":490,"CY":438},{"PX":490,"PY":438,"CX":499,"CY":423},{"PX":499,"PY":423,"CX":500,"CY":421},{"PX":500,"PY":421,"CX":512,"CY":402},{"PX":512,"PY":402,"CX":519,"CY":392},{"PX":519,"PY":392,"CX":532,"CY":371}]
$.ajax({
url: "/Ajax",
type: "GET",
//datatype: "json", //could be xml, json, html, text or script
contentType: "application/json",
data: JSONObj,//JSON.stringify(PointsOnCanvas),
error: function (response) {
console.log(response)
},
success: function (response) {
console.log(JSON.stringify(PointsOnCanvas))
console.log("response is " + response)
console.log("json response is " + JSON.stringify(response))
PointsOnCanvas = [];
}
});
I have commented out //JSON.stringify(PointsOnCanvas) above this is the code that i believe is causing the problem.
The laravel code is below
public function RecieveAjax(Request $request){
if($request->ajax()){
return response()->json(['result' => $request->all()]);
}else{
return "Not Helo";
}
}

Issue with ajax and toastr.js

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

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

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

Ajax POST MyUrl 404 (Not Found)

i'm working on some grails code and geting this error whenever the ajax function is getting the response from the controller action!
the Ajax function is passing the parameters and controller function is performed after the return i get this error from the browser developing tool.
$.ajax({
url: urlMap.myUrl_url,
type: "POST",
dataType: 'JSON',
data: {
pId: pId,
stId: stId
},
success: function (data) {
$supplementaryHolder.html(data);
}
})
Here is the controller function !
def deleteSupplementary = {
if (!modifyService.deletePlacement(params.long('pId'))) {
flash.error = g.message(code: 'student.delete.placement.failed')
}
return params.stId;
}
Mistake seems to be at this line
return params.stId;
change it to
render params.stId;

Categories

Resources