Is it possible to use jQuery on a new window? - javascript

I've been trying to solve this problem for hours now maybe anyone of you could help me.
Right now my Code looks like this:
$('.clickable').on('click', function() {
var id = $(this).attr('data-packages');
id = "'" + id + "'";
$.ajax({
url: "show.php",
data: {
type: "showSFM",
data: id,
user: username
},
type: "POST",
success: function(data) {
$('#main').html(data);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Everything is working fine but I was asking myself If it is possible to use $('#main').html(data) on a new Window. Right now if I click an Element the current window is showing the result but I want a new tab to pop up with the result.
I was trying things like this:
success: function(data) {
var url = location.href;
var window = window.open(url);
window.document.getElementById('main').innerHTML = data;
}
The result I'm getting is that the window opens on the main page. Looks like window.open(url) works just fine but the line below does nothing.

The reason this likely doesn't work is due to the fact that you use:
window.document.getElementById('main')
The window might already be opened by the line before, but is most likely not loaded and doesn't contain an element with id main yet (since making a HTTP(S) request takes time). This could be solved by moving the filling of main element into a callback.
window.addEventListener('load', function () {
window.document.getElementById('main').innerHTML = data;
}, { once: true });

You can send the data you need for the request in the URL and then on the new page, you can send the AJAX request again, and getting the data you need for it from the URL.

Related

AJAX Post HTML Code

I'm having an issue with sending some HTML code using AJAX please see my code below
<iframe src="http://www.w3schools.com" width="10" height="10" id="awc_frame"></iframe>
<script>var iframe = document.getElementById("awc_frame");</script>
Here is the AJAX code below
<script>
$.ajax({
type: "POST",
url: "mobileView.php",
data: { val : iframe },
success: function(data){
console.log(data);
}
})
</script>
The code isn't sending the variable to the PHP file. Looking into the Network side of things it sends text ie if I put "" around iframe it sends this code
"val = iframe" but not the actual code within the iframe. The "var iframe"does work and pulls back the HTML code of the iframe
Please tell me what I'm doing wrongly.
Thanks in advance.
EDIT: I'm sorry. It's not the HTML code within the iFrame I need to send, It's the entire iFrame code I need to send.
Another Edit: What I'm trying to accomplish when a visitor from my company goes to my website I would like Javascript or Jquery to load an internal website from the visitors computer and then have all of the code from that website that's on the client's end to be sent to a Server which will store the entire iFrame code in a database.
This would send the entire html inside the iframe.
var iframe = $('#awc_frame').html();
First of all, var iframe does not contain HTML of the iframe element - it contains a DOM Node, which is kind of a wrapper around the iframe element (it contains various properties of that element, including the HTML).
Next thing, you probably want to wait for the iframe to completely load all the contents, so you'll have to bind to the load event of it.
Something like this should work:
var $iframe = $("#awc_frame");
$iframe.on("load", function () {
var iframeHTML = $iframe[0].contentWindow.document.body.innerHTML;
// jQuery alternative
var iframeHTML = $iframe.contents().find("body").html();
$.ajax({
type: "POST",
url: "mobileView.php",
data: {
val: iframeHTML
},
success: function(data){
console.log(data);
}
});
});
Super important thing in this example
Just one more thing - please note that for websites outside of your own domain, this code won't work (due to Same Origin Policy). Any other code won't work too.
Since javascript has problems with getting the HTML from a cross-domain iframe, you can't do this across domains. However, why not just send the iframe's src attribute to the PHP page, and then just use file_get_contents to get the HTML, and then store that? Problem solved:
Javascript:
var iframe = $('#awc_frame').prop('src');
$.ajax({
type: "POST",
url: "posttest.php",
data: { val : iframe },
success: function(data){
console.log(data);
}
});
PHP:
$html = file_get_contents($_POST['val']);
what are you trying to do?
var iframe = document.getElementById("awc_frame");
above code is an javascript object of your iframe which contains a lot of properties.. since you are using jQuery, you could get that with:
var iframe = $('#awc_frame');
keep in mind that above code is the element it self in jquery object format you could get element object like this:
var iframe = $('#awc_frame')[0];
** you're doing something wrong.
if you're trying to get iframe HTML content:
var iframe_contents = $("#awc_frame").contents();
if you explain more about what you are trying to do, i can update my answer to suit you.
* UPDATE *
considering what you are trying to do..
Method #1: (Easy Way)
you could use php to fetch content of the website you need:
<?php
$contents = file_get_contents('http://www.w3schools.com');
// Saving $contents to database...
?>
Method #2: (Hard Way)
as #mdziekon said, you first should wait until your iframe gets loaded then:
var iframe = $("#awc_frame");
iframe.on("load", function () {
var contents = $(this)[0].innerHTML;
$.ajax({
type: "POST",
url: "mobileView.php",
data: {
val: contents
},
success: function(data){
console.log(data);
}
});
});
hope it solves your problem

Dynamic script loading works first time but not thereafter

I have contact page on my website where I have various social network links (plus an e-mail form) with links at the side to select each one. Clicking a link makes an ajax request to the server, and on success replaces the html of a common div with the response.
Each one has a javascript file associated with it, and this is added as a script tag in the document head on ajax success.
These scripts should evaluate on each load and prepare the DOM in the response. However, I am finding that the first click works perfectly, the script is loaded and executes, but when I go to click on another link, it loads the new script but it never seems to execute. And none of those dynamically loaded scripts work thereafter.
The ajax call for loading each option is bound to each link's click event here:
$('.socialLink').click(function() {
var id = $(this).prop('id').toLowerCase();
var callingObj = $(this);
$.ajax({
url: "./socialMedia/" + id + ".php",
success: function(msg) {
$('.socialLink').css('opacity', '0.4');
$('.socialLink').data('active', false);
callingObj.css('opacity', '0.9');
callingObj.data('active', true);
if ($('#Feed').css('display') !== 'none') {
$('#Feed').slideToggle(400, function() {
$('#Feed').html(msg);
});
}
else
{
$('#Feed').html(msg);
}
$('#Feed').slideToggle(400);
$.getScript('./script/' + id + '.js');
}
});
});
The thing is, I dynamically load scripts for each page on the site, too... and don't seem to have any problems with that.
You can see the page I am talking about if you go here http://www.luketimoth.me/contact.me. Only two options actually load any javascript at the moment, the e-mail and twitter ones... the rest are empty js files with only a single comment inside.
EDIT: I am now using jQuery getScript()... I have changed the code above to reflect this. The scripts I am trying to load, which are not working as exepcted, are:
twitter.js (just the standard code twitter gives you for one of their widgets):
!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+"://platform.twitter.com/widgets.
js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");
email.js:
$('#Send').click(function() {
var senderName = $('#YourName').val();
var senderEmail = $('#Email').val();
var emailSubject = $('#Subject').val();
var emailBody = $('#EmailBody').val();
$.ajax({
url:'./script/sendMail.php',
data: {
name: senderName,
email: senderEmail,
subject: emailSubject,
body: emailBody
},
type: "POST",
success: function(msg) {
$('#success').html(msg);
}
});
});
$('input, textarea').focus(function() {
if (this.value === this.defaultValue) {
this.value = '';
}
});
$('input, textarea').focusout(function() {
if (!this.value.length) {
this.value = this.defaultValue;
}
});
Thanks for all the comments and suggestions. I decided in the end to load everything in the background rather than make an ajax request every single time.
It's actually a much more responsive page now... admittedly at the cost of having unused DOM elements in the background. Given how much faster it is, though, I think the trade-off is acceptable.

Jquery script works only after opening new window in IE

The script below queries a PHP service that returns a JSON response. Buttons are created for each returned record, allowing the user to delete that record from the database. A link is also created below to refresh the data.
This all works fine in IE, Chrome, Safari...IE (tried 8 & 9), however, is having a strange issue.
When the page loads, I am able to refresh the data by clicking the 'refresh' link. After this, clicking has no effect UNLESS I open the same page in a different IE window, click the link in the new window, and return to the original window. The 'refresh' link then works on the new window ONE time. It then turns into a vicous cycle.
Your help is appreciated!
function getNew(){
$('#new').remove();
$.getJSON('service.php', function(data) {
var items = [];
items.push('<tr><th>EmplId</th><th>ExternalID</th><th>Name</th></tr>');
$.each(data, function(key, val) {
var indiv = val.toString().split(",");
items.push('<tr>');
var id = indiv[0];
$.each(indiv, function(index, value) {
items.push('<td align="center" id="' + index + '">' + value + '</td>');
});
items.push('<td class="updateButton" align="center" onclick=\'return update("'+id+'")\'>Update</td>');
});
items.push('<tr><td class="refreshButton" align="center" onclick=\'return getNew();\'>Refresh </td></tr>');
$('<table/>', {
'id': 'new',
html: items.join('')
}).appendTo('body');
});
}
function update (emplID){
$.ajax({
url: "service.php?emplID="+emplID,
context: document.body,
success: function(){
$('#new').remove();
getNew();
}
});
}
I have tried using .live and I get the same results.
$(".refreshButton").live("click" , function() {
getNew();
$.ajax({
url: "Service.php?emplID=",
context: document.body,
success: function(){
$('#new').remove();
getNew(); }
});
});
I have disabled the cache still to no avail. The ONLY way to make the link work is to open the same page in a separate window, click the link, and return to the original window. Is there any solution to this?
$(".refreshButton").live( "click" , function() {
getNewStudents();
$.ajax({
url: "studentService.php?emplID=",
cache: false,
context: document.body,
success: function(){
$('#newStudents').remove();
getNewStudents();
}
});
});
Thanks for your suggestions. I fixed the tr, but it seems that the solution was to use
$.ajaxSetup({ cache: false });
It seems all versions of IE treat ajax calls as normal web requests (cacheable), whereas other browsers consider ajax calls as non-cacheable.
Learned something new today, thanks guys!
Maybe it's because of cache, have you tried to clear your cache and try again? this may help http://kb.iu.edu/data/ahic.html#ie8
Perhaps IE is choking on the malformed HTML that getNew is generating; note that in your .each loop, you are not closing the tr element. Also, if you're getting a JavaScript error, JS execution may stop, so make sure your browser isn't configured such that it ignores JS errors. Check the error console.

jQuery selectors on an ajax response string that is a full html page

I'm trying to get some page details (page title, images on the page, etc.) of an arbitrarily entered URL/page. I have a back-end proxy script that I use via an ajax GET in order to return the full HTML of the remote page. Once I get the ajax response back, I'm trying to run several jQuery selectors on it to extract the page details. Here's the general idea:
$.ajax({
type: "GET",
url: base_url + "/Services/Proxy.aspx?url=" + url,
success: function (data) {
//data is now the full html string contained at the url
//generally works for images
var potential_images = $("img", data);
//doesn't seem to work even if there is a title in the HTML string
var name = $(data).filter("title").first().text();
var description = $(data).filter("meta[name='description']").attr("content");
}
});
Sometimes using $("selector", data) seems to work while other times $(data).filter("selector") seems to work. Sometimes, neither works. When I just inspect the contents of $(data), it seems that some nodes make it through, but some just disappear. Does anyone know a consistent way to run selectors on a full HTML string?
Your question is kind of vague, especially w/r/t what input causes what code to fail, and how. It could be malformed HTML that's mucking things up - but I can only guess.
That said, your best bet is to work with $(data) rather than data:
$.ajax({
type: "GET",
url: base_url + "/Services/Proxy.aspx?url=" + url,
success: function(data) {
var $data = $(data);
//data is now the full html string contained at the url
//generally works for images
var potential_images = $("img", $data);
//doesn't seem to work even if there is a title in the HTML string
var name = $data.filter("title").first().text();
var description = $data.filter("meta[name='description']").attr("content");
}
});

JQuery Treeview not working with Ajax

I'm new to JQuery and web development in general. I'm trying to load some data from an XML file and build an unordered list. I've got that part working, now I'm trying to use the TreeView plugin so I can collapse/expand the data. The data is loaded like this:
$(document).ready(function(){
$.ajax({
type: "GET",
url: "solutions.xml",
dataType: ($.browser.msie) ? "text" : "xml",
success: function(data) {
var xml;
if (typeof data == "string") {
// Work around IE6 lameness
xml = new ActiveXObject("Microsoft.XMLDOM");
xml.async = false;
xml.loadXML(data);
} else {
xml = data;
}
list = ""
$(xml).find("Group").each(function() {
group = $(this).attr("name");
list += "<li><span>" + group + "</span><ul>";
$(this).find("Solution").each(function() {
solution = $(this).attr("name");
list += "<li><span>" + solution + "</span></li>";
});
list += "</ul></li>";
});
$("#groups").html(list);
},
error: function(x) {
alert("Error processing solutions.xml.");
}
});
$("#groups").treeview({
toggle: function() {
console.log("%s was toggled.", $(this).find(">span").text());
}
});
});
and the HTML looks like this:
<html>
...
<body>
<ul id="groups">
</ul>
</body>
</html>
The unordered list shows correctly, but the little [+] and [-] signs don't show up and the sections aren't collapsible/expandable. If I get rid of my Ajax loading and insert an unordered list inside of #groups manually it works as expected.
What am I doing wrong? Is there any other plugins or Javascript libs that could make this easier? The solution needs to work on IE6 locally (i.e. webserver).
Update: I found a work-around: If I define my treeview stuff like this it works:
function makeTreeview() {
$("#container").treeview({
toggle: function() {
console.log("%s was toggled.", $(this).find(">span").text());
}
});
}
setTimeout('makeTreeview();', 50);
I think the problem is, when I create the treeview, the ajax stuff hasn't done it's work yet, so when treeview() is called, the unordered list hasn't been created yet. I haven't tested this with IE6 yet. Is there a nicer way to do this, without using SetTimeout()?
I made the same type of call for another project.
For other reasons you will probably want to wrap your ajax call in an anonymous function to create a closure so that your variables remain what you expect them to...
The success method is a callback function that happens after your call is complete , just create your treeview inside that method, or break it out into a seperate fumction if you need to for clarity.
in the example that you show - your treeview will still fail if the ajax call takes longer than 50ms - which could easily happen during initial load if more than two objects are being loaded from that same server.
This example used JSON, and concurrently loaded html data from a page method into a series of divs.
$(document).ready(function() {
for (i= 1;i<=4;i++)
{
(function (){
var divname ="#queuediv"+i;
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "test12.aspx/GetHtmlTest",
data: "{}",
error: function(xhr, status, error) {
alert("AJAX Error!");
},
success: function(msg) {
$(divname).removeClass('isequeue_updating');
$(divname).html(msg);
$("#somethingfromthemsg").treeview();
}
});
})();
}
});
Hope that helps!
You need to get FireBug (Firefox add-in) and then you can see in the console what is being returned, and make sure it matches what you expect (And that it is actually doing the request..).
Once you get it working in FF, you can support the ancient 10-year old IE6 browser.
There's also some other things you may want to consider:
The whole ActiveXObject("Microsoft.XMLDOM") jumps out as me as unnecessary. If you pass XML in a string to $(), jQuery turns it into a DOM object.
Additionally, .Find can be replaced by:
$('Element', this);
So for example:
var xmlDoc = '<Group><Solution name="foo" /><Solution name="bar" /></Group>';
$('Solution', xmlDoc).each(function() {
document.write( $(this).attr('name') );
});
would spit out:
foo
bar
Also, with firebug, stick a console.log(list); at the end, to be sure you're generating the HTML you think you are. If you're really stuck in IE6, alert(list) somewhat works as a poor man's equivalent (as long as your file isn't too big).
In short, I think you're on the right track, you just need the tools to debug properly.
For anyone who also finds their way to this post. I had this trouble with an ajax call.
If you want to wait for the ajax call to be returned, you need to set async as false.
$.ajax({
type: 'POST',
async: false,
........

Categories