Problem sending AJAX request with headers on Blackberry Webworks - ajax

I am developing a Blackberry webworks application and I am having trouble with an AJAX request that I am making to a server. I am learning HTML/Javascript/AJAX on the fly, so excuse any beginner mistakes. Basically, formatted HTTP requests are made to the server, which returns JSON objects that I use in the application. I am using AJAX to make the requests without any kind of framework.
Most requests do not have to be authenticated, and those are returning just fine. However, to access a directory part of the server, a username and password are encoded and sent as a header with the XMLHTTPRequest. when I try and add the header, the request is sent, but I never get anything back. The readyState property is set to 1, but never goes beyond that. I know the server works fine, because I did the same thing for iPhone, and it worked.
Here is the relevant code:
function grabFromServer(httpRequest){
httpConnection = new XMLHttpRequest();
var me = this;
httpConnection.onreadystatechange=function(){
alert(httpConnection.readyState);
if(httpConnection.readyState==4){
me.processResponseText(httpConnection.responseText);
}
};
httpConnection.open("GET", httpRequest,true);
if(this.request == "company" || this.request == "property" || this.request == "individual"){
var authorized = this.checkCredentials();
if(!authorized){
//ask for username pword
}
//here, add credentials
httpConnection.setRequestHeader("Authorization", "Basic : ODI5ZGV2bDokY19kdXN0Ym93bA==");
}
httpConnection.send();
}

Your code appears to be good. Have you added an entry in your config.xml file to allow access to your domain? You should see an entry for something like <access subdomains="false" uri="http://data.mycompany.com/"/>. To make any HTTPRequests to an external website from a WebWorks application, you have to add an entry to "whitelist" domain like this.
If you're using the eclipse plugin, open up the config.xml file, click the Permissions tab at the bottom, and click "Add Domain".

Related

$urlRouteProvider, simple routing

Can't get my head around $urlRouterPovider...
basically whenever I go to a link it should load associated view and controller. So that works.
$urlRouterProvider.when("/","/home")
$urlRouterProvider.otherwise("/error")
$stateProvider.state('views', {
url: "/:view",
templateUrl: function(stateParams, formResolver) {
return "views/" + stateParams.view + "/" + stateParams.view + "-view.html";
},
controllerProvider: function($stateParams) {
return "" + $stateParams.view + "Ctrl";
}
});
So whenever user goes to http://localhost:3030/#/foo, it loads "views/foo/foo.html" with controller as "fooCtrl", and goes to home by default, and for all other cases errror.
That is cool. What I need though, whenever user goes to http://localhost:3030/#/auth it would redirect to "/auth" on the server, skipping stateProvider. Currently it sees that as a state and tries to find corresponding view and controller.
If you need to redirect them to the server you need to leave out the #/ part of the URL.
The browser ignores the the #/ portion of the URL, which is how AngularJS is able to allow the page you server from localhost:3030/#/ handle the request. This is essentially still just requesting localhost:3030/
If you are wanting to do a true redirect or navigation to /auth on your server, ignore state for that request - you want your browser to make a straight-up HTTP request pointed directly at your server. Use /auth as the action in your form, or post to /auth from within your controller. When you are done on the server, redirect the user back to your Angular application.
Remember as well that you need to have some mechanism for your AngularJS application to know ehnIn our applications, we have the server set a cookie with a JWT token in it that is then used by the AngularJS application to retrieve the user information. This way the AngularJS application knows how to tell when a the user is really logged in (vs. a user going to a URL that represents a logged-in state).

Localhost returns 404.3 when fetching json through ajax (Windows 8.1)

So I have been getting the infamous 404.3 error when trying to use AXAJ to access a .json file launching the site (or more of a test app hehe) through WebMatrix on localhost.
Yes, I am aware of the IIS configuration. I am on Windows 8.1(x64), so I had to even turn on MIME types functionality separately. I configured a MIME type for .json with application/javascript. Then I went and added a handler to *.json, pointed it to C:\WINDOWS\system32\inetsrv\asp.dll. I set the verbs to GET and POST (those are what I use in my ajax function). I also tried unchecking the "Invoke the handler only if request is mapped to..." to no avail.
I am using one function to send data to PHP file which writes it to the JSON file and then another to fetch data from the JSON file directly. Writing through PHP works. Fetching doesn't. I am completely at a loss, does anyone have any ideas? The code I am using to fetch the data is your bog-standard ajax:
function getDate(path, callback) {
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState === 4) {
if (httpRequest.status === 200) {
var data = JSON.parse(httpRequest.responseText);
if (callback) callback(data);
}
}
};
httpRequest.open('GET', path);
httpRequest.send();
}
When I host this on my server space, it works totally fine. But I want to get it to work locally for testing purposes as well.
If writing to the file works but fetching doesn't work. Then you should check for the link of the file.
The error 404 as the name refers to, is an error for the file name. There isn't any other sort of error, even the Ajax request is working fine and giving the error 404 (file not found). So the only thing that you can do is, to make sure that while fetching the data, you use the correct link.
Here can be a help, when you send the Request through Ajax, there is a Network tab in your Browser's console. Open it, and look for the request. It would in red color denoting an error and click it. You'll see that the link you're providing isn't valid.
Look for the errors in the File Link then and update it.
The lengths I go to, to clean up my profile...
When you require a JSON format, or any file for that matter you have to specify in your request what data type you need, IIS will not make any assumptions. So
xhr.setRequestProperty('Content-Type', 'application/json');
is something one must not forget. I set also the X-Requested-With header. Note that to reproduce this issue I used IIS that is installed on Windows 10 Pro, so not exactly the same system (3 years later - holy crap!).

Refused to set unsafe header "Origin" when using xmlHttpRequest of Google Chrome

Got this error message:
Refused to set unsafe header "Origin"
Using this code:
function getResponse() {
document.getElementById("_receivedMsgLabel").innerHTML += "getResponse() called.<br/>";
if (receiveReq.readyState == 4 || receiveReq.readyState == 0) {
receiveReq.open("GET", "http://L45723:1802", true, "server", "server123"); //must use L45723:1802 at work.
receiveReq.onreadystatechange = handleReceiveMessage;
receiveReq.setRequestHeader("Origin", "http://localhost/");
receiveReq.setRequestHeader("Access-Control-Request-Origin", "http://localhost");
receiveReq.timeout = 0;
var currentDate = new Date();
var sendMessage = JSON.stringify({
SendTimestamp: currentDate,
Message: "Message 1",
Browser: navigator.appName
});
receiveReq.send(sendMessage);
}
}
What am I doing wrong? What am I missing in the header to make this CORS request work?
I tried removing the receiveReq.setRequestHeader("Origin", ...) call but then Google Chrome throws an access error on my receiveReq.open() call...
Why?
This is just a guess, as I use jquery for ajax requests, including CORS.
I think the browser is supposed to set the header, not you. If you were able to set the header, that would defeat the purpose of the security feature.
Try the request without setting those headers and see if the browser sets them for you.
In CORS the calling code doesn't have to do any special configuration. Everything should be handled by the browser. It's the server's job to decide if request should be allowed or not. So any time you are making a request which breaks SOP policy, the browser will try to make a CORS request for you (it will add Origin header automatically, and possibly make a preflight request if you are using some unsafe headers/methods/content types). If the server supports CORS it will respond properly and allow/disallow the request by providing CORS specific response headers like
Access-Control-Allow-Origin: *
Keep in mind that Chrome is very restrictive about 'localhost' host name. (At least it was when I was working with it). Instead use your computer name or assign it another alias in 'hosts' file. So for example don't access your site like:
http://localhost:port/myappname
Instead use:
http://mymachinename:port/myappname
or
http://mymachinealias:port/myappname
For more details please check specification.
Are you working cross-domain?
Try Brian S solution or try this:
instead of setting to localhost just pass anything... and see what happens.
receiveReq.setRequestHeader("Origin", "*");

Cross domain javascript ajax request - status 200 OK but no response

Here is my situation:
Im creating a widget that site admins can embed in their site and the data are stored in my server. So the script basically has to make an ajax request to a php file in my server to update the database. Right? Right :)
The ajax request works excellent when i run it in my local server but it does not work when the php file is on my ONLINE server.
This is the code im using:
var url = "http://www.mydomain.net/ajax_php.php";
var params = "com=ins&id=1&mail=mymail#site.net";
http.async = true;
http.open("POST", url, true);
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
//do my things here
alert( http.responseText );
}
}
http.send(params);
In firebug it shows: http://www.mydomain.net/ajax_php.php 200 OK X 600ms.
When i check the ajax responnseText I always get a Status:0
Now my question is: "Can i do cross-domain ajax requests by default? Might this be a cross-domain ajax problem? Since it works when the requested file resides in my local server but DOESN'T work when the requested file is in another server, im thinking ajax requests to another remote server might be denied? Can you help me clear on this?
Thanks..
Cross-domain requests are not directly allowed. However, there is a commonly-used technique called JSONP that will allow you to avoid this restriction through the use of script tags. Basically, you create a callback function with a known name:
function receiveData(data) {
// ...
}
And then your server wraps JSON data in a function call, like this:
receiveData({"the": "data"});
And you "call" the cross-domain server by adding a script tag to your page. jQuery elegantly wraps all of this up in its ajax function.
Another technique that I've had to use at times is cross-document communication through iframes. You can have one window talk to another, even cross-domain, in a restricted manner through postMessage. Note that only recent browsers have this functionality, so that option is not viable in all cases without resorting to hackery.
You're going to need to have your response sent back to your client via a JSONP call.
What you'll need to do is to have your request for data wrapped in a script tag. Your server will respond with your data wrapped in a function call. By downloading the script as an external resource, your browser will execute the script (just like adding a reference to an external JS file like jQuery) and pass the data to a known JS method. Your JS method will then take the data and do whatever you need to do with it.
Lots of steps involved. Using a library like jQuery provides a lot of support for this.
Hope this helps.

Why does running multiple Wicket applications cause AJAX conflicts?

When I open two Wicket web applications in the same browser, it seems there are AJAX conflicts as I see a full page refresh in place of a partial refresh. This is true even if the applications are on different servers and port numbers.
I only use the out-of-the-box JavaScript provided by Wicket (tabbedPanel, onTimerAutoRefresh).
Perhaps it is something related to the fallback function.
When only one web application is open, it works without any problems.
I don't have a problem on the examples site, so I think something is wrong with the configuration of my application.
wicket-ajax.js, line 970:
try {
redirectUrl = t.getResponseHeader('Ajax-Location');
} catch (ignore) { // might happen in older mozilla
}
// the redirect header was set, go to new url
if (typeof(redirectUrl) != "undefined" &&
redirectUrl != null &&
redirectUrl != "") {
//redirect and do a full page refresh (window.location = redirectUrl);
}else{
// do the normal ajax functionality
}
When everything is okay, there is no Ajax-Location in the header. When the second web application is loaded in the same browser, then the next AJAX request on the first loaded web application gets this line in its header:
[Ajax-Location: .]
Can you check that the root context of your applications is different? Otherwise, you could have a conflict at cookie level. They are stored based on the hostname and the path. If the context path of both application is "/", then the cookie values will be overwritten. Whence the conflict that you see.

Resources