OBJECTIVE:
When user is inactive for 5 minutes, my base.js file will send an ajax request to the server, server will flush all session data. I got everything right till here. Further after logging the user out, I want to display a page saying you have been logged out, with some custom data ( eg: user name) which I will be sending to that page via POST method.
I cannot use window.location(url) because in doing so I can only send data with GET method.
AJAX code in VUE Axios :
axios({
method: 'post',
url: 'ajax/logout/',
data: { },
responseType: 'json',
})
.then ( function (response){
console.log('AJAX success');
})
.catch ( function (error){
console.log('ajaxLogout error');
});
Django view looks like :
def ajaxLogout(request):
return JsonResponse ({"success":1} )
Related
I am learning JS, jquery, and trying to build a login page and after giving the credentials to my application URL I should get a response back and I should be able to perform actions accordingly.
Something like: if the response is "success" then I should get an alert for success and redirect to another page (not sure how to do that) and if the response is "fail" I should throw an alert.
Below is the relevant snippet from my js file:
$.ajax({
url: "http://localhost:8588/api/userLogin",
type: "POST",
data: credentials,
dataType: "json",
contentType: 'application/json',
success: function(response) {
alert(response);
}
});
And my java controller method snipped annotated with #RestController:
#PostMapping(value = "/userLogin", consumes = "application/json")
public String userLogin(#RequestBody UserRequest userRequest) {
System.out.println(userRequest.getUserId()+ " "+ userRequest.getPassword());
User user = userService.getUser(userRequest);
return (user != null) ? "succeess" : "fail";
}
I am not getting any error
I am able to call the API but not getting the response back on UI. What am I missing?
I've taken your code and simulated simple case like yours. Most of the code looks right but as you've said there are no errors in the console and no response to client so there's problem got to be somewhere. There are certain things you've not specified here, so for more context for other people I am assuming UserRequest as
public class UserRequest {
public String username;
public String password;
}
and for the ajax request data I'm using
JSON.stringify({username: "developer", password:"pass"})
Now, I'm getting 200 response code with success message in alert at client side. Let me know if any error pops up after trying this.
I am building a web app with Django/Python and trying to send data to a controller via a POST request using the Axios library (within Vue.js code).
The POST QueryDict seems to be empty and I can't see why that is happening:
changeCountry: function(e, id){
console.log("Let's change the country")
console.log(e.target.value) // is printing correctly
console.log(id) // also printing correctly
axios({
method: 'post',
url: '/template/country',
data: {
id: id,
country: e.target.value
},
headers: {
'X-CSRFToken': "{{csrf_token}}"
}
})
.then(function (response) {
alert(response.data); // this is returning what I expect
})
.catch(function (error) {
console.log(error);
})
},
The Python method looks like this:
def update_template_country(request):
pprint(request.POST) # prints an empty QueryDict
id = request.POST.get('id')
country = request.POST.get('country')
print(id, country) #prints None None
return HttpResponse("The country is changed") # this is being returned back to the client
The console.log messages at the top print what I expect and since there is no error I am assuming the CSRF header token is fine. Have I missed something obvious or misunderstood how this is working?
EDIT: looking at the Chrome Network tab, it seems the data is being 'POSTed' correctly:
It shows this:
{"id":"593ff2270098e6e8d3292b60","country":"US"}
and that's what I expect, so I suspect the issue is with Django. But I can't see what that might be.
Write your python POST request like this:
def update_template_country(request):
data = json.loads(request.body)
id = data["id"]
country = data["country"]
'''Any other function you want to perform'''
return HttpResponse(json.dumps({'message':'The country is changed'},status=200)
Basically the problem is with the format of POST request, Django is not able to parse it properly that's why when you print the POST request it return an empty dictionary.
I am trying to send some data to my server using an AJAX Post call. However, whenever I run the function containing the ajax call I get a server error. Here is my AJAX call (I am trying to send a string and put it inside json for the purposes of this call):
function sendFileName(){
data_to_send={"name": scriptName};
data_to_send=JSON.stringify(data_to_send);
$.ajax({
url: '/filename',
type: 'POST',
dataType: 'json',
data: data_to_send,
error: function(resp){
console.log("Oh no...");
console.log(scriptName);
console.log(resp);
},
success: function(resp){
console.log('Sent file name!');
console.log(resp);
}
});
}
When I log the scriptName I get it in the console, so the data exists. I'm assuming the issue has to do with the way in which I'm sending it?
Here is the server-side code as well, where when I log the req it shows up as undefined:
app.post("/filename", function(req,res) {
file = req.body.name;
console.log(file);
});
Would really appreciate any help I can get with this!
I have a route
Route::post('/updateLogo', 'CaptivePortalController#updateLogo');
Then I make a POST here
$http({
method: 'POST', <----- I did a POST
url: '/updateLogo',
headers: { 'Content-Type': undefined },
transformRequest: function (data) {
console.log("data coming into the transform is ", data);
var formData = new FormData();
formData.append("company_logo_path", data.files);
console.log($scope.files.company_logo_path);
return formData;
},
data: { files: $scope.files.company_logo_path }
})
.then(function successCallback(response) {
console.log("success");
console.log(response);
$('.save-fade').delay(500).fadeOut(1000);
}, function errorCallback(response) {
console.log("fail");
console.log(response);
});
When I browse the file, and submit the form, I kept getting
405 in my Network tab on Chrome Dev Tool.
Then, I click on it, I see
MethodNotAllowedHttpException in RouteCollection.php line 218:
I know that I'm NOT suppose to make a GET to a POST route, but Why does it make a GET request instead of a POST?
Request URL:http://l.ssc.com:8888/en/updateLogo
Request Method:GET <------
Status Code:405 Method Not Allowed
Remote Address:127.0.0.1:8888
Referrer Policy:no-referrer-when-downgrade
What did do wrong here ?
Any hints ?
This looks like a re-direction taking place.
refer : $http.post() method is actally sending a GET
Please check your route configuration at the server, make sure it is exactly the same as you're requesting.
If you're requesting a '/myroute' but you've defined the route as '/myroute/' then your server could be redirecting to '/myroute'.
All re-directions are done using a GET.
And since the route doesn't allow GET request, it's returning a 405.
I'm about to implement a Login using Google OAuth. I followed the official Google docs
The client does get a token from the Google server. But whenever I try to send it back to my server to store it, I do not seem to get data from the AJAX call. Here is my code:
function signInCallback(authResult) { //called when client has confirmed the Login dialog
if (authResult['code']) {
// Hide the sign-in button now that the user is authorized, for example:
$('#signinButton').attr('style', 'display: none');
console.log("signinCallback. Send code to server:")
console.log("Code = "+ authResult['code']);
console.log("performing AJAX call now...\n\n")
// Send the code to the server
$.ajax({
type: 'POST',
url: 'http://localhost:9000/storeauthcode',
contentType: 'application/octet-stream; charset=utf-8',
success: function(result) {
// Handle or verify the server response.
console.log("AJAX call --> success");
console.log(result)
},
processData: false,
data: authResult['code']
});
} else {
//There was an error.
console.log("AJAX call failed.")
}
I created a line in my routes file:
POST /storeauthcode controllers.Application.storeAuthCode
The method on the server:
def storeAuthCode = Action { request =>
Ok("storeauthcode called with queryString = "+request.rawQueryString)
}
The following is a console output of my Chrome browser:
hello.js:2 Welcome to your Play application's JavaScript!
(index):67 signinCallback. Send code to server:
(index):68 Code = <token deleted for privacy reasons>
(index):69 performing AJAX call now...
(index):77 AJAX call --> success
(index):78 storeauthcode called with queryString =
So although my browser gets a token back, I cannot store it on the server, because I don't get any data back.
Ok("storeauthcode called with queryString = "+request.body.asJson)
is also empty.
This one here also delivers an empty result:
def storeAuthCode = Action { request =>
Ok("storeauthcode called with queryString = "+request.getQueryString("data"))
}