Cross domain jQuery ajax calls not working - javascript

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);
}

Related

Unable to access JSONBin.io even I have added the Auth Headers

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

How to disable 'withCredentials' in api call using node.js only (https package)

I'm using a node.js script that load in-built https package. When using it I get error:
XMLHttpRequest cannot load [constructed-api-url]. A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true. Origin 'http://localhost:3000' is therefore not allowed access. The credentials mode of an XMLHttpRequest is controlled by the withCredentials attribute.
I'm using node.js 4.4.3, and its https api docs does not really mention anything about withCredentials.
The script being used is this one.
Is there anyway to set the xhr call's withCredentials to false using node.js https?
I am looking to something analogous to this jquery ajax call (just focusing on the xhr field):
$.ajax({
type: 'POST', async:true,
url: 'https://someapp.constructed.url/token',
dataType: "json",
contentType: 'application/x-www-form-urlencoded; charset=utf-8',
xhrFields: {
withCredentials: true
},
headers: {
'Authorization': 'Basic ' + appInfo
},
success: function (result) {
var token = result.access_token;
//…
},
error: function (req, status, error) {
if (typeof(req) != 'undefined') {
var msg = status || req.responseJSON.error;
//…
}
}
});
There is another very similar example, but this is related to the request package, which I don't want to include in dependencies. Beside, my used script is already using https.
So the answer was there all the time, after all:
After a bit of research, found that node's https package uses practically same options as http, including the withCredentials option (not documented in node's http/https, but part of xhr documentation). It was a matter of including the url option within the options object along the withCredentials option, and then pass the options object as parameter for https.get.
And the constructed code would be more or less as follows (focus on the options variable):
var options = {
url: 'https://my.domain.com/api/endpoint',
withCredentials: false
}
var querystring = '?key=' + [_my_api_key];
var param1 = '&' + [paramKey] + '=' + [paramValue];
var datos;
options.url += querystring;
options.url += param1;
https.get(options, function (res) {
res.on('data', function (data) {
datos += data;
});
res.on('end', function () {
try {
var data = JSON.parse(datos);
} catch (e) {
console.error('Unable to parse response as JSON', e);
}
});
}).on('error', function (e) {
console.error('An error occurred with the request:', e.message);
callback(e.message);
});

How to Post Google Forms Data via jQuery and Ajax to Spreadsheets

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

Error When Ajax sending two Request to Wicket Server

I am posting data to the wicket server via ajax when user click.to make the state ,retrieve the data when page loading ,via ajax GET, if only one request is sending then its working fine ,but in second request following error has thrown.
org.apache.wicket.core.request.mapper.StalePageException
How can I send the data to the server via ajax and later load the panel
with the submitted data when user load it.
Code :Java Script
Sending data to the server
function submitdata() {
$.ajax({
url : $('#mark').attr('json:callback.url1'),
type : 'post',
cache : false,
data : ko.toJSON(familyModel),
ntentType : 'application/json',
dataType : 'json',
complete : function() {
} ,
error: function(xhr, status, error){
console.log(xhr);
alert(status);
alert(error);
}
});}
}
Page Load
$(document).ready(function() {
$.ajax({
url : $('#mark').attr('json:callback.url'),
type : 'GET',
cache : false,
contentType : 'application/json',
success: function (data) {
console.log(data);
var parsed = JSON.parse(data);
// ko.mapping.fromJS(data, familyModel);
/ ko.applyBindings(familyModel);
// familyModel=new FamilyModel();
ko.applyBindings(familyModel);
},
error: function(xhr, status, error){
console.log(xhr);
alert(status);
alert(error);
}
});
}
public class AbstractJSONBehavior extends AbstractAjaxBehavior {
public void onRequest() {
RequestCycle requestCycle = RequestCycle.get();
readRequestData(requestCycle);
sendResponse(requestCycle);
}
You are using plain jQuery APIs and Wicket believes that the requests are non-Ajax, so it increments the Page#renderCount counter to prevent using page with stale information.
If you use Wicket.Ajax.post({...}) then Wicket will figure this out automatically.
So you can either use Wicket.Ajax.post() or pass either the request parameters or headers from https://github.com/apache/wicket/blob/master/wicket-request/src/main/java/org/apache/wicket/request/http/WebRequest.java#L40-L48 with value true to the jQuery#ajax().

Not getting proper response from server using jquery?

I am not getting server response from server using jquery.But when I check from server end server end guy get the response .I am sending same value in parameter ,But not getting the response ?
can you please help me out ?
This image is when server person check .It is getting response.
But
http://jsfiddle.net/ravi1989/LsKbJ/4/
$(document).ready(function () {
//event handler for submit button
$("#btnSubmit").click(function () {
//collect userName and password entered by users
var userName = $("#username").val();
var password = $("#password").val();
//call the authenticate function
authenticate(userName, password);
});
});
//authenticate function to make ajax call
function authenticate(userName, password) {
$.ajax
({
type: "POST",
//the url where you want to sent the userName and password to
url: "http://dd.c-dd.de/cc/REST/Login",
type: "POST",
dataType: 'json',
async: false,
crossDomain: true,
//json object to sent to the authentication url
data: {Application:"61136208-742B-44E4-B00D-C32ED26775A3",
Device:"null",
LoginKind:"0", Password: "1",Username:"qus"},
success: function (t) {
alert(t+"df")
},
error:function(data){alert(data+"dfdfd")}
})
}
XMLHttpRequest cannot load http://isuite.c-entron.de/CentronService/REST/Login. Origin http://fiddle.jshell.net is not allowed by Access-Control-Allow-Origin.
Cross Origin Policy restricts connecting to different domain name

Categories

Resources