Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Hannah Stahl
Hannah Stahl
991 Points

How to open AJAX response in new window

Hi, I am currently working on an HTML/JavaScript/Python project. I am creating a web dashboard that has a list of options and, when you click on an option, an AJAX request is submitted to a Python CGI file that sends an HTML template back. As of now, I am displaying this HTML template in the current window. However, I would like to keep what I have in the current window and open this new HTML template in a different tab. I have an HTML file written out for this new page, with a title, style, etc. I want to put my new HTML code into the body of this page, instead of the body of the current page. The code I have written to try to do this is:

var w = window.open(http://localhost/newpage.html);
$(w.document).open();
$(w.document.body).html(response);
$(w.document).close();

However, it is not adding my response (the new HTML code) into the body of the new web page. It isn't throwing an error; it just simply isn't showing my new code. I've searched the Internet but cannot figure out the problem. Please help!!

2 Answers

Dave McFarland
STAFF
Dave McFarland
Treehouse Teacher

Hi Hannah Stahl,

Are you adding this code as part of the AJAX callback function? It has to go in the callback, because you need to wait for the response to come back from the server, before you can add the HTML to the new window.

Hannah Stahl
Hannah Stahl
991 Points

Yes, sorry--it is in the callback function. I have successfully gotten the callback to generate an HTML page in the current page, but now I'm trying to change it to get it to open the page in a new window. Thanks for any help!

Dave McFarland
STAFF
Dave McFarland
Treehouse Teacher

Hi Hannah Stahl

Try it without specifying a page -- also there are no close() or open() functions in jQuery:

var w = window.open();
$(w.document.body).html(response);
Hannah Stahl
Hannah Stahl
991 Points

This didn't work either unfortunately--it just opened up a new blank web page. I ended up, in my Python CGI file, just writing to an HTML file, and then, in the AJAX callback, opening that file in the web browser. This method seems to work just fine. I'm not sure why the other code didn't work for me, but oh well. Thank you for your help!