No route matches [GET] error when sending a post request with ajax - ajax

Sending a post request via ajax but getting the error above, "No route matches [GET]".
ajax looks like this
$.ajax({
type: 'POST',
url: '/stage_progress',
data: {'subject_id' : subject, 'course_id' : course, "chapter_id" : chapter, "stage_id" : stage, "user_id" : user, "session" : "0", "completed" : "true"},
success: function(){
console.log('got it');
}
});
routes.rb
post '/stage_progress', to: 'stage_progress#track_progress'
If I run rake routes it shows that a post route to this url exists but for some reason the ajax is creating a "get" request. Any help explaining why and how to fix it would be greatly appreciated.

When looking into your code, you are overriding the default index action of your controller 'stage_progress'. Calling '/stage_progress' will only route to the default index action(get). I guess you either rename the route '/stage_progess' to something else and that would solve the issue.
Or in other case you still want the same route, then try writing it above all other routes,
post '/stage_progress', to: 'stage_progress#track_progress'
resources 'stage_progress'
Because the routes are always mapped from top to bottom in the routes.rb file. If there is any other 'GET' route above the 'POST' route declaration, it will still take only the first route configured.

Related

Axios AJAX call nulls parameter

I use Vuejs to create my frontend for my project.
At the creation of one component ('TimeCapsy.vue'), I make an AJAX call to my backend like this:
created: function () {
if (verify.verify_login()) {
let token = this.$cookies.get('jwt_us_cas');
let params = {'jwt': token};
console.log(params);
axios({
method: 'post',
url: dev.HOST+'getuserinfoobject',
params: queryString.stringify(params)
})
.then(response => {
console.log(response.data)
})
}
}
As you can see I use the
this.$cookies.get('jwt_us_cas');
to get the a json web token, that I set on the client at the login.
I use the queryString Library to stringify my parameters for my request.
I also tried it without the queryString.stringify(params) call, but I get the same error, e.g. the parameter still turns into null.
When I look at the console log, where I check the params variable, I get this output:
{jwt: "my token comes here"}
So I can see, that it gets the correct value from the cookie.
But when I check the answer from my backend (PHP), I get this error:
Undefined index: jwt in <b>D:\casb\public\index.php</b> on line <b>52</b>
Of course I know that it means, that jwt is null, but I can't understand why.
As I said, right before I make the call I check the params and it shows the token.
I checked the endpoint with Postman and the token as the jwt parameter and it returned a successfull call with the correct answer.
A correct answer is basically just a nested object with some information in it.
My PHP endpoint is pretty basic too:
Router::add('/getuserinfoobject', function () {
$response['response'] = User::getUserInfoObject($_POST['jwt']);
echo json_encode($response);
}, 'post');
So I guess that right before or in my call it nulls my parameter. But I can't understand how, since I make a lot of requests and never had this problem.
From axios docs
params are the URL parameters to be sent with the request
Which means, you should get the value with PHP $_GET.
Or $_REQUEST (which stores both $_GET, $_POST. Also $_COOKIE).
The other hand, you can use data key as docs says
data is the data to be sent as the request body
Only applicable for request methods PUT, POST, and PATCH
So the value would be available in $_POST
axios({
method: 'post',
url: dev.HOST+'getuserinfoobject',
data: {
jwt: token
}
})

Ext.Ajax Cross-Domain post request

I'm testing ExtJS v.5.1.0.107 and I my goal is that to perform a post ajax request on a different server. I've found some similar discussions but nothing seems to work for my scenario.
Here's request code:
Ext.Ajax.request({
url: 'http://192.168.1.60/test.php',
method: 'POST',
cors: true,
useDefaultXhrHeader : false,
params : {
myPar1 : myPar1Value
},
success: function () {
alert('success');
},
failure: function () {
alert('failure');
}
});
Here's error message:
XMLHttpRequest cannot load http://192.168.1.60/test.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://192.168.1.50:22800' is therefore not allowed access.
Is there something wrong?
Hope someone can help me.
Thanks to all.
Make sure your files are reachable from the server...
If the server is well configured, try add a response header for
Access-Control-Allow-Origin: *
This command will allow cross-domain through Ajax operations. Then, the requested file (test.php for instance on the targeted server) should contain in the first lines :
<?php header('Access-Control-Allow-Origin: *'); ?>
Then, you should change parameter for Apache server hosting test.php file. In the .htacess file :
header set Access-Control-Allow-Origin "http://192.168.1.60/"
Hope this helps !

A 405 status code from web API after trying to send PUT data in body

ok.
I'm using Web API to make AJAX requests.
I'm trying to send a PUT request to an action on a controller.
I'm using route attributes.
When I'm sending the data as part of the route data, everything is fine and the action gets the right info.
However, when I'm trying to send the data in the body, I get a 405 status ((Method is not allowed).
I'm also adding the [FromBody] attribute to the parameter. Here's by jQuery call:
type: 'PUT',
url: 'api/ServerQueue/activity',
data: "=2",
success: function (xhr) {
$("#load").hide();
},
error: function () {
$("#load").hide();
}
};
Here's my action:
[Route("status/{status}")]
public string PutStatus([FromBody]int status)
{
}
I placed a "RoutePrefix" on the controller body.
BTW, I'm using VS 2012.
Any idea what could be the source of the problem?
Try changing the route configuration from
[Route("status/{status}")]
to
[Route("status")]

Error 404 RESTFul Service with Ajax

I got a RESTful service call with ajax :
var request = $.ajax({type: "GET",
type : "GET",
url : "/services/equipment/searchEquipments?pId="+id,
cache : false
});
The java method in the service is declared as :
#GET
#Path("/searchEquipments/{pId}")
#Produces("application/json; charset=UTF-8")
public List<EquipmentVO> searchEquipments(#PathParam("pId") String pId){
I got a 404 return code.
I can't understand because after the call, the 404 code is on a weird URL :
http://localhost:7001/services/equipement/searchEquipments?pId=00192772&_=1408446932784
I can't figure why there's &_=1408446932784 at the end ??? It's not a part of the made URL during the call.
Any idea ?
RESTfull service does not accept argument in this way.
the argumant should be a part of the path (as it is defined)
so you should send a get request to "/services/equipment/searchEquipment/"+id
(without the ?pId=)
for example, if the Pid is 123, the path should be
/services/equipment/searchEquipment/123

ajax json request , always returning error

Hello i've got a problem with ajax json request. Im always getting an error, even if the requests are succeeded. At the moment i have this code:
function sumbitLoginForm(user, pass) {
if (user.trim() == '' || pass.trim() == '') {
alert("You must enter username and password!");
} else {
$.ajax({
type : 'POST',
url : 'https://url.php',
dataType : 'json',
data : {
userlogin : user,
userpass : pass
},
contentType: "application/json;",
success : function(data) {
$("#images").html("uspeshno");
},
error : function(data) {
$("#images").html("greshka");
}
});
}
return false;
}
$(document).ready(function() {
clearPageInputs();
$("#submitButton").click(function() {
sumbitLoginForm($("#username").val(), $("#password").val());
});
});
Im always getting an error , no matter what username and password i type . But the status of request is changing , if i type correct user and pass i get status 302 Moved temporarly , but when i type wrong user or pass i get status 200 OK . What am i doing wrong ?
PRG Pattern and Ajax
It looks like your server returns a HTTP 200 status code when the userid and password will not validate. This is proper behavior, as HTTP error codes not meant for application errors, but for HTTP protocol errors.
When the userid and password are matched succesfully, you are redirected to another page. This is also normal behavior, e.g. to prevent other people to re-use your login credentials using the back key.
This is called the Post/Redirect/Get pattern.
See: http://en.wikipedia.org/wiki/Post/Redirect/Get
The problem is that the PRG pattern does not play nice with Ajax applications. The redirect should be handled by the browser. It is therefore transparent for the jQuery code. The Ajax html response will be the page that is mentioned in the Location header of the 302. Your Ajax application will not be able to see that it is being redirected. So your are stuck.
In one of my projects I solved this on the server side. If I detected an Ajax call, I would not send a redirect but a normal 200 response. This only works if you have access to the server code.
If you cannot change the redirect for your Ajax calls, then you can parse the response headers or the html to see if you were being redirected and act accordingly. Probably the login will set a cookie, so you might try and look for the presence of that cookie.

Resources