So, basically, I am trying to get data from JSONbin.io. I have set the RequestHeader before I send the request. As you see there's beforeSend and xhr.setRequestHeader("X-Master-Key", "$2b$10$QCzFeVffyq7vaiSBUfPbCeXUGV.IBpiHlWIOsDQAgj########");. But, it still say Error 401 aka unauthenticated request. I wondering if someone can help me with this. I also provide image that show that the headers is there.
Link: https://jsonbin.io/api-reference
Image: https://ibb.co/jGtFLk9
<script>
function getKey() {
$.ajax({
url: 'https://api.jsonbin.io/b/624efc9cd8a4cc06909d66cd/2',
type: "GET",
dataType: "json",
beforeSend: function(xhr) {
xhr.setRequestHeader("X-Master-Key", "$2b$10$QCzFeVffyq7vaiSBUfPbCeXUGV.IBpiHlWIOsDQAgj########");
},
success: function(data) {
const keyStore = data.keys;
var copyKey = document.getElementById("KeyDisplay");
document.getElementById('KeyDisplay').value = keyStore[Math.floor(Math.random() * 49)]
document.getElementById('Button').textContent = "Copied Key"
document.getElementById("Button").disabled = true;
copyKey.select();
navigator.clipboard.writeText(copyKey.value);
}
});
}
</script>
```
[1]: https://i.stack.imgur.com/zQxGv.png
Related
I am using node.js and Express.js on the back end, and am trying to make a server call from the client via AJAX.
So I have this POST request that works fine with AJAX:
node.js/Express.js:
app.post('/createNewThing', function(req, res) {
var userInput = req.body.userInput;
if (userInput) {
res.send('It worked!');
}
});
Client Side/AJAX request:
var userInputForm = $('#userInputForm.val()')
$.ajax({
url: "/createNewThing",
type: "POST",
data: "userInput=" + userInputForm,
dataType: "text",
success: function(response, status, http) {
if (response) {
console.log('AJAX worked!);
}
}
});
The userInputForm comes from an HTML form.
This POST request works fine. But I want to change this to a GET request. If I change app.post to app.get, and change type in the AJAX call to GET, I get this 500 error:
GET /createNewThing?userInput= 500
When you make a GET request, the data appears in the query string (of the URL in the request headers). It doesn't appear in the request body. There is no request body.
When you try to read from the request body, you are trying to access a property of an undefined object, which triggers an exception and cause an internal server error.
This answer explains how to read a query string:
var id = req.query.id; // $_GET["id"]
So
var userInput = req.query.userInput;
I think var userInputForm = $('#userInputForm.val()') will get error or get wrong data..This may be the reason for the error. Due to userInputForm may not be a string and concatenate with userInput=
Actually it is bad data.
And for the data in ajax, you should modify data from data: "userInput=" + userInputForm,
to:
data: {
userInput: userInputForm
},
dataType: "json"
And var userInputForm = $('#userInputForm.val()')
to var userInputForm = $('#userInputForm').val();
At last, you could modify as bellow, I believe it works:
var userInputForm = $('#userInputForm').val();
$.ajax({
url: "/createNewThing?userInput=" + userInputForm,
type: "GET",
success: function(response, status, http) {
if (response) {
console.log('AJAX worked!);
}
}
});
I am trying to call MVC Controller from jquery but not able to place the call. Is there any problem in below code
Please figure out that if any problem and also I am not getting any error.
url="http://localhost:49917/Account/SaveAddress"
this.SaveAddress = function (url, addressData)
{
$.ajax({
type: "POST",
url: url,
dataType: "json",
data: JSON.stringify(addressData),
contentType: 'application/json; charset=utf-8',
success: function (responseDetail) {
},
error:function(e)
{
},
});
return 0;
};
public async Task<ActionResult> SaveAddress(AddressListViewModel addressListVM)
{
bool response;
string message;
if (addressListVM.ID <= 0)
{
response = await Task.Run(() => AccountManager.Instance().AddAddress(addressListVM));
message = response ? "New address added successfully." : "Failed to add new address.";
}
else
{
response = await Task.Run(() => AccountManager.Instance().UpdateAddress(addressListVM));
message = response ? "Selected address updated successfully." : "Failed to update selected address.";
}
ModelState.Clear();
return Json(new { responsestatus = response, message = message }, JsonRequestBehavior.AllowGet);
//return PartialView("_AddressDetail", BuildAddressListEntity(
// UserManager.FindById(User.Identity.GetUserId()), response, message, addressListVM.ID, true));
}
Yes, you are missing a closing bracket at the end of the this.saveaddress function
this.SaveAddress = function (url, addressData)
{
$.ajax({
type: "POST",
url: url,
dataType: "json",
data: JSON.stringify(addressData),
contentType: 'application/json; charset=utf-8',
success: function (responseDetail) {
},
error:function(e)
{
},
});
after all of that .. you need one more closing bracket:
}
;)
What does the console display? If you are using Chrome then right-click, choose Inspect, and find the Console tab. If you are calling the AJAX function correctly then something must be displayed in this Console tab which will probably lead you in the right direction better than I could with the information I have.
Put a breakpoint in your success and error functions. If it hits the error function then the issue is either that the controller action was not found or that the data is not valid json (either the post data or return data). You should add the errorThrown parameter to the error function so you can easily see what the issue is. You also do not need to stringify the data if it is already valid json, but if it is a string representing json data, you will need to use json.parse (sorry for the incorrect case).
I have requirement like that, when I send request, CSRF-token should be send with it. I Explore some SO questions, But I can't find Solution.
I have written Code like bellow to add token when request being sent,
var send = XMLHttpRequest.prototype.send,
token = $('meta[name=csrf-token]').attr('content');
XMLHttpRequest.prototype.send = function(data) {
this.setRequestHeader('X-CSRF-Token', "xyz12345");
//this.setRequestHeader('X-CSRF-Token',getCSRFTokenValue());
return send.apply(this, arguments);
}
This is Working Fine, But now i need to add CSRF-Token in function in place of xyz12345.
I have tried ajax function as below .
`
$.ajax({
type: "POST",
url: "/test/"
//data: { CSRF: getCSRFTokenValue()}
}).done(function (data) {
var csrfToken = jqXHR.getResponseHeader('X-CSRF-TOKEN');
if (csrfToken) {
var cookie = JSON.parse($.cookie('helloween'));
cookie.csrf = csrfToken;
$.cookie('helloween', JSON.stringify(cookie));
}
$('#helloweenMessage').html(data.message);
});
But it is not Yet Worked.
So my question is:
How to get js side CSRF-Token Value?
you need to do this in new Laravel
var csrf = document.querySelector('meta[name="csrf-token"]').content;
$.ajax({
url: 'url',
type: "POST",
data: { 'value': value, '_token': csrf },
success: function (response) {
console.log('value set');
}
});
I get my CSRF Token by this way,
By adding function :
$.get('CSRFTokenManager.do', function(data) {
var send = XMLHttpRequest.prototype.send,
token =data;
document.cookie='X-CSRF-Token='+token;
XMLHttpRequest.prototype.send = function(data) {
this.setRequestHeader('X-CSRF-Token',token);
//dojo.cookie("X-CSRF-Token", "");
return send.apply(this, arguments);
};
});
Where CSRFTokenManager.do will be called from CSRFTokenManager Class.
Now It is adding token in header and cookie in every request.
I'm working on a Chrome extension that's essentially a simple custom Google Form that will post to a response Spreadsheet. I got the following function to successfully send and populate data only once, but never again:
function postFormToGoogle() {
var timeOne = $("#time1hour").val();
var timeTwo = $('#time2hour').val();
var timeThree = $('#time3hour').val();
$.ajax({
url: "https://docs.google.com/forms/d/FORMKEY/formResponse",
beforeSend: function (xhr) {
xhr.setRequestHeader('Access-Control-Allow-Origin', 'chrome-extension://EXTENSION_ID');
xhr.setRequestHeader('Access-Control-Allow-Methods', 'GET, POST, PUT');
},
data: { "entry_856586387": timeOne,
"entry_244812041": timeTwo,
"entry_2138937452": timeThree },
type: "POST",
dataType: "xml",
xhrFields: {
withCredentials: true
},
statusCode: {
0: function () {
document.getElementById("message").innerHTML = "Your form has been submitted!";
window.location.replace("ThankYou.html");
},
200: function () {
document.getElementById("message").innerHTML = "Your form has been submitted!";
console.log("Success");
window.location.replace("ThankYou.html");
}
}
});
}
I had to include the cors request headers because I was getting a No 'Access-Control-Allow-Origin' warning that blocked my request.
It being an extension, I also added the following permissions to the manifest.json file:
"permissions": [
"http://docs.google.com",
"https://docs.google.com",
"https://*.google.com",
]
At this point, I'm not sure exactly what's preventing the data from posting. Possible indicators could be that when submitting the form I'm getting a "Provisional Headers are shown" caution and the server is taking way too long to respond as indicated by the Waiting (TTFB) time.
Where am I going wrong in the code? (It did work once, for some reason.) Any alternative solutions out there to post a custom form to Spreadsheets?
This is the way I did it... http://jsfiddle.net/adutu/7towwv55/1/
You can see that you receive a CORS error but it works... the data gets where it should be
function postToGoogle() {
var field3 = $('#feed').val();
$.ajax({
url: "https://docs.google.com/forms/d/[key]/formResponse",
data: {"entry.347455363": field3},
type: "POST",
dataType: "xml",
statusCode: {
0: function() {
//Success message
},
200: function() {
//Success Message
}
}
});
}
See more info here
I'm having trouble with this code and I can't seem to get it to work. The typical error that I get back for this call is a "Failed to load resource: the server responded with a status of 401 (Unauthorized) " .
$('#btnZendesk').click(function () {
$.ajax({
url: "https://flatlandsoftware.zendesk.com/api/v2/topics/22505987.json",
type: 'GET',
crossDomain: true,
xhrFields: {
withCredentials: true
},
cache: false,
dataType: 'jsonp',
processData: false,
data: 'get=login',
timeout: 2000,
username: "test#test.com",
password: "test",
success: function (data, textStatus, response) {
alert("success");
},
error: function (data, textStatus, response) {
alert(data);
}
});
Problem is that the resource you are trying to access is protected with Basic Authentication.
You can use beforeSend in jQuery callback to add a HTTP header with the authentication details e.g.:
beforeSend: function (xhr) {
xhr.setRequestHeader ("Authorization", "Basic XXXXXX");
}
Alternatively you can do it using jQuery ajaxSetup
$.ajaxSetup({
headers: { 'Authorization': "Basic XXXXX" }
});
EDIT
A few links to the mentioned functions
jQuery.ajaxSetup
jQuery.ajax
EDIT 2
The Authorization header is constructed as follows:
Username and password are joined into a string "username:password" and the result string is encoded using Base64
Example:
Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
I too got this problem and somehow all solutions from internet either failed or were not applicable due to client webservice restrictions (JSONP, XDR, CORS=true)
For this, I added an iframe in my page which resided in the client;s server. So when we post our data to the iframe and the iframe then posts it to the webservice. Hence the cross-domain referencing is eliminated.
We added a 2-way origin check to confirm only authorized page posts data to and from the iframe.
Hope it helps
<iframe style="display:none;" id='receiver' name="receiver" src="https://iframe-address-at-client-server">
</iframe>
//send data to iframe
var hiddenFrame = document.getElementById('receiver').contentWindow;
hiddenFrame.postMessage(JSON.stringify(message), 'https://client-server-url');
//The iframe receives the data using the code:
window.onload = function () {
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
eventer(messageEvent, function (e) {
var origin = e.origin;
//if origin not in pre-defined list, break and return
var messageFromParent = JSON.parse(e.data);
var json = messageFromParent.data;
//send json to web service using AJAX
//return the response back to source
e.source.postMessage(JSON.stringify(aJAXResponse), e.origin);
}, false);
}