Javascript replace not working with jQuery - javascript

So I am using jQuery to load in an html file then do a simple string replace on some tokens. However they will not do the replace. Can someone explain to me why this is not working with the replace calls?
pendingRow.html
<span id="{pendingDbId}" data-database="{pendingName}">
{pendingName} ({pendingTime}) - <a id="cancel-{pendingDbId}" data-dbId="{pendingDbId}" href="#">Cancel</a>
<br />
</span>
jQuery
$('#pendingLoadDiv').load('templates/pendingRow.html', function() {
$('#pendingLoadDiv').html($('#pendingLoadDiv').html().replace("{pendingName}", $('#database option:selected').text()));
$('#pendingLoadDiv').html($('#pendingLoadDiv').html().replace("{pendingDbId}", $('#database').val()));
$('#pendingLoadDiv').html($('#pendingLoadDiv').html().replace("{pendingTime}", "--:--:--"));
$('#pendingDiv').append($('#pendingLoadDiv').html());
});
It is getting all the way to the append at the bottom with no errors however it is not replacing any text.
I have even tried storing the pendingLoadDiv to a variable then running the replace calls on the variable and still am having the same issue.
Any ideas?

You really should not use load, I am sure the browser freaks out with the invalid characters in the id. Plus you are doing all of this DOM look ups when you can just work with the string directly.
$.ajax({
url: "templates/pendingRow.html",
success: function( data ){
var html = data.replace("{pendingName}", $('#database option:selected').text())
.replace("{pendingDbId}", $('#database').val())
.replace("{pendingTime}", "--:--:--");
$('#pendingDiv').append( html );
}
});

In the load success handler it has not yet updated the container. You should first set the html into the container and then try to replace.
$('#pendingLoadDiv').load('templates/pendingRow.html', function(data) {
var $pendingLoadDiv = $('#pendingLoadDiv').html(data);
var markup = $pendingLoadDiv.html();
markup = markup.replace("{pendingName}", $('#database option:selected').text());
markup = markup.replace("{pendingDbId}", $('#database').val());
markup = markup.replace("{pendingTime}", "--:--:--");
$('#pendingDiv').append(markup);
});

.replace() will only replace the first instance of the string, then return. To do a replaceAll, use a regular expression with the global flag: http://jsfiddle.net/RwPuu/
$('#pendingLoadDiv').html($('#pendingLoadDiv').html().replace(/{pendingName}/g, "replacingString"));
EDIT: The jQuery API documentation also seems to state, contrary to the other answers, that the selected element's content is replaced, then the callback is run. http://api.jquery.com/load

I'd guess that at the time the inner function has been called, Jquery has not yet updated the contents of your div with the loaded data, so you're search/replacing the OLD data, which is about to get deleted.
Try
$('#pendingLoadDiv).load('templates/pendingRow.html', function(data) {
^^^^^--- the loaded data
data.replace("{pendingName}", $('#database option:selected').text()));
etc...
$('#pendingDiv').append(data);
}

Related

ajax loading of search results

I have setup a search funtionality that will search in an XSLT file. This works flawlessly but I have a little trouble returning the search results dynamically with ajax.
This is my JS:
var SearchHandler = function(frm) {
frm = $(frm);
var data = frm.find(".search-field").val();
$.ajax({
method: 'GET',
url: '/',
data: { query: data },
dataType: 'xml',
success: SearchSuccessHandler,
error: SearchSuccessHandler
});
};
var SearchSuccessHandler = function(html) {
};
What I want is the SearchSuccessHandler to dynamically load the search result from index.php?query=searchword
I just can't seem to figure out the right way to handle it.
Based on your comment:
Bah.. Sorry... The ajax call will return some new html based on the
query ... I want the existing html to be replaced I have tried
$('body').html(html.responseText); but then I cannot search again
because javascript is not loaded correctly
It's not the AJAX which is the issue but rather event delegation
When you bind a function to an element directly like this:
$('.my-element').on('whatever', function() { ... })
the handler will work as long as the element exists however if you replace the contents of the entire body you'll run into trouble as your original .my-element no longer exists.
You can overcome that by using event delegation to make sure your function keeps searching e.g.
$(body).on('whatever', '.my-element', function() { ... })
This basically says: "If I click on body and the target is .my-element then execute this function"
Instead of a directly bound handler which says: "If I click on this specific element then execute this function"
the body will always exist and therefore you'll always be able to delegate down from the body but if you can do it on some more specific element that would obviously be better since then you won't have an onclick handler on the entire body.
I think this is what your issue is since you're replacing the entire body.
Try this
success:function(data) {
// do your stuff here
}
Of course, you need to be sure your function is returning some values.
To make it easier for your, encode the values as json on your index.php
return json_encode($values)
Then, inside your success function, just parse it with eval()

Trying to use an id from the same page that my .click function was triggered on, in an ajax function

newbie to coldfusion/jquery/programming general here. So the overview of my problem is this: I have a ticket id that corresponds with a specific row in my database. When I click a button, I would like one of the columns in that row to change values to "In Testing". My issue is that I do not know how to pull that ticket id number into my jquery function, or if this is even possible. My code:
<script src="/TicketFaster/js/jquery-1.11.3.js"></script>
<script src="/TicketFaster/js/scripts.js"></script>
<cfset ticketid="#ticketid#">
<button id="in_testing" type="button">In Testing</button>
my js:
$(document).ready(function() {
$("#in_testing").click(function() {
var x = (#ticketid#);
$.ajax({
url: 'ticketcomponent.cfc?method=in_testing',
type: 'POST',
data: {
test: x
}
});
});
});
The big problem is that these pages are being generated dynamically, so each one will have a different ticket id. Therefore, I need to have the ticket id variable be imported rather than just hard coded in to the jquery function. So is this possible? I did not include the query because it works fine when I use it in other places, just getting the data delivered is the tough part. I appreciate any help you can give me :)
Edit: I was requested to post what I'm trying right now.
The original coldfusion is the same so I'm not going to post that again. Here is the js I'm using:
$(document).ready(function() {
$("#in_testing").click(function() {
var x = (<cfoutput>#ticketid#</cfoutput>);
alert(x);
});
});
(I also tried without the cfoutput tags)
As you can see, I'm just trying to do a simple alert to check if my variable has been correctly set. Once I get that to work, then the ajax should follow fairly quickly because I have some experience in that.
What is your specific issue?, can you share a jsfiddle?
for dynamic events replace
$("#in_testing").click(function() {});
for
$(document).on('click','#in_testing', function() {});
This value
var x = (#ticketid#);
in jquery is some like that
var x = $('#ticketid').val(); // for value or $('#ticketid') for object
you just have to take account id created dynamically

Find and manipulate a HTML DIV element that is stored in a variable, using jQuery

I've been searching for a few hours to try and find a solution to my issue, for some reason partially similar answers on here don't seem to be working for me - so I'm creating my own question.
Basically, I'm loading pre-rendered HTML from the server using jQuery's $.get method, and I need to split the HTML returned into two sections (one that's wrapped in a div called #section-one and the other simply alongside that div, with no parent element).
See the example below:
$.get('http://jamie.st/remote_file.php', function(data){
// I want to get '#section-one' and then remove it from data, basically splitting a single returned HTML resource into two, that can be placed in two different areas of the page.
var sectionOne = $(data).find('#section-one');
// This should only return the HTML of '#section-one'
console.log(sectionOne);
// Also how can I then remove '#section-one' from the 'data' variable? The equivalent of calling the below, but from the 'data' variables string/html.
$(sectionOne).remove();
// So eventually the below would return the HTML without the '#section-one' element (and it's children)
console.log(data);
});
I've also created a jsfiddle which you can play around with if you need to, it's set up to use a real PHP file that I've hosted for demo purposes.
http://jsfiddle.net/6p0spp23/6/
If you can submit a jsfiddle link back that would be much appreciated, thanks in advance guys!
When you create a jQuery object with the remote contents $(data) becomes a collection of elements so instead of find() you want to use filter() like so:
$.get('http://jamie.st/remote_file.php', function(data){
var $data = $(data),
$sectionOne = $data.filter('#section-one'),
$rest = $data.filter(':not(#section-one)');
console.log($sectionOne);
console.log($rest);
});
Demo fiddle
I think the best way to put the received data inside a parent div. Then you can call remove or any other method to use it.
You can make parent div hidden using .hide() method if you don't want to show it.
Here I did it:
http://plnkr.co/edit/jQKXyles8sP8dliB7v0K?p=preview
// Add your javascript here
$(function() {
$.get('http://jamie.st/remote_file.php', function(data) {
$("#parent").hide();
$("#parent").html(data);
$("#section-one").remove();
console.log($("#section-one").html())
alert($("#parent").html())
});
});
When you remove a subsection from a derived jQuery object, the original string is not updated with the change so if you want the updated html content you need to generate it from the jQuery object. One way to do this is to
$.get('http://jamie.st/remote_file.php', function (data) {
var $ct = $('<div />', {
html: data
});
// I want to get '#section-one' and then remove it from data, basically splitting a single returned HTML resource into two, that can be placed in two different areas of the page.
var sectionOne = $ct.find('#section-one');
// This should only return the HTML of '#section-one'
console.log(sectionOne);
// Also how can I then remove '#section-one' from the 'data' variable? The equivilant of calling the below, but from the 'data' variables string/html.
$(sectionOne).remove();
// So eventually the below would return the HTML without the '#section-one' element (and it's children)
console.log($ct.html());
});
Demo: Fiddle

text going blank once [ ] gets replaced by < >

I have the following code
$(document).ready(function () {
$(".page").on('click', function () {
$("#ctl00_MainContent_dfComments").html(function (i, val) {
return val.replace(/\]/g, '>');
});
});
$(".page").on('click', function () {
$("#ctl00_MainContent_dfComments").text(function (i, val) {
return val.replace(/\[/g, "<");
});
});
});
Which with the help of replacing characters in entire document JQuery works wonderfully. However, when the < bracket is inserted, the entire div goes blank. I can replace the [ with anything, but as soon as I put in < everything inside that div disappears. Any idea of what might be going on?
Yes, this is supposed to create a bold (kind of like a bb parser)
Your second replace is using .text() instead of .html(). As a side note, you can also combine the two event handlers.
$(document).ready(function () {
$(".page").on('click', function () {
$("#ctl00_MainContent_dfComments").html(function (i, val) {
return val.replace(/\]/g, '>').replace(/\[/g, '<');
});
});
});​
Here it is in action: http://jsfiddle.net/pbnDP/8/
Pressing the button makes the text go bold.
The obvious security concerns are discussed in the comments on the main post. Don't put this on a site where users can generate the content this is being run on.
It looks like your probably not ending up with Valid HTML and the DOM rendering the html is disposing of any invalid HTML for you.
Theres a few problems with your script - the first it that it promotes dangerous html, your appear not to be doing any form of sanity or blacklist/whitelist checking on the code.
The other issue is your manually naming ASP.NET IDs - this is bad since they can change. Use .ClientID instead.
$(".page").on('click', function () {
$("#ctl00_MainContent_dfComments").html(function (i, val) {
return val.replace(/\[/g, "<");
});
});
.html might work better then text, and also use class name or clientid to select elements with like John suggested in his answer , that is not good to guess what the browser is going to change the id to.
Pleas check your DOM again, seems like browser either detects the < > as html tag or html aint valid.
Working version: http://jsfiddle.net/pbnDP/
I do know in few programming world including Ruby there is somthing called html_safe you might want to use alongside this.
Hope it helps.

Setting the innerHTML of an anchor tag through JavaScript

I have an anchor tag on an ASP.NET page, whose text (inner HTML) I wish to populate, through JavaScript, with an integer retrieved from a Web Service.
I tried this using the following:
HTML:
<script type="text/javascript">
$(function () {
GetEntityCount([{ domId: document.getElementById("entityCountIndicator")}]);
});
</script>
<a id="entityCountIndicator"></a>
JavaScript:
function GetEntityCount(domId) {
$.ajax({
type: 'POST',
url: webServiceProxy + '/GetEntityCount',
cache: true,
success: function (xml) { GotEntityCount($(xml).text(), domId); }
});
}
function GotEntityCount(entityCount, domElement) {
if (isNaN(entityCount)) return;
domElement.innerHTML = entityCount.toString();
}
but it did not work.
After examining the variables in FireBug, and doing a bit of experimentation I managed to get it working by changing the line that sets the innerHTML to:
domElement[0].domId.innerHTML = entityCount.toString();
This seemed to do the trick, but I have no idea why it is working or what is happening here.
Why is the document.getElementById("entityCountIndicator") call apparently returning an array, rather than a single element? And why do I then have to probe the first element of that array and set innerHTML on its domId property?
Because your are passing an array in
[{ domId: document.getElementById("entityCountIndicator")}]
Your code can't possibly work, as:
Your passing an array as your first argument (GetEntityCount([{ domId: document.getElementById("entityCountIndicator")}]);), but next try to write the innerHTML from the second element (domElement)
Why are you passing an object inside an array as your domElement, rather than only the element like this: GetEntityCount(0,document.getElementById("entityCountIndicator"));
And here you seem to only pass an id, rather than a dom element: GotEntityCount($(xml).text(), domId);
Edit: I guess I took too long to answer, nevermind in that case.

Categories