I'm trying to make an AJAX call to CouchDB with Qooxdoo, but as far as I can tell no events seem to be firing on my request object (ie. Nothing is appearing on the console and no alerts are coming up). Can anyone tell me what should be happening/what I'm doing wrong?
(This is all in the 'main' method of my class)
var req = new qx.io.remote.Request('http://localhost:5984/japanese/words', 'GET', 'application/json').set({crossDomain:true,timeout:0});
this.debug("Testing");
req.addListener("created", function(e) {
this.debug("Created");
alert(e.getContent());
}, this);
req.addListener("sending", function(e) {
this.debug("Configured");
alert(e.getContent());
}, this);
...
(This is just a sample - I've added a similar listener for all the events I can think of but nothing is coming up on the console)
My server is running Ubuntu 10.10 with Qooxdoo 1.3.
Edit:
Now trying to request "http://localhost/languages/test.php" (my app is at "http://localhost/languages/index.html") and still no alerts are appearing except for the test one I put outside of any event. My request is now: new qx.io.remote.Request('http://localhost/languages/test.php', 'GET', 'application/json'); The PHP file is returning valid JSON when I access it in my browser. Surely this should work?
Cross-domain requests in qooxdoo use a script transport which doesn't fire events. Instead, your server needs to wrap the response data in a call to a static method. See the package documentation of qx.io.remote for details:
http://demo.qooxdoo.org/current/apiviewer/#qx.io.remote
Related
I have a web resource embedded on my CRMform. Its easy to submit the data to CRM but a bit more tricky to populate the web resource (html page) with data from CRM onLoad.
With that being said I have a js file with postMessage as so:
iFrame.contentWindow.postMessage(postObj, 'https://server.xrm.com/crmOrg/WebResources/htmlPageToPostMessageTo');
The following js on another HTML page holds the listener for the postMessage as follows:
$(window).on('message',
function(event) {
// Important. Only accept messages from trusted origins.
if (~event.originalEvent.origin.indexOf('https://server.xrm.com')) {
var messageData = event.originalEvent.data;
//#1
if (messageData.attribute)
{
....do stuff......
}
This behaves very strangely as in sometimes it hits the listener and sometimes it doesn't
In the debugger, it does seem that the following is async:
if `(~event.originalEvent.origin.indexOf('https://server.xrm.com')) {...`
Im fairly certain that there is a timing issue.
Can anybody provide any suggestions?
This is having me and my other dev pull our hair out.
Regards.
It took me sometime to find a workaround, but this seems to fix the issue as you guys have suggested
Promise.resolve(setTimeout(
() => {
iFrame.contentWindow?.postMessage(postObj, 'https://...')
}, 200),
)
-------------------- UPDATE 2 ------------------------
I see now that what I am trying to accomplish is not possible with chrome. But I am still curios, why is the policy set stricter with chrome than for example Firefox? Or is it perhaps that firefox doesn't actually make the call either, but javascript-wise it deems the call failed instead of all together blocked?
---------------- UPDATE 1 ----------------------
The issue indeed seems to be regarding calling http from https-site, this error is produced in the chrome console:
Mixed Content: The page at 'https://login.mysite.com/mp/quickstore1' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://localhost/biztv_local/video/video_check.php?video=253d01cb490c1cbaaa2b7dc031eaa9f5.mov&fullscreen=on'. This request has been blocked; the content must be served over HTTPS.
Then the question is why Firefox allows it, and whether there is a way to make chrome allow it. It has indeed worked fine until just a few months ago.
Original question:
I have some jQuery making an ajax call to http (site making the call is loaded over https).
Moreover, the call from my https site is to a script on the localhost on the clients machine, but the file starts with the
<?php header('Access-Control-Allow-Origin: *'); ?>
So that's fine. Peculiar setup you might say but the client is actually a mediaplayer.
It has always worked fine before, and still works fine in firefox, but since about two months back it isn't working in chrome.
Has there been a revision to policies in chrome regarding this type of call? Or is there an error in my code below that firefox manages to parse but chrome doesn't?
The error only occurs when the file is NOT present on the localhost (ie if a regular web user goes to this site with their own browser, naturally they won't have the file on their localhost, most won't even have a localhost) so one theory might be that since the file isn't there, the Access-Control-Allow-Origin: * is never encountered and therefore the call in its entirety is deemed insecure or not allowed by chrome, therefore it is never completed?
If so, is there an event handler I can attach to my jQuery.ajax method to catch that outcome instead? As of now, complete is never run if the file on localhost isn't there.
before : function( self ) {
var myself = this;
var data = self.slides[self.nextSlide-1].data;
var html = myself.getHtml(data);
$('#module_'+self.moduleId+'-slide_'+self.slideToCreate).html(html);
//This is the fullscreen-always version of the video template
var fullscreen = 'on';
//console.log('runnin beforeSlide method for a video template');
var videoCallStringBase = "http://localhost/biztv_local/video/video_check.php?"; //to call mediaplayers localhost
var videoContent='video='+data['filename_machine']+'&fullscreen='+fullscreen;
var videoCallString = videoCallStringBase + videoContent;
//TODO: works when file video_check.php is found, but if it isn't, it will wait for a video to play. It should skip then as well...
//UPDATE: Isn't this fixed already? Debug once env. is set up
console.log('checking for '+videoCallString);
jQuery.ajax({
url: videoCallString,
success: function(result) {
//...if it isn't, we can't playback the video so skip next slide
if (result != 1) {
console.log('found no video_check on localhost so skip slide '+self.nextSlide);
self.skip();
}
else {
//success, proceed as normal
self.beforeComplete();
}
},
complete: function(xhr, data) {
if (xhr.status != 200) {
//we could not find the check-video file on localhost so skip next slide
console.log('found no video_check on localhost so skip slide '+self.nextSlide);
self.skip();
}
else {
//success, proceed as normal
self.beforeComplete();
}
}, //above would cause a double-slide-skip, I think. Removed for now, that should be trapped by the fail clause anyways.
async: true
});
I have window.unload hooked to save my form data in emergencies when the user just closes their browser. I send this using ajax via POST. This works in IE9, Chrome etc, but not in IE10 where the form data is empty (using GET is a workaround).
I can't find any references to this behaviour, is it documented somewhere?
I assume, you are using code like this:
<html>
...
<body onunload="inOnUnload();">
...
with an inOnUnload()-function being defined like the following:
function inOnUnload() {
xmlhttp.open("POST", "http://some-location", /*async*/ true);
http.send(request);
}
The problem with this in IE10 is that it seems to cancel the request, after the document has finally been unloaded. This happens before the form data had a chance to leaf the client. To send data in onunload events in IE10, you must use the async = false parameter in XMLHttpRequest.open(...).
The following works fine for me:
function inOnUnload() {
xmlhttp.open("POST", "http://some-location", /*async*/ /*!!!*/ false);
http.send(request);
}
I'm having an issue where I have deleted code that called an ajax request & displayed a message box in a grid but it is still showing in the browser.
Someone else tried it and it's showing the change for them.
I am using Eclipse & cleaned, rebuilt, removed/readded & restarted my project. I have also cleared all cache/browser hsitory from my browser & tried removing & readding the file to project. None of which have resolved the issue.
The function is being called from an image hyperlink which is being displayed in the grid. That code has not changed, only the underlying function.
This is the actual code in the file:
function getReport(type, date){
alert(type);
alert(date);
}
This is the code shown in Firebug:
function getReport(type, date){
alert(type);
alert(date);
Ext.Ajax.request({
url: 'cxf/rest/ws/getX',
method: 'POST',
timeout:180000,
params: {Type: type, Date: date},
success: function(){
var grid = Ext.getCmp('oGrid');
grid.getStore().reload();
},
failure: function(){
alert('Unable to retrieve the report. Please contact the System Administrator');
}
});
}
Any ideas why this is happening? I have the same setup as the other person who tried it & this is the first time any JS changes have not appeared.
Did you clear your cache? Is there a proxy cache in play?
Open up firebug and see where the code is on the js files. Add break points and see what is called. Track down the problem.
Use fiddler to see the http requests if needed.
In Firebug, open the Firebug menu (top left, picture of a fiery bug) and select "Deactivate Firebug for this site". This is different in some special way from just closing Firebug, which I see you've already done.
I am trying to use Apple's UIAutomation to write unit tests for an iOS Application that has a server-side component. In order to setup the test server in various states (as well as simulate two clients communicating through my server), I would like to issue HTTP get requests from within my javascript-based test.
Can anyone provide an example of how to either issue HTTP GET requests directly from within UIAutomation javascript tests, or how to invoke a shell script from within my UIAutomation javascript tests?
FWIW, most of the core objects made available by all browsers are missing within the UIAutomation runtime. Try to use XMLHTTPRequest for example and you will get an exception reporting that it cannot find the variable.
Thanks!
Folks,
I was able to work around this by sending HTTP requests to the iOS client to process and return the results in a UIAlertView. Note that all iOS code modifications are wrapped in #if DEBUG conditional compilation directives.
First, setup your client to send out notifications in the event of a device shake. Read this post for more information.
Next, in your iOS main app delegate add this code:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(deviceShakenShowDebug:)
name:#"DeviceShaken"
object:nil];
Then add a method that looks something like this:
- (void) deviceShakenShowDebug:(id)sender
{
if (!self.textFieldEnterDebugArgs)
{
self.textFieldEnterDebugArgs = [[[UITextField alloc] initWithFrame:CGRectMake(0, 0, 260.0, 25.0)] autorelease];
self.textFieldEnterDebugArgs.accessibilityLabel = #"AlertDebugArgsField";
self.textFieldEnterDebugArgs.isAccessibilityElement = YES;
[self.textFieldEnterDebugArgs setBackgroundColor:[UIColor whiteColor]];
[self.tabBarController.selectedViewController.view addSubview:self.textFieldEnterDebugArgs];
[self.tabBarController.selectedViewController.view bringSubviewToFront:self.textFieldEnterDebugArgs];
}
else
{
if ([self.textFieldEnterDebugArgs.text length] > 0)
{
if ([self.textFieldEnterDebugArgs.text hasPrefix:#"http://"])
{
[self doDebugHttpRequest:self.textFieldEnterDebugArgs.text];
}
}
}
}
- (void)requestDidFinishLoad:(TTURLRequest*)request
{
NSString *response = [[[NSString alloc] initWithData:((TTURLDataResponse*)request.response).data
encoding:NSUTF8StringEncoding] autorelease];
UIAlertView *resultAlert =
[[[UIAlertView alloc] initWithTitle:NSLocalizedString(#"Request Loaded",#"")
message:response
delegate:nil
cancelButtonTitle:NSLocalizedString(#"OK",#"")
otherButtonTitles:nil] autorelease];
resultAlert.accessibilityLabel = #"AlertDebugResult";
[resultAlert show];
}
This code will add a UITextField to the very top view controller after a shake, slapped right above any navigation bar or other UI element. UIAutomation, or you the user, can manually enter a URL into this UITextField. When you shake the device again, if the text begins with "http" it will issue an HTTP request in code (exercise for the reader to implement doDebugHttpRequest).
Then, in my UIAutomation JavaScript file, I have defined the following two functions:
function httpGet(url, delayInSec) {
if (!delayInSec) delay = 1;
var alertDebugResultSeen = false;
var httpResponseValue = null;
UIATarget.onAlert = function onAlert(alert) {
httpResponseValue = alert.staticTexts().toArray()[1].name();
alert.buttons()[0].tap();
alertDebugResultSeen = true;
}
var target = UIATarget.localTarget();
var application = target.frontMostApp();
target.shake(); // bring up the input field
application.mainWindow().textFields()["AlertDebugArgsField"].setValue(url);
target.shake(); // send back to be processed
target.delay(delayInSec);
assertTrue(alertDebugResultSeen);
return httpResponseValue;
}
function httpGetJSON(url, delayInSec) {
var response = httpGet(url, delayInSec);
return eval('(' + response + ')');
}
Now, in my javascript file, I can call
httpGet('http://localhost:3000/do_something')
and it will execute an HTTP request. If I want JSON data back from the server, I call
var jsonResponse = httpGetJSON('http://localhost:3000/do_something')
If I know it is going to be a long-running call, I call
var jsonResponse = httpGetJSON('http://localhost:3000/do_something', 10 /* timeout */)
I've been using this approach successfully now for several weeks.
Try performTaskWithPathArgumentsTimeout
UIATarget.host().performTaskWithPathArgumentsTimeout("/usr/bin/curl", "http://google.com", 30);
Just a small correction. The answer that suggests using UIATarget.host().performTaskWithPathArgumentsTimeout is an easy way to make a request on a URL in iOS 5.0+, but the syntax of the example is incorrect. Here is the correct way to make this call:
UIATarget.host().performTaskWithPathArgumentsTimeout("/usr/bin/curl", ["http://google.com"], 30);
The "[" around the "args" param is important, and the test will die with an exception similar to the following if you forget the brackets:
Error: -[__NSCFString count]: unrecognized selector sent to instance
Here is a fully working example that hits google.com and logs all the output:
var result = UIATarget.host().performTaskWithPathArgumentsTimeout("/usr/bin/curl", ["http://www.google.com"], 30);
UIALogger.logDebug("exitCode: " + result.exitCode);
UIALogger.logDebug("stdout: " + result.stdout);
UIALogger.logDebug("stderr: " + result.stderr);
+1 for creative use of "shake()". However, that's not an option for some projects, especially those that actually use the shake feature.
Think outside the box. Do the fetching with something else (Python, Ruby, node.js, bash+wget, etc). Then, you can use the pre-canned response and auto-generate the ui-test.js on the fly by including that dynamically generated json payload as the "sample data" into the test. Then you simply execute the test.
In my opinion, the test is the test, leave that alone. The test data you are using, if it's that dynamic, it ought to be separated from the test itself. By doing it this way of fetching / generating JSON, and referencing it from the test, you can update that JSON however often you like, either immediately right before every test, or on a set interval like when you know the server has been updated. I'm not sure you would want to generate it while the test is running, that seems like it would create problems. Taking it to the next level, you could get fancy and use functions that calculate what values ought to be based on other values, and expose them as "dynamic properties" of the data, rather than that math being inside the test, but at that point I think the discussion is more of an academic one rather than the practical one of how.
Apple has recently updated UIAutomation to include a new UIAHost element for performing a task on the Host that is running the instance of Instruments that is executing the tests.