Get jQuery object from HTML string - javascript

I have an AJAX request that grabs the source of Wikipedia pages:
$.ajax({
url: "TrollWikipedia.ashx",
data: {
url: "http://en.wikipedia.org/wiki/20s",
},
type: "GET",
success: function (html) {
var page = $(html);
alert(page.find("#content").length); //Alerts 0
alert(page.html()); //alerts null
}
});
It successfully returns the source of the page (I have a copy of the string it returns here on jsFiddle).
The problem: I can't seem to make a jQuery object from the HTML (like they do here). For some reason, it doesn't seem to be creating the object correctly. What am I doing wrong?

html data seems to be badly parsed (maybe a closing div tag is missing in the html code), use:
$.ajax({
url: "TrollWikipedia.ashx",
data: {
url: "http://en.wikipedia.org/wiki/20s",
},
type: "GET",
datatype: "html",
success: function (html) {
html=html.replace(/(<body [^>]*>)/i, '$1<div>').replace(/(<\/body>)/i, '</div>$1');
var page = $(html);
alert($("#content",page).length); //Alerts 1
alert(page.html()); //alerts html
}
});

html string contains the links pointing to en.wikipedia.org site, so when we do $(html) jQuery might be getting exception due to cross domain script calls inside the html markup due to which you are not getting any thing after $(html)

Related

Javascripts in dynamic loaded div not working (JSON)

This might be duplicate - but in all other soloutions I can't seem to find any usefull information for my purpose.
I have this script parsing data to a .php file which generate content from a database query.
The .php file returns the generated HTML content as JSON - And this generated content includes som JS (some contextMenu functions to run when clicked on certain DIV's inside the loaded content).
These functions does not work in the loaded content.
From my main site I run:
$('.part_click').on('click', function(){
var data_id = $(this).attr('id');
$.ajax({
url: 'explode_machine.php',
type: 'POST',
data: {id: data_id, machineid: '<?php echo $machineid;?>'},
dataType: 'json',
success: function(data){
$('#explode').html(data.html);
}
});
});
And the .php returns (among many things):
$('#clickedDiv').contextMenu('#menu-Div',{triggerOn:'contextmenu'});
#clickedDiv and #menu-Div is just fancy names used here as the actual names and numbers of id's may vary depending on the database query.
The .js file including the contextMenu function is loaded in the top of my main site.
If i right click on the #clickedDiv inside the dynamic loaded content nothing happens - If I add the same function to content outside the dynamic loaded content everything works as aspected.
As far as I understand from other topics the problem is either in the JSON parsing or in the .html() - but I'm not able to sort it out.
Assuming the #clickedDiv element is added by your AJAX success handler, you need to initialise that plugin after the element is placed in the DOM. Try this:
$('.part_click').on('click', function(){
var data_id = $(this).attr('id');
$.ajax({
url: 'explode_machine.php',
type: 'POST',
data: {
id: data_id,
machineid: '<?php echo $machineid;?>'
},
dataType: 'json',
success: function(data){
$('#explode').html(data.html);
// initialise the plugin here:
$('#clickedDiv').contextMenu('#menu-Div', {
triggerOn: 'contextmenu'
});
}
});
});

DOM not updating, jquery selectors not detecting dynamic elements for further processing

I am adding table into my html using ajax call
$.ajax({
url: "/getdata",
type: "POST",
data: {data : jsonString},
success: function( resp ){
//console.log(resp);
$('div.table-responsive').html(resp);
}
});
I am able to get table at right place in broswer view. However when i run in separate script tag
console.log("Tables found"+$('table').length)
i get 0 in output.
How do I update dom after adding elements dynamically so that i can further process them.
I read many answers on this question, everyone is talking about assigning events to these dynamically added elements however I just need to add some classes to some of these tags so my css and javascript can process them.
Your table manipulations should be in the callback :
$.ajax({
url: "/getdata",
type: "POST",
data: {
data: jsonString
},
success: function (resp) {
//console.log(resp);
$('div.table-responsive').html(resp);
console.log('table length: ' + $('.table-responsive table').length);
// Do something with the tables here
}
});
Since this is async, you're gonna need an event or callback. Try something like this:
$('table').contentChange( function(){
// do something
console.log('table length: '+this.length);
});

Retrieving HTML file using AJAX

I have a Javascript application and I need to retrieve an HTML file to template it. The way I am doing this now is:
var _$e = null;
$.ajax({
type: "GET",
url: "/static/jobs_overview.html",
async: false,
dataType: "xml",
success: function (xml) {
_$e = $(xml.documentElement);
}
});
This does seem to work, but for some reason, I am not getting a proper jQuery object in _$e. I know that because the styling is done by jQuery is getting lost at some point, but also, when I set a breakpoint in success, here is what I see:
> _$e
[<div class=​"hello" style=​"background-color:​#FFD700;​height:​200px;​width:​100px;​">​<p>​ Hi ​</p></div>​]
> _$e.width()
TypeError: Cannot read property 'position' of null
However, when I copy the HTML string manually and convert it to a jQuery object as in success, the output is:
> $('<div class="hello" style="background-color:#FFD700;height:200px;width:100px;"><p> Hi </p></div>').width()
100
Seems like the xml object returned isn't getting converted properly into jQuery (or not all attributes of the object are being read properly by jQuery -- given that the HTML is rendering but styling isn't).
The xml object is:
> xml
#document
<div class=​"hello" style=​"background-color:​#FFD700;​height:​200px;​width:​100px;​">​…​</div>​
Any ideas how to get the xml (or the HTML file) rendered as a jQuery object properly?
Could it be because you're grabbing the datatype XML? Have you tried setting your datatype to HTML (or nothing) and just do this (ignoring the .documentElement and just assuming the whole glomp is your HTML):
$.ajax({
type: "GET",
url: "/static/jobs_overview.html",
async: false,
dataType: "html",
success: function (data) {
_$e = $(data); // we are getting back HTML,
console.log(_$e.width()); // jQuery is fine with html globs
}
});
This is likely because you are pulling it in as XML. Try setting the dataType to html and see if that makes any difference.
It also sounds like .load() might better fit your needs: http://api.jquery.com/load/

Jquery response load

A jQuery function receives a string from a database using GET, after that I would like to inject that string into HTML in place of a div. Pretty standard stuff so it seems.
However I am not quite managing it.
Here is what I have going on:
<h1>Whatever</h1>
<div id="replace_me">
</div>
<a id="click_me" href="#">Click Me</a>
<script>
//AJAX
var brand_id = 8
var dataX = {'brand': brand_id, 'csrfmiddlewaretoken': ""};
$(function(){
$("#click_me").click(function(){
$.ajax({
type: 'GET',
url: '/ajax_request/',
data: dataX,
datatype: "json",
success: function(data) {
alert(data);
$("#replace_me").load(data);
},
error: function() {
alert("Nope...");
}
});
});
});
</script>
When the alert is set off I receive my string which shows everything is working fine, but how can I input that string I just received into the div "replace_me" without having to load from another url?
You have an error in your success function. Check documentation on jQuery load(). Instead, you should do
success: function(data) {
//alert(data);
$("#replace_me").html(data);
},
or, slightly better style
success: function(data) {
//alert(data);
$("#replace_me").empty().append($(data));
},
Also note, that you specified "json" in your datatype option. As a consequence, if your server responds in proper JSON, your data will be a JavaScript object, as jQuery will parse the JSON format for you. If you really want to see the object, you will need to use, e.g. JSON.stringify():
$("#replace_me").empty().append($(JSON.stringify(data)));
If your server does not produce valid JSON, your success method will not be called in most cases.
load() is a convenience method to do the two steps of calling the ajax url, then putting the data into the element all in a single function. Instead of calling .ajax(), just call .load()
i.e.
var brand_id = 8
var data = {'brand': brand_id, 'csrfmiddlewaretoken': ""};
$("#replace_me").load('/ajax_request/', data);

How to serialize entire XML document into JavaScript array?

I have a html document which loads an XML document using jQuery
jQuery.ajax( {
type: "GET",
url: example.xml,
etc...
When that XML is loaded I want to serialize the entire XML document into a JavaScript array.
How would I do this?
Something like this?
jQuery.ajax( {
type: "GET",
url: "example.xml",
success: function(data) {
var results = [];
// This bit varies depending on your XML structure, but you get the idea
$(data).find('your_element').each(function(){
results.push($(this));
});
}
});

Categories