Ajax POST MyUrl 404 (Not Found) - javascript

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;

Related

Ajax request to Django returns 404 not found

I am writing my first project in Django where I now want to make an Ajax request using jQuery to get some data. The problem is that the Ajax request returns:
GET http://localhost:8000/ajax/teams_for_issue/?medIssue=MI6 404 (Not Found)
I am rather certain that the problem is with the URL, and I have gotten the URLs wrong several times before in this project. My Ajax code looks as follows:
var medIssue = _this.issueSelector.val();
$.ajax({
url: '/ajax/teams_for_issue/',
data: {
'medIssue': medIssue
},
dataType: 'json',
success: function(data) {
_this.setTeams(data.teams)
}
});
This is the Django function that I want to send the answer:
def teams_for_issue(request):
medIssue = request.GET.get("medIssue", none)
teams = Team.objects.filter(has_competence=medIssue)
data = {
"teams":teams
}
return JsonResponse(data)
I have defined the following URL
url(r'newpatient/', views.newpatient, name='newpatient'),
url(r'ajax/teams_for_issue/', views.teams_for_issue, name='teams_for_issue'),
Any help on where I go wrong would be much appriciated :)
define type in your ajax request.
$.ajax({
url: '/ajax/teams_for_issue/',
type: "POST",
data: {
'medIssue': medIssue
},
dataType: 'json',
success: function(data) {
_this.setTeams(data.teams)
}
});
also your view should read data from request.POST
def teams_for_issue(request):
medIssue = request.POST.get("medIssue", none)
teams = Team.objects.filter(has_competence=medIssue)
data = {
"teams":teams
}
return JsonResponse(data)

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!

When sending jQuery post to MVC controller getting 404 error

I'm sending from view using jQuery to MVC post action
function DoSomething(passedId) {
$.ajax({
method: "POST",
dataType: 'text',
url: '/MyController/SomeAction/',
data: { id: passedId}
}).done(function (data) {
//
});
}
And inside MyController
[HttpPost]
public ActionResult SomeAction(int id)
{
...
}
In Firebug console I'm getting 404 error.
You didn't said which version of jquery you are using. Please check jquery version and in case that this version is < 1.9.0 you should instead of
method: "POST"
use
type: "POST"
this is an alias for method, and according to jquery official documentation you should use type if you're using versions of jQuery prior to 1.9.0.
function DoSomething(passedId) {
$.ajax({
type: "POST",
dataType: 'text',
url: '/MyController/SomeAction/',
data: { id: passedId}
}).done(function (data) {
...
});
}
Tested above code and it works (each request enter inside mvc controller http post SomeAction action).
In the RFC 2616 the code 404 indicates that the server has not found anything matching the Request-URI.
So you need to look at your URL parameter.
Try the MVC conventional call using :
url: '#Url.Action("SomeAction", "MyController")',
To resolve the 404 issue:
There are a few options to resolve this. You controller/action cannot be find the way it is describe.
-If you are in a view that is in the controller for which the action your are trying to call is located, then:
url: 'SomeAction',
-If you are trying to call an action from another controller, OtherController, for example, then:
url: 'Other/SomeAction',
-To add to another answer, if you are calling your ajax inside the view (and NOT in a javascript file) then you can also use (for a controller called SomeController):
url: '#Url.Action("SomeAction", "Some")',
Additional Items Of Note:
You do not specify a content type for json (contentType indicates what you are sending):
contentType: "application/json; charset=utf-8",
I can't tell, based on your action if you are expecting 'text' or something else. However, unless expecting 'json', I would remove the data part.
You need to stringify your data
JSON.stringify(data: { id: passedId}),
In the end, I would expect it to look something like:
function DoSomething(passedId) {
var url = "SomeAction"; //if action is in OtherController then: "Other/SomeAction"
$.ajax({
method: "POST",
url: url,
data: JSON.stringify({ id: passedId}),
contentType: "application/json; charset=utf-8"
}).done(function (data) {
//
});
}
The slash at the beginning of this designates an absolute path, not a relative one.
/MyController/SomeAction/
You should include a URL or relative path.. maybe
'MyController/SomeAction/ajax.php'
or the full URL
'http://example.com/myajaxcontroller/someaction/ajax.php'
or stolen from the other guys answer
url: '#Url.Action("SomeAction", "MyController")',
To address others on here, I don't think the datatype is the
problem... OP says "I'm getting 404 error."
contentType is the type of data you're sending, so
application/json; charset=utf-8 is a common one, as is
application/x-www-form-urlencoded; charset=UTF-8, which is the
default.
dataType is what you're expecting back from the server: json, html,
text, etc. jQuery will use this to figure out how to populate the success function's parameter.
Write the code this way:
function DoSomething(passedId) {
$.ajax({
url: 'yourController/SomeAction',
type: 'POST',
data: { id: passedId},
dataType: 'json',
error: function (ex) {alert(ex.responseText)},
success: function (data)
{
if (data.Results != null) {
//use the return values
});
}
}
});
}
and the controller
public JsonResult SomeAction(int id)
{
try
{
return Json(new { Results = "Text To return or send some object or an list, etc"}, JsonRequestBehavior.AllowGet);
}
catch (Exception)
{
throw;
}
}
Finally, check that the controller has its respective view. :)
and and the library of "jQuery" updated.
just in case.
use the following ajax call
var datum = { id: passedId };
$.ajax({
url: url, // your url
type: 'POST',
data: JSON.stringify(datum),
contentType: 'application/json; charset=utf-8',
beforeSend: function () {
},
complete: function () {
},
success: function (user, status, XHR) {
},
error: function (req, status, error) {
}
});
UpDated
public ActionResult SomeAction(int id){} should accept string parameter instead of int

ajax Json return type not comming in success

I have following ajax call:
$.ajax({
type: "GET",
url: "/Company/validateForm",
dataType: "json",
data: {
'txtCompanyName': txtCompanyName,
'txtCompanyContactPerson': txtCompanyContactPerson,
'txtCompanyPhone': txtCompanyPhone,
'txtCompanyFax': txtCompanyFax,
'txtCompanyEmail': txtCompanyEmail,
'txtCompanyWebsite': txtCompanyWebsite,
'txtZipcode': txtZipcode,
'txtCountry': txtCountry,
'txtAddress1': txtAddress1,
'txtAddress2': txtAddress2,
'txtCompanyRegNo': txtCompanyRegNo
},
success: function (responceMessage) {
alert(responceMessage);
if (responceMessage != "1") {
alert(responceMessage);
} else {
saveCompanyInformation();
}
},
error: function () {
alert('failure');
}
});
I have made sure that call is going to server side and returning proper message in string format.
But when call from validateForm method on server side is returned, it directly goes to failure instead of success method.
I can't figure out what I'm doing wrong here.
Console is showing:
GET http://localhost:49273/Company/validateForm?txtCompanyName=+x&txtCompanyCon…ebsite=&txtZipcode=&txtCountry=&txtAddress1=&txtAddress2=&txtCompanyRegNo= 500 (Internal Server Error)
I just made cache:false in ajax and code worked.
It was as follows:
$.ajax({
type: "POST",
url: "/Company/validateForm",
cache:false,
dataType: "json",
data:
{
'txtCompanyName': txtCompanyName,
'txtCompanyContactPerson': txtCompanyContactPerson,
'txtCompanyPhone': txtCompanyPhone,
'txtCompanyFax': txtCompanyFax,
'txtCompanyEmail': txtCompanyEmail,
'txtCompanyWebsite': txtCompanyWebsite,
'txtZipcode': txtZipcode,
'txtCountry': txtCountry,
'txtAddress1': txtAddress1,
'txtAddress2': txtAddress2,
'txtCompanyRegNo': txtCompanyRegNo
}
,
success: function (responceMessage) {
if (responceMessage != "0") {
alert(responceMessage);
}
else {
saveCompanyInformation();
}
},
error: function () {
alert('failure');
}
});

PHP RestServer Class - Ajax call

I'm practicing with the PHP RestServer Class. But I can't get the correct data from it if I use an Ajax call on it. I have the following code:
<?php
require_once "locationOfRestServer.php";
class HelloWorld
{
public static function sayHello()
{
return array("Response" => "Hello World");
}
}
$rest = new RestServer('HelloWorld');
$rest->handle();
And in my javascript file I use the following:
this.helloWorld = function() {
$.ajax({
url: 'locationOfHelloWorld.php'
type: 'POST',
dataType: 'json',
success: function(data){
console.log(data);
}
});
};
I get the following error:
error: "No method was requested."
Because; whenever I use it, I have to go to localhost/HelloWorld.php?method=sayHello which is actually working.
So I added the following line to the ajax call:
method: 'sayHello',
But it still keeps giving me the same error.
Try this,
$.ajax({
url: 'locationOfHelloWorld.php'
type: 'GET',// use GET method according to your working url
data:{method: 'sayHello'},// use method in data parameter
dataType: 'json',
success: function(data){
console.log(data);
}
});

Categories

Resources