$.Get() method with authentication 401 response - javascript

I have an ajax get method, it needs credentials to work.
I have the credenntials to access the API, i don't know how to pass the credentials through the get method:
$.get(url, function (response) {
$.each(JSON.parse(response).canchas, function (key, bucket) {
}
}
thanks!
edit:
$.ajax({
url: "https://tes.r/links/" + id + "/buckets",
data: {username: "backoffice", password: "111111"},
dataType: "JSON",
type: "GET",
success: function (response)
{
$("#ul_list_view").empty();
$.each(response.buckets, function (key, bucket) {
$("#ul_list_view").append('<li><h2>' + bucket.dayOfWeek + '</h2><p>' + bucket.timeOfDay + '</p></li>');
});
$("#ul_list_view").listview("refresh");
},
error: function (response)
{
$("#div_resultado2").addClass("error");
$("#div_resultado2").html(response.responseText);
}
});
Still returning 401, username and password is correct

Assuming you mean the API uses HTTP Basic authentication, use $.ajax instead and pass the username and password properties ~ http://api.jquery.com/jQuery.ajax/
$.ajax(url, {
username: 'backoffice',
password: '111111',
dataType: 'json' // no need for JSON.parse if you tell jQuery the response type
}).done(response => {
$.each(response.canchas, (key, bucket) => {
// etc
})
})

Related

csrf token is changing where it shouldn't be changed

I'm running code below to prevent CSRF vulnerability
if (!isset($_POST['_token'])) {
$_SESSION['_token'] = bin2hex(random_bytes(20));
}
and i am using the token in hidden inputs named _token. I use the following code in my main.js file so that the user can add the product to their favorites.
const wishlist = {
'add': function (id) {
$.ajax({
url: 'api/wishlist?method=add',
type: 'post',
dataType: 'json',
data: 'id=' + id + '&_token=' + $('input[name="_token"]').val(),
success: function (response) {
console.log(response)
}
})
},
'remove': function (id) {
$.ajax({
url: 'api/wishlist?method=remove',
type: 'post',
dataType: 'json',
data: id,
success: function (response) {
console.log(response)
}
})
}
};
Below is the code in wishlist.php which ajax request goes to
<?php
if ($_SERVER['REQUEST_METHOD'] != 'POST') {
header('Location:' . site_url('404'));
}
if (!isset($_POST['_token']) or $_POST['_token'] != $_SESSION['_token']) {
die('Invalıd CSRF Token!');
}
if ($_GET['method'] == 'add') {
$json['method'] = "adding to favorites";
}
if ($_GET['method'] == 'remove') {
$json['method'] = "removeing from favorites";
}
The all code is this but sometimes this code works sometimes it gives Invalid csrf token error and sometimes it works for 3-5 times and gives error again.
I found the solution. It was because client is trying to access to an non-exist file
so that that request executes init.php

JQuery ajax function sends the correct value.But RestController receives null

These codes are RestController of my spring boot project,
#RestController
#RequestMapping(value="/rest/user")
public class UserRestController {
#Autowired
private UserService userService;
#PostMapping("login")
public ResponseEntity<Boolean> authenticated(#RequestBody User user) {
System.out.println(user.getUsername() +":"+ user.getPassword()); //This line returns NULL password value
Boolean blogin = userService.authenticate(user.getUsername(), user.getPassword());
if(!blogin)
return new ResponseEntity<Boolean>(blogin, HttpStatus.NOT_ACCEPTABLE);
return new ResponseEntity<Boolean>(blogin, HttpStatus.OK);
}
}
And Below codes are JQuery ajax java-script codes.
function ajax_login_submit() {
var user = {
username: $("#username").val(),
password: $("#password").val()
};
console.log(user);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "rest/user/login",
data: JSON.stringify(user),
dataType: 'json',
success: function (data) {
var resultJson = JSON.stringify(data);
$('#helloUserDiv').html(resultJson);
console.log("SUCCESS : ", data);
alert(data);
},
error: function (e) {
var resultJson = e.responseText;
$('#helloUserDiv').html(resultJson);
console.log("ERROR : ", e);
}
});
}
console.log(user); of java script returns the correct value.
{"username":"joseph","password":"password"}
But in the RestController codes, password value is missing, "NULL".
The line System.out.println(user.getUsername() + ":" + user.getPassword()); returns strange value, "joseph:null"
Is it possible for JQuery ajax method not to transfer the json value to REST server? If I make some mistakes, kindly inform me how to send the json value to REST server correctly.
Try this:
$.ajax({
type: "POST",
contentType: "application/json",
url: "rest/user/login",
data: JSON.stringify({"username": $("#username").val(), "password": $("#password").val()}),
dataType: 'json',
success: function (data) {
var resultJson = JSON.stringify(data);
$('#helloUserDiv').html(resultJson);
console.log("SUCCESS : ", data);
alert(data);
},
error: function (e) {
var resultJson = e.responseText;
$('#helloUserDiv').html(resultJson);
console.log("ERROR : ", e);
}
});

Get json response with jquery or ajax or angular js

Good morning stackoverflow,
I try to get json response from an URL
Click, as expected i got Access-Control-Allow-Origin within GoogleChrome, I switched to FireFox, to avoid this problem and then i got status -1 and data null.
$(document).ready(function () {
var URL = "https://www.infojort.com/axs/search?q=marouani%20zied";
console.log('------------------------');
$.ajax({
url: URL,
dataType: 'application/json;charset=utf-8',
success:function (data) {
console.dir(data);
console.log('yes');
},
complete:function () {
console.log('yes');
}
})
$.ajax({
dataType: "application/json;charset=utf-8",
url: URL,
success: function (data) {
console.dir(data);
}
});
$.getJSON(URL, function (data) {
var items = [];
$.each(data, function (key, val) {
items.push("<li id='" + key + "'>" + val + "</li>");
});
$("<ul/>", {
"class": "my-new-list",
html: items.join("")
}).appendTo("body");
});
Notice :
I can get the response with postman without problems.
Content-Type →application/json;charset=utf-8
I need a solution with jquery, ajax or angularjs.
Thanks you all.
Your problem seems related to the API and not to your JavaScript call itself,
what I mean is that you are trying to Call to your API from a Cross Origin and it is not allowed by default for security reasons, so you have to enable cross origin in the server in order to make this kind of calls https://spring.io/understanding/CORS
Look at this, it is a Cross Origin call (Jquery within AngularJS):
$.ajax({
type: 'POST',
url: CTHelper.ApiUrl() + '/token',
data: {
grant_type: 'password',
username: $scope.UserName,
password: $scope.Password
},
success: function (result) {
alert('OK');
},
error: function (result) {
alert('Error');
}
});
but the API must allows CORS, this is a part of the file Startup.Auth.cs
[This example uses AspNet Web Api, C# as Backend]
public void ConfigureAuth(IAppBuilder app) {
...
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
...
}
Microsoft.Owin.Cors can be downloaded as a nuget package.

Can't sending data from View to Controller

can you help about that issue?
I am trying to pass my data to the controller. Below you can see my ajax code.
<script type="text/javascript">
$(document).on("click", "#login_button", function () {
var userName = document.getElementById("userName").value;
var password = document.getElementById("password").value;
if (userName !== "" && password !== "") {
$.ajax({
url: '/Home/Login',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: {
'userName' : userName,
'password' : password
},
datatype: 'json',
success: function (data) {
}
})
}
else {
alert("Lütfen Alanları Doldurunuz.")
}
})
</script>
And my controller is like,
[HttpPost]
public ActionResult Login(string userName, string password)
{
return View();
}
I checked my data and it is not empty or null. How can I fix it?
Now I am getting this error =
jquery.min.js:4 POST http://localhost:59277/Home/Login 500 (Internal Server Error)
Thanks a lot.
I had the same problem today during a programming competition.
What solved it for me was using a different way of sending a GET request:
$.get("URL/to/send/request/to", function(data, status){
alert("Data: " + data + "\nStatus: " + status);//data is the actual response you get, while status is weather the request was successful
});
});
Hope it works for you too.
i thik you should use
url: 'http://stackoverflow.com/Home/Login',
instead of
Home/Login
i solve my problem changing the type of ajax as "GET" and changing my controller as "HttpGet" but when I do this for "POST" it didn't solve. Can anyone explain it to me?
$.ajax({
url: 'http://stackoverflow.com/Home/Login',
type: "POST",
dataType: 'json',
data: dataToPost,
contentType: "application/json; charset=utf-8",
success: function (data) {
alert("hi" + data);
}
});
i think it is work

jQuery Ajax request turn into AngularJS $http request

I have such jQuery Ajax request. I need to turn it into an AngularJS $http request. How can I do that?
$.ajax({
type: "POST",
dataType: "jsonp",
crossDomain: false,
data:{
user: username,
pass: password
},
beforeSend: function (request){
request.setRequestHeader("Accept-Language", languageCode);
},
url: someUrl
})
.done(function (data, textStatus, jqXHR){
console.log(data);
})
.fail(function (jqXHR, textStatus){
console.log("failed");
});
My Angular Implementations
Response {"data" : "", "status" : "200", "config" : .... } Data is empty
login : function (username, password) {
return $http({
method: 'POST',
url: someUrl,
data: {
user: username,
pass: password
},
headers: {
'Accept-Language': languageCode
}
})
}
I succeeded to get data wrapped in JSON_CALLBACK with next request. But I don't know how to call that callback. It is not done automatically. Response looks like {data:"JSON_CALLBACK({mydata})"...}
login : function (username, password) {
var url = someUrl
+ '?callback=JSON_CALLBACK&user=' + username
+ '&pass=' + password;
return $http.post(url);
},
There is no such thing as a JSONP POST request. When jQuery sees dataType: jsonp, it ignores the method propery and uses a script GET request. The data is added as parameters of the URL.
In AngularJS, JSONP requests are specified with method: 'JSONP. The callback parameter needs to be JSON_CALLBACK and must be capitalized.
login : function (username, password) {
return $http({
//method: 'POST',
method: 'JSONP',
url: someUrl,
//data: {
params: {
user: username,
pass: password,
callback: "JSON_CALLBACK"
},
headers: {
'Accept-Language': languageCode
}
})
}
Be aware that since the data is sent as URL parameters, sensitive information such as passwords are vulnerable to snooping attacks.
To demonstrate on JSFiddle:
var url="//jsfiddle.net/echo/jsonp/";
var params = { user: "myUser",
pass: "123456",
callback: "JSON_CALLBACK"
};
$http.jsonp(url, { params: params} )
.then(function onSuccess(response) {
$scope.response = response;
console.log(response);
})
The DEMO on JSFiddle.
Please refer to $http documentation. but here is somewhat counterpart for that jquery request
$http({
method: 'POST',
url: '/someUrl',
data: {
user: username,
pass: password
},
headers: {
'Accept-Language':languageCode
}
}).then(function successCallback(response) {
//do something
}, function errorCallback(response) {
//do something
});
AngularJS error .success is not a function
Might have something to do with it??
What API are you working with?

Categories