I have the following function which I use to render partial views in my app. Yet it is not filling the element I pass it with any content.
function RenderPartialView(view, contentcontainer, maskcontainer, params) {
$.get(view, params, function (data) {
$("#" + contentcontainer).html(data);
$(maskcontainer).unmask();
})
}
I call this function from various methods with in my app and as of now have had no trouble with it. At the moment though, I'm prepending a div to the page and then calling this function from a method like so in order to fill the div with the html data from RenderPartialView.
loadExpandedDashboard: function () {
RenderPartialView('../Metrics/ExpandedDashboard', 'expanded-view', '#expanded-view');
}
everything works fine in all other browsers, in IE8 I do not get any console errors and when running basic error checking callbacks everything is clean. If I log the 'data' returned from the $.get() it shows the full length html that I am requesting from my own server. Because of this I'm completely lost on what could be the cause, Any ideas would be greatly appreciated. Thanks!
My guess would be that there is something in the returned HTML - missing or out of order tags, etc. - that IE is having trouble with. IE is known for being picky about the markup it accepts when in the html() method, whereas other browsers are more lenient.
Strangely, setting the innerHTML property directly sometimes works when jQuery's html() function does not.
Related
I recently read about the solution for these protractor issues:
Unable to easily pass context to addMockModule #695
feat(addMockModule): add third parameter to pass context #787
I have been eager to DRY up my protractor tests and this was the solution I needed. This solution is working great with ChromeDriver, but with FirefoxDriver it's oddly broken. Here's my code (in a beforeEach() block:
var httpBackendMock = function() {
angular.module('httpBackendMock', ['ngMockE2E'])
.value('mockData', arguments[0])
.run(function ($httpBackend, mockData) {
$httpBackend.whenGET(/.*aggregates/)
.respond(200, mockData.testAggregates);
$httpBackend.whenGET(/.*merchants\/123456/)
.respond(200, mockData.testMerchant);
});
};
browser.addMockModule('httpBackendMock', httpBackendMock, {
testAggregates: testAggregates,
testMerchant: testMerchant
});
(testAggregates and testMerchant are defined previously.)
This works perfectly in Chrome, but in Firefox when the whenGET expectations fire they return no data. It fails whether I use the mockData object or directly use arguments[0].
But it gets weirder. If I try to inspect the mockData module value I created above in a later browser.executeScript() call, the data is there, and console.log renders it the same way in both Chrome and Firefox.
browser.get('index.html#/experiments');
browser.executeScript(function() {
return angular.injector(["httpBackendMock"]).get('mockData');
}).then(function(data) {
console.log("DATA", data);
});
When the test runs the data shows up as expected.
The only workaround for this I have found is to JSON.stringify() the input to addMockModule() and JSON.parse() it inside. It seems to work, but is ugly - the framework should already be taking care of it.
So I think this is a bug, but I'm really not sure which component this is a bug in.
I'm using jQuery's $.when() to handle multiple $.get() requests. This is how I have it set up.
var request1 = $.get('myURL');
var request2 = $.get('mySecondURL');
$.when(request1, request2).done(go);
function go(request1, request2){
console.log(request1);
console.log(request2);
}
Everything works great. Chrome's console shows
[#document, "success", Object]
I know that #document is what I need to read, but what is the syntax to get it? Every example I've seen uses anonymous functions, which I'm not use to and bug me, coming from OOP AS3.
I've tried console.log(request1[0]); which works, but there has to be a more proper way. Something like request1.data or $(request1).$('#document');
Like I said, I'm a heavy Flex developer coming into JS and jQuery so the syntax I'm still trying to pickup.
According to the documentation for $.when, request1[2] has the jqXHR object, which in turn has responseText member. If you use console.log in Chrome at least, you can see the contents of the jqXHR to find what member you specifically want to access, but it's probably responseText.
Create a jQuery object and use it like you would use one created from a selector: $(request1)
For example, $(request1).appendTo('#out') would append the newly loaded content to an element with id="out".
I was wondering how I can get a function from an AJAX request, like this:
Let's say I have a file called myfunction.js, that looks like this:
function(bar){
alert(bar);
}
Can I retrieve it via Ajax as a function, like this?
var foo = $.ajax({url:'myfunction.js',async:false}).responseText;
And run it like this?
foo(bar);
The reason I ask is because I know responseText is a string,
so I'm not really sure if JavaScript will understand that it is a function.
Is there a way to convert a string into a function?
In your JS file, give the function a name.
function foo(bar){
alert(bar);
}
Then use $.getScript to load it.
$.getScript('myfunction.js', function(){
foo('test');
});
Absolutely:
foo = eval('(' + foo + ')');
foo(bar);
You could use new Function but in my testing it doesn't work on some versions of IE.
I ended up using new Function instead of eval, eval executes the code as soon as it's parsed, which is not what I was after.
This is what I ended up doing, and it works very nicely in firefox, chrome, and IE 7+ (no errors at all)
function createMyFunction(code){return new Function('params',code)};
var thecode = $.ajax({
url: 'myCode.js',
async: false,
dataType: 'html'
}).responseText
myFunction = createMyFunction(thecode);
I know the createMyFunction is pretty lazy in terms of not being able to define different arguments, but using a single params map works for my templating scenario quite well.
Note the dataType:'html' in the ajax request, if you don't specify a plain text mime type, jQuery will actually recognize that you are getting JS code and try to parse it, which generally ends up throwing a parse error or sometimes "Uncaught TypeError: params is not defined".
With this, I am able to have template files that specify template-specific events, and keep them organized in the same way as the markup and css files for that template.
Thanks for the help everyone, the reason I chose the answer that I did is because the link at the end pointed me in the right direction.
Cheers,
D
One thing to beware.
Chrome and IE don't allow you to eval an anonymous function directly (FF is fine). That is
// Throws Syntax Error in Chrome, Object expected in IE 8
var fun = eval('function(){return 5}'); fun();
A hackaround is to put it in an array, doesn't seem very reliable for the future:
var fun = eval('[function (){return 5}][0]'); fun();
The only safe way would be to make sure your functions are named, since the following works fine in all browsers:
eval('function a(){return 5}]'); a(0);
See Are eval() and new Function() the same thing? for further discussion
When using third-party plugins, I typically initialize them in my main application.js file.
Example:
$('.scroll').jScrollPane();
The problem is if a page loads that doesn't have the scroll class, then I get:
TypeError: Result of expression '$('.scroll').jScrollPane' [undefined] is not a function.
So to get around this, I wrap it in:
if ($(".scroll").length){
$('.scroll').jScrollPane();
}
That remedies the problem but just seems like a hack.
Is there a "correct" way to solve this?
If you're getting:
ScrollPane' [undefined] is not a function.
...it wouldn't be because the page doesn't have a .scroll element.
That sort of error occurs when the plugin (or jQuery itself) isn't loaded.
If you're reusing some code on several pages, some of which don't have that plugin, do this instead:
if ( $.fn.jScrollPane ){
$('.scroll').jScrollPane();
}
you can use try/catch blocks...
try
{
$('.scroll').jScrollPane();
}
catch(err)
{
//Handle or ignore errors here
}
Uhh ... no; jQuery doesn't work like that. A call to $("any selector") will always give you back a ready-to-use (but empty) jQuery object. I don't think that's really your problem. Can you describe more about what your page is doing?
if ($('.scroll').jScrollPane()){
$('.scroll').jScrollPane();
}
this error is prob just because an addon failed loading
As a couple others have said, that error is the jScroll's error. If it's because an element doesnt exist jQuery will return an empty array.
Its because the plugin isn't loaded. jScroll is the plugin to change the scrollbars, correct? I've had numerous issues with it. I suggest wrapping it in a
$(window).load(function(){
//Call it here
})
This fixed all the issues i had with it.
I'm using jQuery 1.3.2 and it's breaking under Safari 4 for mysterious reasons.
All of my javascript references are made right before the tag, yet with the following code:
var status = $('#status');
status.change( function(){ /* ... */ } );
The following error is displayed in the Web Inspector:
TypeError: Result of expression 'status.change' [undefined] is not a function.
However the error is not encountered if I eliminate the variable assignment attach the change method directly like so:
$('#status').change( function(){ /* ... */ } );
Why? I need to use variables for this and several other findById references because they're used many times in the script and crawling the DOM for each element every time is regarded as bad practice. It shouldn't be failing to find the element, as the javascript is loaded after everything except and .
Try changing the variable to something other than "status."
It's confusing your variable with window.status (the status bar text). When I typed var status = $('#status') into the debugging console, the statusbar changed to [Object object]. Must be a bug in Safari.
If you put the code inside a function, so that status becomes a function-local variable, it should work.
It's standard practice in jQuery to wrap things in a
$.onready(function() {
});
This makes sure the DOM is loaded before you try to manipulate it.