We have approval with our client, just a heads up to cover me in any way.
We are needing to modify some of the code in a clients site if a cookie is seen on their computer, the client's site is in ASPX format. I have the first part of the code created, but where I am getting stuck is this:
I need to remove the last 2000 characters (or so) of the body of the page, then append the new HTML to it.
I tried:
$('body').html().substring(0, 10050)
but that doesn't work, I also tried copying that HTML (which did work) and put it back with the new code, but it created a loop of the script running.
Any suggestions on what I should do? It has to be javascript/jQuery sadly.
//////// EDIT ////////////
My script is brought in by Google Tag Manager, and added to the page at the bottom, then my script runs, this is what was causing the loop in the script. Basically, here is the setup:
My Script on my server is loaded into the client site using Google Tag Manager, added to the bottom of the page. From there it is able to execute, but when doing this, it creates a loop of adding the Google Tag Manager script, causing my code to re-add, causing it to re-execute again.
The client is not willing to do anything, he has pretty much told us to just figure it out, and to not involve his web guy.
This is the code straight from their site I am trying to edit.
<script language="JavaScript">
jQuery(function($){
$('#txtPhone').mask('(999) 999-9999? x99999');
$('#submit').click(function(){CheckForm();});
});
function CheckForm(theForm){
if (!validRequired($('#txtfirst_name'),'First Name')){ return false; }
if (!validRequired($('#txtlast_name'),'Last Name')){ return false; }
if (!validRequired($('#txtEmail'),'E-Mail Address')){ return false; }
if (!validEmail($('#txtEmail'),'E-Mail Address',true)){ return false; }
if (!validPhone($('#txtPhone'),'Phone Number')){ return false; }
var dataList='fa=create_lead';
dataList += '&name=' + $('#txtfirst_name').val();
dataList += '&lastname=' +$('#txtlast_name').val();
dataList += '&email=' + $('#txtEmail').val();
dataList += '&phone=' + $('#txtPhone').val();
dataList += '&vid=' + dealerOnPoiVisitId;
dataList += '&cid=' + dealerOnPoiClientId;
dataList += '&leadType=9';
dataList += '&leadSrc=32'; ////////////////////// THIS IS WHAT I AM ATTEMPTING TO CHANGE /////////////////////////
dataList += '&contactname=' + $('#contactname').val();
dataList += '&comment=' + encodeURIComponent($('#txtComments').val());
dataList += '&dvc=' +encodeURIComponent(DealerOn_Base64.encode($('#txtfirst_name').val() + $('#txtEmail').val()));
var lid=1;
$('#submit').prop('disabled', true);
$.ajax({
url:'/lead.aspx',
data: dataList,
dataType: 'json',
success: function(data){
$('#submit').prop('disabled', false);
lid=data.leadid;
if (lid > 1){
$('#submit').prop('disabled', false);
var jqxhr = $.post('/lead.aspx?fa=complete_lead&leadid=' + lid , function() {
window.location.href='/thankyou.aspx?name=' + $('#txtfirst_name').val() + '&lid=' + data.leadid;
});
}
},
error: function(request,error) {
$('#submit').prop('disabled', false);
}
});
}
</script>
This is the page on the site: www.moremazda.com/contactus.aspx
You have to add the HTML back:
var html = $('body').html().substring(0, 10050);
$('body').html(html);
Note that doing this, and just randomly removing chunks of HTML is not good practice, and could lead to a number of problems.
Technically you should be able to do this:
var bodyHTML = $('body');
bodyHTML.html(bodyHTML.html().substring(2000));
But as I pointed out in my comment above, that is a REALLY BAD idea.
If you have access to the HTML to the page, wrap the code you want to replace in a identifiable tag and remove that. I.e.:
<div id="tobeRemoved">Lorem Ipsum</div>
<script>
$('#toBeRemoved').empty();
</script>
If you can't edit the HTML, but you know that it is always the last script tag, you could do something like this:
var scripts = $('script');
scripts.get(-1).remove;
Related
Overview:
I am creating a web page using Python and generating both html as well as javascript in my code. Additionally, I am parsing through csv files and converting their table data to html. I want to be able to click on a line of text and the associated table data for that text would then be loaded into an iframe on the currently active web page. The problem I am having, is that my javascript function is not recognizing the key I send it to retrieve the corresponding table data. If I manually enter the key to return the table data, the correct data is returned - though the table doesn't load. However, if I generate the key programmatically, it returns as 'undefined' even though the strings appear to be identical.
Goal:
I need to figure out if there is something wrong with either the syntax, or the format of the key I am using to try and retrieve the table data. Secondly, I need to figure out why the table data is not being correctly loaded into my iframe.
Example:
import pandas
opening_html = """<!DOCTYPE html><h1> Test</h1><div style="float:left">"""
table_html = pandas.DataFrame({'Col_1':['this', 'is', 'a', 'test']}).to_html()
tables_dict = {'test-1 00': table_html}
java_variables = "%s" % json.dumps(tables_dict)
table_frame = """<iframe name="table_frame" style="position:fixed; top:100px; width:750; height:450"></iframe>"""
test_link_text = """ test-1<br>"""
java = """<script type='text/javascript'>
var table_filename = """ + java_variables + ";"
java += """function send_table_data(obj) {
var t = obj.text + ' 00';
alert(t)
//This line below will not work
var table_data = table_filename[t];
//But this line will return the correct value
var table_data = table_filename['test-1 00'];
alert(table_data);
//This line should load the data, but does nothing
document.getElementsByName('table_frame').src = table_data;
}
</script>"""
html_text = """<head>
<link rel="stylesheet" href="style.css">
</head>""" + test_link_text + table_frame + """<body>""" + "</div>" + java + '</body>'
with open('test_table_load.html', 'w') as w:
w.write(html_text)
EDIT: I did just figure out that for some reason there was a default space at the beginning of the var t - so using trim() seemed to fix that. Now, the only issue left is why the data doesn't load into the table.
It looks like you figured out your typo with the space that was messing with your key, so this is for your second question.
Your code
So to get your table to populate in the iframe you need to fix three things:
To edit the HTML contents of your iframe you should be setting the .srcdoc element, not .src
The document.getElementsByName() function will return an array of HTML elements so in order to get the element you want you should do one of the following:
(recommended) switch to using document.getElementById and use id='table_frame' in your iframe tags
select the first element of the array by using document.getElementsByName('table_frame')[0]
The anchor tag that you're using as the trigger for your function is redirecting you back to the original HTML page, stopping you from seeing any of the changes your javascript function is making. A simple solution to this is to switch to using a <button> element in place of <a>.
Here is what your code looks like with the fixes:
import pandas
import json
opening_html = """<!DOCTYPE html><h1>Test</h1><div style="float:left">"""
table_html = pandas.DataFrame({'Col_1':['this', 'is', 'a', 'test']}).to_html()
tables_dict = {'test-1 00': table_html}
java_variables = "%s" % json.dumps(tables_dict)
table_frame = """<iframe id="table_frame" style="position:fixed; top:100px; width:750; height:450"></iframe>"""
test_link_text = """<button href='' onclick="send_table_data(this);"> test-1</button><br>"""
java = """<script type='text/javascript'>
var table_filename = """ + java_variables + ";"
#for the button, innerText needs to be used to get the button text
java += """function send_table_data(obj) {
var t = obj.innerText + ' 00';
alert(t)
//This line below will not work
var table_data = table_filename[t];
//But this line will return the correct value
var table_data = table_filename['test-1 00'];
alert(table_data);
//This line should load the data, but does nothing
document.getElementById('table_frame').srcdoc = table_data;
}
</script>"""
html_text = """<head>
<link rel="stylesheet" href="style.css">
</head>""" + test_link_text + table_frame + """<body>""" + "</div>" + java + '</body>'
with open('test_table_load.html', 'w') as w:
w.write(html_text)
Other Recommendations
I strongly suggest looking into some python frameworks that can assist you in generating your website, either using HTML templates like Flask, or a library that can assist in generating HTML using Python. (I would recommend Dash for your current use case)
I am building an Application with PhoneGap. The application has content pulled from an outside resource. Within the content I pull, there are URLs. Since I load the content in my html dynamically, the href does not exist when the page is created. What I need is a way to find that dynamically added href once the content is loaded, and call a function on it when clicked.
Here is part of the html page where the content is placed, specifically in the #page-content div:
<div data-role="content">
<div id="page-title"></div>
<div id="page-region"></div>
<div id="page-content"></div>
</div>
Once the page is loaded with the content, the html page changes to this:
<div data-role="content" class="ui-content" role="main">
<div id="page-title">Mtg: Switchboard and Panelboard Basics: A Tour of the Eaton Hayward Facility<br></div>
<div id="page-region">Oakland/East Bay<br></div>
<div id="page-content"><p>THURSDAY February 20, 2014<br>
OEB Industry Applications Chapter<br>
- construction, differences, functions, features …<br>
Speakers: Joseph Burnett, Jason Maffioli, Kendyl Brown, and Bob Salter, Eaton<br>
Time: Light Dinner at 5:30 PM; Short Presentation at 6:00PM; Tours at 6:30 PM<br>
Cost: none<br>
Place:<br>
Web: www.ThisIsTheUrlINeed.com </p>
<p>We will discuss Basics of switchboard construction, functions and features, some of the basic “dos and don’ts” related to Switchboard specification, differences between Switchboards and Panelboards, some of the differences and similarities between switchboards and <span id="more-4060"></span>switchgear, and application limitations. The short presentation will be followed by a tour where attendees can see first-hand the basic building blocks, and how panelboards and switchboards are built.</p>
<br></div>
</div>
The function I wrote/found to try and grab the href is:
$('#page-content').on('click','a', function(){
console.log(this);
currentPage = $(this).attr('href');
window.open(currentPage, '_blank', 'location=yes')
});
Nothing appears in the console.log when I run it. I read that .on should be used for situations like this, so I am stumped as to what to do next.
Edit, here is the function I am using to populate the html page:
function IE_navigate(index) {
Bindex = index;
$.mobile.changePage('#eventPage', 'slidefade');
$.each(data, function(i,item){
if (i == Bindex) {
//Clear if page was previously populated
//Populate page
$('#page-title').html(item.title + "<br />");
$('#page-region').html(item.Region + "<br />");
$('#page-content').html(item.fullInfo + "<br />");
return false
}
});
};
Edit: SOLUTION Thanks to a combination of the two answers below (and all the help from everyone else!) here is how I was able to get this problem to work:
function IE_navigate(index) {
Bindex = index;
$.mobile.changePage('#eventPage', 'slidefade');
$.each(data, function(i,item){
if (i == Bindex) {
//Clear if page was previously populated
//Populate page
$('#page-title').html(item.title + "<br />");
$('#page-region').html(item.Region + "<br />");
$('#page-content').html(item.fullInfo + "<br />");
$(this).ready(function(e) {
$('#page-content').on('click','a', function(e){
e.preventDefault();
console.log(this)
currentPage = $(this).attr('href');
window.open(currentPage, '_system', 'location=yes')
});
});
// return false;
return false
}
});
};
Basically, the function needed to come after the content was loaded. My original method of implementation was not differentiating between the content before or after it was populated. Thanks again everyone!
you need to preventDefault action.
I have tried with sample data.
Demo: http://jsfiddle.net/a6NJk/642/
Jquery:
$('#page-content').on('click','a', function(e){
e.preventDefault();
console.log(this);
currentPage = $(this).attr('href');
window.open(currentPage, '_blank', 'location=yes')
});
//this function for generating dynamic html
$("#bb").click(function(){
$("#page-content").append("Web: www.ThisIsTheUrlINeed.com ");
})
The function you wrote/found to try and grab the href must be run after the page is populated with external content.
e.g
$.ajax({
url: 'http://external/foobar.html',
success: function( data, status, xhr ) {
// stuff data in #page-content and so on
// ...and when the anchor is in DOM;
$('#page-content').find('a').click(function(){
dooTheDoo($this.attr('href'));
});
}
})
Once again I humbly come before you with bruises upon my head from beating my head against a wall...
I have been trying to learn as I go in figuring out how to populate a jQuery EasyUI accordion from a php/MySQL query. I believe that I am now getting the data back to the webpage correctly, but I am unable to figure out how to parse and format this to be displayed as the content on the page. What I am attempting to achieve is basically an accordion to display the contact history with each correspondence with an individual as an accordion item. Here is a sample of the output from the PHP query.
{"rows":[{"phone":"5554072634","contact_dt":"2014-01-27 22:51:37","method":"Email","who":"Scott","note":""},{"phone":"5554072634","contact_dt":"2014-01-27 23:08:49","method":"Spoke","who":"Scott","note":"Called back and she is not interested."}]}
I am trying to get the "contact_dt" as the title of each accordion tab and then format the rest of the elements in the body of the accordion tabs. Currently I'm getting a busy spinner when I select the Contact History tab that contains the accordion but this only yields a tiny square box in the body and does not alter the title. Here is the code that I'm sure I have mangled. First for the HTML portion...
<div id="history" title="Prospect Contact History" closable="true" style="padding:10px;">
<h2 class="atitle">Prospect Details</h2>
<div id="aa" class="easyui-accordion" style="width:500px;height:300px;">
<div title="Title1" data-options="iconCls:'icon-save'" style="overflow:auto;padding:10px;">
<h3 id="hist_title" style="color:#0099FF;">Accordion for jQuery</h3>
<p>Accordion is a part of easyui framework for jQuery.
It lets you define your accordion component on web page more easily.</p>
</div>
</div>
</div>
Now for the jQuery pieces... First is the JS to basically call the function. This is in the body at the end of the page.
<script type="text/javascript">
$('#tt').tabs({
onSelect:function(title){
if (title == 'Prospect Contact History'){
//$( "#hist_title" ).html( "Accordion function is working.");
accordionHistory();
}
}
});
</script>
Now for the function that is defined in the head and where I think the real mess is at.
function accordionHistory() {
$( "#hist_title" ).html( "Accordion function is working.");
var pp = $('#aa').accordion('getSelected'); // get the selected panel
if (pp){
pp.panel('refresh','contact_history.php?phone=' + phone); // call 'refresh' method to load new content
var temp = $('#aa').form('load',pp);
$.each( temp, function( i, val ) {
var txt1=$("<p>Time: ").html(val.contact_dt);
var txt2=$("</p><p>Method: ").html(val.method);
var txt3=$("</p><p>Who: ").html(val.who);
var txt4=$("</p><p>Note: ").html(val.note);
//$("#hist_title").html(val.contact_dt);
$("#hist_item").html(txt2,txt3,txt4);
});
}
}
I'm sure I'm displaying gross ignorance here in basic JS concepts. As I mentioned at the beginning I'm really using this as a learning exercise as well as building something useful. Any help would be greatly appreciated. Additionally, any online tutorials that might help walk me thru some of my conceptual shortcomings would be most welcome. Thanks in advance.
Well... I finally have figured out my issues. Here is the function that I'm now using to get this working.
function accordionHistory() {
var pp = $('#aa').accordion('getSelected'); // get the selected panel
if (pp){
$.ajax({
post: "GET",
url: "get_history.php?phone=" + phone,
dataType: 'json',
success: function( details ) {
$.each(details.rows, function(index, element) {
$('#hist_title').replaceWith(
'Phone: '
+ element.phone
+ 'Contact time: '
+ this.contact_dt
+ '<br/>Method: '
+ this.method
+ '<br/>Who: '
+ this.who
+ '<br/>Note: '
+ this.note
);
});
}
});
}
}
I hope some other noob like myself finds this useful.
I have written a function to display some paragraph tags from an external webpage. For some reason the results are displayed in firebug console but not showing on the web page as I wanted (blank page).
function requestCrossDomain(callback){
var querylink = "select * from html where url='http://somedomain.com'" +
" and xpath='/html/body/div/div/div[2]/div/div/div/dl'";
var yql = 'http://query.yahooapis.com/v1/public/yql?q=' +
encodeURIComponent(querylink) + '&format=json&callback?';
$.getJSON(yql, function(data){
if (typeof callback === 'function'){
callback(data);
}
});
}
My firebug console shows the below value.
{"query":{"count":1,"created":"2013-12-23T06:31:46Z","lang":"en-US","results":{"dd":{"p":"Hills: High"}}}}
How can I modify the code to display the value of the P tag, which is "Hills: High"
I'm calling the function from HTML code and trying to display the value inside "#targetWrapper"
requestCrossDomain(function(results){
$('#targetWrapper').html(results);
});
Edited to reflect a functional fiddle
$(document).ready(function(){
requestCrossDomain();
});
function requestCrossDomain(){
var querylink = "select * from html where url='http://www.bom.gov.au/wa/forecasts" +
"/armadale.shtml' and xpath='/html/body/div/div/div[2]/div/div" +
"/div/dl'";
var yql = 'http://query.yahooapis.com/v1/public/yql?q=' +
encodeURIComponent(querylink) + '&format=json&callback?';
$.getJSON(yql, function(data){
$('#targetWrapper').html(data.query.results.dl.dd[0].p);
$("#targetWrapper").append("<br/><strong>" + JSON.stringify(data) + "</strong>");
});
}
Your data format was very much off the mark AND you cannot have two functions with the same name.
The object you get back from $.getJSON is a simple Javascript Object. You can access it just as you would any other object:
In this case, you'd use:
requestCrossDomain(function(results) {
$("#targetWrapper").html(results.query.results.dd.p);
}
I would highly recommend that you read the MDN documentation I linked above. Having MDN bookmarked is also a good idea; it's a great resource to have easy access to.
this is my first time here as a poster, please be gentle! I have zero knowledge of JS (yet, working on it) but am required to do some JS anyway. Here's my problem. I got some code (not mine) allowing a user to select multiple choices. I found the function that gathers these choices and store them
function getProductAttribute()
{
// get product attribute id
product_attribute_id = $('#idCombination').val();
product_id = $('#product_page_product_id').val();
// get every attributes values
request = '';
//create a temporary 'tab_attributes' array containing the choices of the customer
var tab_attributes = [];
$('#attributes select, #attributes input[type=hidden], #attributes input[type=radio]:checked').each(function(){
tab_attributes.push($(this).val());
});
// build new request
for (var i in attributesCombinations)
for (var a in tab_attributes)
if (attributesCombinations[i]['id_attribute'] === tab_attributes[a])
request += '/'+attributesCombinations[i]['group'] + '-' + attributesCombinations[i]['attribute'];
$('#[attsummary]').html($('#[attsummary]').html() + attributesCombinations[i]['group']+': '+attributesCombinations[i]['attribute']+'<br/>')// DISPLAY ATTRIBUTES SUMMARY
request = request.replace(request.substring(0, 1), '#/');
url = window.location + '';
// redirection
if (url.indexOf('#') != -1)
url = url.substring(0, url.indexOf('#'));
// set ipa to the customization form
$('#customizationForm').attr('action', $('#customizationForm').attr('action') + request);
window.location = url + request;
}
I need to make a simple display summary of these choices. After quite a bit of searching and findling, I came with the line with the DISPLAY SUMMARY comment, this one:
$('#[attsummary]').html($('#[attsummary]').html() + attributesCombinations[i]['group']+': '+attributesCombinations[i]['attribute']+'<br/>')
In the page where I want those options, I added an empty div with the same ID (attsummary):
<div id="attsummary"></div>
Obviously, it is not working. I know I don't know JS, but naively I really thought this would do the trick. May you share with me some pointers as to where I went wrong?
Thank you very much.
Correct form of the line it isn't working for you:
$('#attsummary').html($('#attsummary').html() + attributesCombinations[i]['group']+': '+attributesCombinations[i]['attribute']+'<br/>')