Javascript hyperlinks don't work with jQuery append - javascript

I need some help pointing to the right direction. I have a jQuery code what pulls some HTML content via the $.get function after the page is loaded, puts them into the $data variable and it's appended to the div_content.
Everything works perfectly, except after the appending the javascript links in the original content don't work.
The code part:
$(document.body).ready(function() {
$.get("content1.php", {id:"1234" }, function(data) {
// for example this is the pulled data
var data = 'link'
$('.div_content').append(data);
});
});
The standard tags, without javascript aren't affected, they work fine.
I found some advices like this - jQuery Appended elements with href and javascript doesn't work - and this - Appending a link with Jquery - and read the jQuery's .on() function but doesn't seem to resolve my exact problem with appending the content.
I have jQuery 1.10.1, thanks for all the inputs.

Without seeing what data may contain its difficult to see exactly what you're trying to achieve but I can see the fist thing you do after receiving the ajax response is overwrite the returned data which is obviously incorrect.
perhaps you meant something like this?:
$.get("content1.php", {id:"1234" }, function(i,data) {
var link = 'link';
$('.div_content').append(link);
});

Thanks for the responses and comments, mea culpa, it was my, a design error. I had to include the jquery and fancybox JS and CSS into the someotherpage.php (the data-id attribute), and now it's working.

Related

Append a load() output to the same div in jQuery

A button calls a JS function that loads a different PHP page asynchronously using jQuery load, and it will put the result in a errorReturn div.
<div id='errorReturn'></div>
<button onclick='trySomething()'>Click me</button>
<script>
function trySomething() {
var url = 'otherpage.php'
$('#errorReturn').load(url)
}
</script>
All is fine.
Since I want the user to see ALL the errors if the button is clicked multiple times, I wanted to APPEND that result to the same div.
I tried both
$('#errorReturn').append.load(url)
$('#errorReturn').append(load(url))
And they didn't work. Then I found the solution:
$('#errorReturn').append($('#errorReturn').load(url))
It works. Kind of :( It fills the errorReturn div, but it doesn't append to it. It simply overwrites it, as if I simply wrote
$('#errorReturn').load(url)
I should probably just take a break, but I cannot see what's wrong :(
EDIT: Since somebody flagged this as "answered in another question", the other question was using JS while I was explicitly asking for jQuery - plus the other answer generated a lot of fuss about adding HTML with possible XSS injection and I think the accepted answer here is way nicer and simpler to understand
load() always overwrites the content of the target element. To do what you require you could make the AJAX request and append the content manually. Try this:
<div id="errorReturn"></div>
<button id="add-content">Click me</button>
jQuery($ => {
$('#add-content').on('click', e => {
$.ajax({
url: 'otherpage.php',
success: html => $('#errorReturn').append(html)
});
});
});
Make a new <div>, .load() content into it, and .append() that.
$("#errorReturn").append($("<div/>").load(url));
You can of course also add styles etc. to the <div>, like for example a top margin to separate the individual errors.

Use callback function to create variables and use in a html element

Firstly excuse my ignorance with any inaccurate information I provide I a very new to javascript, jquery and json.
Anyway I have a script which pulls data from a json file and displays in a webpage with the help of javascript, jquery, ajax(i think) and json.
There is a callback for when I get back the results:
function searchCallback(data) {
$(document.body).append('<h1>' + data.title + '</h1>');
}
And it works fine the like this. However I want data.title (json object) to be displayed in a html element of my choice without having to use $(document.body) because my page won't display correctly at I have other html elements outside the script.
As far as I know (excuse ignorance) with javascript I can possible add a variable and use it as follows:
var title = data.title;
And in my html:
<span id="title"></span>
or maybe there is cleaner way?
Anyway how do I achieve this. Thank you for any help!!
If you want to find an element and modify, jQuery makes this easy. Instead of $(document.body).append find an existing element by it's id, and then call the text method on it to replace the text inside that element with something new.
$('#title').text(data.title);

Removing data attributes from HTML using jQuery

Can't seem to get this one to work...
I have a page that hides certain links. When the DOM is loaded, I'm using jQuery to toggle some of those elements. This is driven by using a data attribute like so:
<div class="d_btn" data-usr='48'>
<div class="hidden_button">
Then, I have the code:
$.each($(".d_btn"), function() {
var btn = $(this).data('usr');
if ( btn == '48' ){
$(this).children('.hidden_button').toggle();
}
The above all works as planned. The problem is that I am trying to remove the data-usr from the class .d_btn once the if statement is evaluated. I've tried the following and nothing works (i.e., after the page is loaded, the source still shows the data-usr attribute:
$(this).removeAttr("data-usr");
$(this).removeData("usr");
I've been working on this for a couple of hours now and...nothing! Help is greatly appreciated!
UPDATE
I've tried the great suggestions of setting the data attribute to an empty string but I'm still not getting the desired result.
To explain a little further, The reason I'm trying to remove the attribute is so when an ajax response adds another item to the page, the previously added items would already have the button either shown or hidden. Upon AJAX response, I'm calling the same function once the DOM is loaded.
Currently, when something is added via AJAX, it toggles all the buttons (showing the ones that were hidden and vice versa.) Ugh...
I'm also fully willing to try alternatives to my approach. Thanks!
UPDATE
Well, the light bulb just flashed and I am able to do what I want to do by just using .show() instead of .toggle()
Anyway, I'd still like to find an answer to this question because the page will be potentially checking hundreds of items whenever something is added - this seems horribly inefficient (even for a computer, hahaha.)
Why don't you set the value to a random value or empty variable instead if removeAttr does not work..
$(this).attr("data-usr" , '');
$(this).prop("data-usr" , '');
Changing the DOM doesn't affect the source. It affects the DOM, which you can view with the Inspector/Developer Tools. Right click => View Source will give you the original source of the page, not the actual current source as modified by JavaScript.
Set it to a blank string:
$(this).attr("data-usr", "");
I second what Kolink said: check the DOM, not the source. (Chrome: Ctrl + Shift + i).
As others have stated. Checking the source will only show the original unedited source for the webpage. What you need to do is check the DOM using developer tools.
I've just checked everything in Chrome's inspector on jsfiddle here and the attribute is definitely being removed as well as the data.

Retrieving links using Jquery

I posted this up a day or two ago, received an answer which worked on JSfiddle, but didn't work on my actual code.
<div id="PublicResults">
<h2>
<dl>
<dt>
<a onmouseout="swho.alone.OnMouseOut(event)" onmouseover="swho.alone.showPopup(event, 'DR647E481', 'pra**', '', '', 'everyone', 'closed')" href="/SWApp/detailAction.do?key=DR647E481&search=pra**&soundex=&stanfordonly=&affilfilter=everyone&filters=closed">Ajay Prakash</a>
</dt>
Now, I tried $jq("#PublicResults a").attr("href"), which worked in jsfiddle, but isn't working on the page (my console reads undefined). However, when I try $jq("#PublicResults a[href]").attr("href"), I get the url of the current webpage- so I guess the issue is that .attr() is returning only the first element
So my question is twofold- if what I wrote just above is correct, how do I make .attr() return all elements. If not, what should I do to retrieve the url in href?
You have to loop troughout the array list of all links do you want to scraping:
$jq("#PublicResults a").each(function()
{
alert($(this).attr("href"));
});
If you have your jQuery instance tied to $jq() (instead of the usual $() or jQuery()), then $jq("#PublicResults a[href]").attr("href") should work. Could you post a link to where it doesn't work?
I suspect one of the following:
You may be running the jQuery code before the #PublicResults element is added to the page
It is possible that the $jq() function is not available
Something else may be altering your link href
You can use map to extract all of the href's from the jQuery wrapped objects. eg.
$('...').map(function() { return $(this).attr('href'); });
This returns a jQuery wrapped array, to get a normal JavaScript one, just use .get().

Firefox add <a xmlns="http://www.w3.org/1999/xhtml">

EDIT: This isn't happening because of the ajax call. I changed it to use a value from a TinyMCE component for fun and I get the same thing.
content = tinyMCE.get('cComponent').getContent(); //content at this point is <p>test</p>
valueToDisplay = content;
If I do:
jQuery(selector).html(valueToDisplay);
I get:
<p><a xmlns="http://www.w3.org/1999/xhtml">test</a></p>
Has anyone ever seen this before using Firefox 3.6.10 and jQuery 1.4.2, I am trying to change a link text using the result from a jQuery ajax call.
I get the result expected from the ajax call:
function getValueToDisplay(fieldType){
var returnValue;
jQuery.ajax({
type: "GET",
url: "index.cfm",
async:false,
data: "fieldtype="+fieldType,
success:function(response){
returnValue = response;
}
});
return returnValue;
}
If I check the value at this point I get the expected value
console.log(returnValue) //output this --> <p>Passport Photo</p>
However when I use jQuery(selector).html to insert it inside of an existing anchor
I get:
<p><a xmlns="http://www.w3.org/1999/xhtml">Passport Photo</a></p>
I have been trying to figure out where that xmlns anchor is added but can't narrow it down to anything specific.
EDIT: I have tried forcing dataType:"html" in the ajax call...no change.
Your selector represents something that is, or is in an a tag.
A much more minimal version of your problem would be:
html:
<a id="test"></a>
js:
$('#test').html('<p>test</p>');
result:
<a id="test"><p><a xmlns="http://www.w3.org/1999/xhtml">test</a></p></a>
Change things around so you aren't putting p tags in an a tag, or do the following:
$('#test').empty().append('<p>test</p>');
I would like to extend the answer, as of why is happening, and provide a workaround.
Doing a GreaseMonkey script i was trying to change the content of an element, perhaps not changing per se but adding more elements as the tag had only an IMG inside.
Original:
<a onclick=something><img src=url></a>
What i tried to do was to insert a DIV element that would wrap the already IMG and another new SPAN second child, so the objetive was to end up with this:
<a onclick=something><div><img src=url><span>text</span></div></a>
Using the innerHTML property it would be like this:
ANode.innerHTML = '<div>' + ANode.innerHTML + '<span>text</span></div>';
but instead i got:
<a onclick=something><div><a xmlns="http://www.w3.org/1999/xhtml"><img src=url><span>text</span></a></div></a>
Looking at the answers here did help a bit although there's no real explanation. After a while i noticed something that does not happens with the example in the question, which now i believe is the key to this issue. I was the same as jfrobishow thinking where was it happening, i thought there was something wrong concatenating the ANode.innerHTML.
Answering, at the original question, the part of narrowing it down to where does this happens, notice that the out-of-nowhere <A> was enclosing both the IMG and the new SPAN nodes, so this made me curious, the unwanted <A> was being added just before the DIV element was "built". So from this, the original example, and my following workaround you can notice that this happens when you insert a new BLOCK node inside an Anchor, as both DIV and P (original example) elements are BLOCK elements.
(If you don't know what i mean by BLOCK is from the display property of an element http://www.w3schools.com/cssref/pr_class_display.asp)
The obvious workaround is to replace the type of node you're inserting, to a non-block element, in my case the problem was the DIV i wanted, but of course it depends on the objective of your script, most of the things are there by design, i put a DIV because i needed it, so i fixed it turning that DIV into another SPAN ( which is an inline element) but i still needed to behave like a block element so put the style, this is what worked for me:
ANode.innerHTML = '<span style="display:block;">' + ANode.innerHTML + '<span>text</span></span>';
So, plainly, this problem is not from scripting (Javascript for me) but from style (CSS) stuff.
BTW, this happened at Firefox 3.6.18, notice this does not happens at Firefox 5.0.
The problem is placing block elements inside an anchor tag.
This is not valid HTML, even though most browsers will parse it fine.
You just need to use a <span></span> element inside the anchor, instead of a <div> or <p>.
This is happening because in your <html> you declared a XML Namespace (xmlns). If the xmlns anchor is not breaking anything, just leave it there.
Also, don't use async:false, make a callback function to be called on success.
EDIT: Actually that just fixed the issue with that particular value... it started happening on other values where it used to be fine.
Somehow this fixed the issue.
Changed
jQuery(selector).html(valueToDisplay)
to
jQuery(selector).html(
function(index, oldHtml)
{
return valueToDisplay;
}
);
According to the doc, if I read it right it should be doing the same thing as I am not using oldHtml in the function. (http://api.jquery.com/html/).
From the doc: "jQuery empties the element before calling the function; use the oldhtml argument to reference the previous content."
Try changing dataType in your ajax call to "text"
Using .append() instead of .html() fixed the issue for me. Never seen this before today. Why is it adding the extra xmlns? I tried changing my dataType to "text" as well, but it didn't work. It was really messing up my CSS styles as well, but using .append() completely resolved the issue. Thanks!
UPDATE: I needed to completely replace the content of my div with the result of an .ajax() query. .append() by itself wasn't sufficient, as it would just add to the content, so I found another workaround:
First clear the div:
$("#myDiv").html("");
Then, append the content using .append():
$("#myDiv").append("My content");
It's not perfect, but it works.

Categories

Resources