Reputation: 340
I've got html structure like this:
<div id="things">
<div class="whatever">
<div class="frame">content</div>
<div class="frame">content</div>
<div class="frame">content</div>
</div>
</div>
And I got JS with JQuery script that works on click on button on that page:
function intsaver(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "intsaver.php", true);
var tosf = $('<div></div>');
$("#things").find(".frame").each(function(){
tosf.append($(this).innerHTML);
alert(''+tosf);
});
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("data=" + tosf.innerHTML);
}
I can see this
contents in debugger, they are exactly what I'm looking for. But tosf
remains undefined
and on server side I recieve undefined
.
I've tried some ways, for examle, I appended this
itself. As result, div's disappeared from page, but tosf
remained undefined
.
I believe I've made some obvious mistake.
Upvotes: 5
Views: 6340
Reputation: 576
A bit more explanation 'why .innerHTML
' did not work.
As it is stated in the answers, $(this).innerHTML
would not work as jQuery does not have that property. But if you tweak your code you can benefit from .innerHTML
as well. If you wrap an element with $(element)
it creates jQuery specific object and you will need to get the element from it if you want to use .innerHTML
like: $(this)[0].innerHTML
. As the this
is only element in that jQuery array, this.innerHTML
will be sufficient, without making $(this)
. so your code can be:
function intsaver(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "intsaver.php", true);
var tosf = $('<div></div>');
$("#things").find(".frame").each(function(){
tosf.append(this.innerHTML);
alert(''+tosf);
});
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("data=" + tosf[0].innerHTML);}
Upvotes: 2
Reputation: 2111
Change
tosf.append($(this).innerHTML);
To
tosf.append($(this).html());//$(this) a jQuery object
Or
tosf.append(this.innerHTML);//this a dom object
$(this)
is a jQuery object
not a dom object
which doesn't have property innerHTML
.Use .html()
instead.
Upvotes: 4
Reputation: 8488
$(this).innerHTML
should be $(this).html();
and tosf.innerHTML
should be tosf.html()
Reason is tosf
and $(this)
are jQuery style and innerHTML
is pure javascript.
Upvotes: 2
Reputation: 388316
Try
function intsaver() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "intsaver.php", true);
var tosf = $('<div></div>');
$("#things").find(".frame").each(function () {
tosf.append(this.innerHTML); //innerHTML is a property dom element
alert('' + tosf);
});
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("data=" + tosf.html()); //tosf is a jQuery object os call .html()
}
Upvotes: 2