Replace text using Javascript on HTML page - javascript

I have a php web page with many informations on it, some of them are quite sensitive and I would like hide them and the possibilty to unhide them.
My web page is built like this to show the informations :
echo '<b>Login :</b> ' . $data['Login'] . '<br \>';
echo '<b>MDP :</b>' . decrypt($data['MDP'], $passkey) . '';
So I'm working on a small Javascript code to hide/show the MDP. It's not finished (cause it work only half), it look like this :
<span class="visible">My text to hide</span><br \>
<span class="visible">My other text to hide</span><br \>
<button id="Replace" onclick="replace()">Change content</button>
<script>
window.onload = function(){
document.getElementById("Replace").addEventListener( 'click', replace);
}
var Visible = document.getElementsByClassName('visible');
var HiddenText = document.getElementsByClassName('hiddentext');
var OriginalText = new Array();
for (var k = 0; k< Visible.length; k++){
OriginalText[k] = Visible[k].innerHTML;
}
function replace() {
if (Visible != null){
for (var i = 0; i< Visible.length; i++){
Visible[i].innerHTML = '*****';
Visible[i].className = 'hiddentext';
}
}else{
for (var j = 0; j< HiddenText.length; j++){
HiddenText[j].innerHTML = OriginalText[j];
HiddenText[j].className = 'visible';
}
}
}
</script>
I don't know why it look like it only work once. It replace the text with the stars and the Class change well but when I use it again, nothing happen.
I tried the code separetely (both part of the if) and all work good.
I'm far from an expert to code so I probably missing something, maybe someone can help me on it.

I finally did it in a different way, instead of replacing the text I just don't show it. I used PHP to hide the text, if you clic on the button the text is shown and after a delay a javascript code will redirect to the same page without the POST information that will automaticaly hide the text again.
function mdpviewer($data){
$ShowMdp = false;
if (isset($_POST['ShowMdp']) AND ($_POST['ShowMdp'] == true) AND ($ShowMdp != true)){
$ShowMdp = $_POST['ShowMdp'];
}else{
$ShowMdp = false;
}
if ($ShowMdp == true) {
return $data;
}else{
echo '';
}
}
echo '<form action="MyPage.php" method="post"><input type="submit" value="Show Passwd"><input type=hidden name="ShowMdp" value="true"></form></div>';
echo'<p>My Password : (mdpviewer($data['Psswd'])</p>';
if (isset($_POST['ShowMdp']) AND ($_POST['ShowMdp'] == true)){
echo '<script>setTimeout(function() { window.location.href = "MyPage.php";}, 30000);</script>';
}
It's probably not optimized and a bit messy but it's working great !
If someone found how to do it with replacing the text on javascript I will be glad to see it

maybe you could apply your logical differently. You could create php files whose purpose is returns data only in json format. This is simutale web service. So, when load page finished, by javascript you could request fetch to .php file endpoint, and manage response and make DOM modifications, another recommendation is you study es6 to do best practices! But is a tip, congratulations for resolve problem and my apologies if my english is bad, but im learning, cheers!

Related

Get value from jQuery editor to PHP

I'm using this jquery plugin to create a wysiwyg text editor,
I created a textarea in PHP where:
<textarea name="body" id="body"><?php echo $body?></textarea>
and
<script type="text/javascript">
$(document).ready( function() {
$("#body").Editor();
});
</script>
Now i need to get value of this area for send it to SQL
if (isset($_POST['add-article'])) {
unset($_POST['add-article']);
$_POST['user_id'] = $_SESSION['id'];
$_POST['username'] = htmlentities($_SESSION['username']);
$_POST['published'] = isset($_POST['published']) ? 1 : 0;
// I need this line
$_POST['body'] = htmlentities($_POST['body']);
When I put text into this editor, it doesn't enter (value) into the textarea.
I have to have value before I press the add-article button, beacuse now it gives me an empty text.
I found something like this
function displayText(){
alert($("#body").Editor("getText"));
}
This causes it to return text ( i think only display by JS ) but i completely dont know how to use in my PHP scripts.
Second thing is when i write article and make a mistake something like ( Article title already exist ) ( in one session ) text in textarea stayed, but now doesn`t work it.
I think about if there is an error for example "Title already exist" follows:
} else {
$title = $_POST['title'];
$body = $_POST['body'];
$category_id = $_POST['category_id'];
$published = isset($_POST['published']) ? 1 : 0;
}
In my honest opinion i need something like:
add-article.addEventListener('click', function {
$body (from PHP) = alert($("#body").Editor("getText"))(from JS);
}
Thank you in advance for help.
On the plugin page you referenced, I see this is one of the recommendations. Capture the value you want when the click button is pressed, before the form submits.
Add a script to your form submit to put the texteditor content into this element
<form onsubmit='return getItReady()'>
Add an element to the form you'll use as a proxy element and keep it hidden, something like
<textarea id='txtEditorContent' name='txtEditorContent' style='visibility:hidden;height:0px' tabindex="-1"></textarea>
Then add the script to prepare it
<script>
function getItReady() {
console.log('The content:', $('#body').Editor("getText"));
$('#txtEditorContent').val($('#body').Editor("getText"));
return true;
}
</script>
Then in your PHP, it will come through as $_POST['txtEditorContent'].

Issue passing PHP variables through Javascript and back

so this function seems to be confusing me.
echo"
<td style='font-size:12px;width:150px;'><div style=\"overflow-y:auto; max-height:250px; width:200px;\">
{$row['Notes']} </div><br /><center><br />
<button onclick=\"myFunction('{$row['ID']}','$rowID')\">Add Note</button>
<form action=\"http://calls.fantomworks.com/functions/notes.php\" id='notesForm' name='notesForm' method='post'>
<input type='hidden' id='notesID' name='notesID' />
<input type='hidden' id='rowID' name='rowID'/>
<input type='hidden' id='notes' name='notes' />
</form>
</center>";
Calls this javascript
<script language="JavaScript" type="text/javascript">
function myFunction(ID,rowID)
{
var x;
var ID = ID;
var rowID = rowID;
var note = prompt("Customer Note","Write your customer note here...");
if (note != null) {
document.getElementById("notes").value = note;
document.getElementById("notesID").value = ID;
document.getElementById("rowID").value = rowID;
document.getElementById("notesForm").submit();
}
else{
return false;
}
}
</script>
and ends up at this php page
$notesID = $_POST['notesID'];
$rowID = $_POST['rowID'];
$note = $_POST['notes'];
//Redirect to browser
header("Location: ./index.php#row_$rowID");
The only problem is that the rowID does not seem to be making it through and generates links ending like "index.php#row_"
I can't make sense of why rowID isn't coming through but NotesID and notes are.
As you can see from the debug the value is there.
Thanks for any thoughts or suggestions!!
The script at "http://calls.fantomworks.com/index.php" is being POSTed to by your javascript function - thus the variable that you seek ought to be available through the $_POST global.
Try changing
header("Location: ./index.php#row_$rowID");
To
header("Location: ./index.php#row_{$_POST['rowID']}");
Incidentally, the three variables you define in the javascript function seem redundant and could be removed by the looks of things, namely:-
var x;
var ID = ID;
var rowID = rowID;
Have had a closer look since posting original ( and hadn't noticed the assignment of posted vars by the #OP ) - there are hundreds of forms on the page in question - same IDS used from row to row to row. IMHO - this is definitely NOT the way forward - You could have just one form for "Add Note" as you dynamcally set the value by clicking the button. It does appear that the relevant vars ( rowID etc ) are being set and assigned to the button that calls the javascript so theoretically you could have just one form that is used to post to "notes.php" but have this button on each row.
In terms of a general critique / suggestions
The page is very slow to load - due in part to there being hundreds of complex table row layouts, and by the looks of things a form for every button - then there are the images which themselves are fullsize but could really be ( and should be ) thumbnails. The number of forms could be drastically reduced if each button were to dynamically assign the variables like the one in the question above.

Can you perform certain onload functions from a link on a previous page

I'm not even sure what I'm thinking of will work and can't seem to find the right wording to get and search results that are remotely helpful so here goes.
What I want to be able to do is have a link from one page then cause the linked page to display a certain way. The code below is the script being used on the page I'll be linking to.
$(document).ready(function() {
$('.hideshow').click(function () {
var name = $(this).attr('id').replace("-L","");
if ($(this).hasClass("hidden")) {
$(this).addClass("shown");
$(this).removeClass("hidden");
$('div#' + name).show(500);
} else {
$(this).addClass("hidden");
$(this).removeClass("shown");
$('div#' + name).hide(500);
}
});
});
This code will hide or show content when links on the page are clicked using the id names used in the body of the file. Now what I want to be able to do is have the link from the previous page indicate certain links on this page as being shown. The following is some of the in body code.
<a class="hideshow hidden" id="cat-articles-L" style="cursor:pointer;"><font style="font-size:24px; color:#06F; text-decoration:underline;"> Cat Articles</font></a><br />
<div id="cat-articles" style="display:none;">
<a class="hideshow hidden" id="cat-beds-L" style="cursor:pointer;"><font style="font-size:18px; color:#06F; text-decoration:underline;">Cat Beds</font></a><br />
On default the "Cat Articles" are visible but "Cat Beds" is hidden until "Cat Articles" is clicked, then there could be sublevels so more items under "Cat Beds" The idea is when you link from the other page having it load with certain items already open.
Hope I made this clear enough, still new to this site and posting questions.
Add a parameter to the link on the original page. Something like domain.com/page.html?id=5 and then have javascript check for a QueryString of id and do something like a switch with it.
See How can I get query string values in JavaScript? for how to get QueryStrings if you aren't familiar.
If you need to pass multiple of the same type (example, multiple IDs), you can make an array and pass that array to the other page. In that array, include every id you want to display.
See an example of an array to url here: JavaScript Array to URLencoded
Example (Original Page):
var idArray = new Array(1,5,15,38);
var url = "http://www.blah.com/link.html?"+idArray.join('&');
Example (Linked page):
var qs = (function(a) {
if (a == "") return {};
var b = {};
for (var i = 0; i < a.length; ++i)
{
var p=a[i].split('=');
if (p.length != 2) continue;
b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
}
return b;
})(window.location.search.substr(1).split('&'));
var idArray = qs["id"];
for (var i = 0; i < idArray.length; i++) {
switch(idArray[i]){
case 1:
//show link1
break;
case 2:
//show link3
break;
default:
//do nothing, but required
break;
}
}
Note: It may look that I'm using JQuery, but I'm not. This will work without it just fine.

Is there a limit of the size of data using replaceWIth in jQuery?

I am using the replaceWith() function in jQuery to update my web page. I receive the data from a C# web service program that extracts data from a database to build my HTML code. It works fine except when I replace large amounts of data. In the example that's not working, I replace code in my web page with 39000 bytes of data. After that, none of my links work when clicking on a span to calls a JavaScript function. Is there a limit on the size of data used in the replaceWith() function? The html code I am replacing looks like this:
<td align=left valign=top>
<div id="showitems" class="showitems" style="display:inline; float:left"></div>
</td>
The javascript code looks like this:
function ShowDinerItems() {
var gps = document.getElementById("selectdiner").value;
var pos = gps.indexOf(";");
var len = gps.length;
var latitude = document.getElementById("Hiddenlat").value;
var longitude = document.getElementById("Hiddenlng").value;
var dinerkey = gps.substring(0, pos);
PageMethods.CallShowDinerItems(dinerkey, latitude,longitude, OnShowDinerComplete, OnShowDinerError, dinerkey);
}
function OnShowDinerComplete(result) {
var htmlcode = result[0];
if (result == 'none') {
document.getElementById("Message").value = "Search returned no items";
}
else {
var htmlcode = result[0];
htmlcode = "<div id=\"showitems\" class=\"showitems\" style=\"display:inline\">" + htmlcode + "</div>";
$('.showitems').replaceWith(htmlcode); // size of htmlcode is 39849 bytes
var locations = result[1].split(";");
var lat = locations[0];
var lng = locations[1];
markDiner(lat, lng, "", 'map_canvas');
}
}
The reason I am using jquery to build my webpage is to avoid page reloads. I could easily program the webdata content in my C# program which may be more efficient but page reloads are to be avoided as dictated by the people who own the website. I am will try the recommendations given.
Note: I used the following code to make it work.
$('.showitems').html(result[0]);
Using .text will not work as it displays raw data and not html data. Thanks to those who contributed.
To be honest I think you're going about this the wrong way here.
It seems to me that you're using ReplaceWith to completely overwrite the matched tag when you could just as simply change its properties with jQuery.
For example:
var htmlcode = result[0];
htmlcode = "<div id=\"showitems\" class=\"showitems\" style=\"display:inline\">" + htmlcode + "</div>";
$('.showitems').replaceWith(htmlcode); // size of htmlcode is 39849 bytes
Could easily be changed to this:
$('.showitems').css('float','none').text(result[0]);
Just how many showItems are there going to be by the way, and how do you know how it compares to how many results you get back from the C# call ?
Edit 2: Sorry, didn't realise that the CSS display attribute wasn't actually changing.

Is it possible to change a Javascript Variable from an Ajax Response?

I'm trying to update a Javascript variable that controls a scrolling script based upon some Ajax code. The Ajax code is supposed to add to the JS Var when conditions are true in the Ajax script. Is there any way to trigger this?
Thanks!
edit: I'm not sure how to change the value of the variable. I've tried changing it via the Ajax but it doesn't get parsed. I've also tried using PHP inside of JS to check a condition, but doing that only works once.
JS Code
function speedUp()
{
actualheight = actualheight + 50;
}
function slowDown()
{
actualheight = actualheight - 50;
}
function ajaxFunction()
{
var xmlhttp = createRequestObject();
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)
{
document.getElementById('iemarquee').innerHTML=xmlhttp.responseText;
document.getElementById('iemarquee2').innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","saleCallTest.php",true);
xmlhttp.send(null);
}
/*
Cross browser Marquee II- © Dynamic Drive (www.dynamicdrive.com)
For full source code, 100's more DHTML scripts, and TOS, visit http://www.dynamicdrive.com
Modified by jscheuer1 for continuous content. Credit MUST stay intact for use
*/
//Specify the marquee's width (in pixels)
var marqueewidth="500px"
//Specify the marquee's height
var marqueeheight="500px"
//Specify the marquee's marquee speed (larger is faster 1-10)
var marqueespeed=1
//Specify initial pause before scrolling in milliseconds
var initPause=1000
//Specify start with Full(1)or Empty(0) Marquee
var full=1
//Pause marquee onMousever (0=no. 1=yes)?
var pauseit=0
//Specify Break characters for IE as the two iterations
//of the marquee, if text, will be too close together in IE
var iebreak='<p></p>'
//Specify the marquee's content
//Keep all content on ONE line, and backslash any single quotations (ie: that\'s great):
var marqueecontent='<?php for($i=0;$i<=count($saleItems);$i++)
{
if ($saleItems[$i]['stateOfItem'] =="Sold" || $saleItems[$i]['stateOfItem'] =="Unsold")
{
$_SESSION['countItems']++;
echo $saleItems[$i]['itemNumber'];
echo $saleItems[$i]['stateOfItem'] . '<br />';
}};
?>'
////NO NEED TO EDIT BELOW THIS LINE////////////
var copyspeed=marqueespeed
var pausespeed=(pauseit==0)? copyspeed: 0
var iedom=document.all||document.getElementById
var actualheight=''
var cross_marquee, cross_marquee2, ns_marquee
function populate(){
if (iedom){
var lb=document.getElementById&&!document.all? '' : iebreak
cross_marquee=document.getElementById? document.getElementById("iemarquee") : document.all.iemarquee
cross_marquee2=document.getElementById? document.getElementById("iemarquee2") : document.all.iemarquee2
cross_marquee.style.top=(full==1)? '8px' : parseInt(marqueeheight)+8+"px"
cross_marquee2.innerHTML=cross_marquee.innerHTML=marqueecontent+lb
actualheight=cross_marquee.offsetHeight
cross_marquee2.style.top=(parseInt(cross_marquee.style.top)+actualheight+8)+"px" //indicates following #1
}
else if (document.layers){
ns_marquee=document.ns_marquee.document.ns_marquee2
ns_marquee.top=parseInt(marqueeheight)+8
ns_marquee.document.write(marqueecontent)
ns_marquee.document.close()
actualheight=ns_marquee.document.height
}
setTimeout('lefttime=setInterval("scrollmarquee()",20)',initPause)
}
window.onload=populate
function scrollmarquee(){
if (iedom){
if (parseInt(cross_marquee.style.top)<(actualheight*(-1)+8))
cross_marquee.style.top=(parseInt(cross_marquee2.style.top)+actualheight+8)+"px"
if (parseInt(cross_marquee2.style.top)<(actualheight*(-1)+8))
cross_marquee2.style.top=(parseInt(cross_marquee.style.top)+actualheight+8)+"px"
cross_marquee2.style.top=parseInt(cross_marquee2.style.top)-copyspeed+"px"
cross_marquee.style.top=parseInt(cross_marquee.style.top)-copyspeed+"px"
}
else if (document.layers){
if (ns_marquee.top>(actualheight*(-1)+8))
ns_marquee.top-=copyspeed
else
ns_marquee.top=parseInt(marqueeheight)+8
}
}
if (iedom||document.layers){
with (document){
if (iedom){
write('<div style="position:relative;width:'+marqueewidth+';height:'+marqueeheight+';overflow:hidden" onMouseover="copyspeed=pausespeed" onMouseout="copyspeed=marqueespeed">')
write('<div id="iemarquee" style="position:absolute;left:0px;top:0px;width:100%;background:black;color:white;font-size:30pt;">')
write('</div><div id="iemarquee2" style="position:absolute;left:0px;top:0px;width:100%;z-index:100;background:black;color:white;font-size:30pt;">')
write('</div></div>')
}
else if (document.layers){
write('<ilayer width='+marqueewidth+' height='+marqueeheight+' name="ns_marquee">')
write('<layer name="ns_marquee2" width='+marqueewidth+' height='+marqueeheight+' left=0 top=0 onMouseover="copyspeed=pausespeed" onMouseout="copyspeed=marqueespeed"></layer>')
write('</ilayer>')
}
}
}
</script>
AJAX->PHP CODE
<?php
session_start();
//NuSoap Library
require_once('./lib/nusoap.php');
$_SESSION['countTotal'] = 0;
//Creating a Client
$client = new nusoap_client('http://xx.xx.x.xxx:xxxx/WSSERVICE/services/SERVICE?WSDL');
$saleItems= $client->call("getItems", array("Sale" => '001'));
$_SESSION['countNew'] = 0;
$countPresale = count($saleItems);
$timer = $countPresale * 3.15;
for($i=0;$i<=count($saleItems);$i++)
{
if ($saleItems[$i]['stateOfItem'] =="Sold" || $saleItems[$i]['stateOfItem'] =="Unsold")
{
$_SESSION['countNew']++;
echo $saleItems[$i]['itemNumber'];
echo $saleItems[$i]['stateOfItem'] . '<br />';
}};
if($_SESSION['countNew'] < $_SESSION['countVehicles'])
{
$_SESSION['countTotal']--;
}
if($_SESSION['countNew'] > $_SESSION['countVehicles'])
{
$_SESSION['countTotal']++;
}
if($_SESSION['countTotal'] < 0)
{
$opx = 3 * ($_SESSION['countItems'] - $_SESSION['countNew']);
echo 'actualheight = parseInt(actualheight) + parseInt(' . $opx . ');';
$_SESSION['countVehicles'] = $_SESSION['countNew'];
}
if($_SESSION['countTotal'] > 0)
{
$opx = 3 * ($_SESSION['countItems'] + ($_SESSION['countNew'] - $_SESSION['countNew']));
echo 'actualheight = parseInt(actualheight) - parseInt(' . $opx . ');';
$_SESSION['countItems'] = $_SESSION['countNew'];
}
?>
Assuming that the variable is not locked away in a different namespace with no interface made available, then of course.
"Ajax" just means "Fetch some data from the server using JS without leaving the page, then run some JS".
There is nothing special that adds extra limitations to what that JS can do.
I ran into some issues with this as well. Probably namespace problems like another answer here suggests.
Rather than figure out the what/when/why, I just used <input name="blah" type=hidden> and then update that and read that with Javascript:
Then, to write the variable:document.getElementById('blah').value='some new value';
To read the variable: somevar=document.getElementById('blah').value;
That has worked every time. Actually figuring out the correct namespace would be a better option, but this works.
EDIT: Are you using any Javascript libraries to do your ajax for you, or just coding it from scratch? I've used xajax, Prototype, and Jquery for things like this. Jquery is my new baby, but 5 years ago already this was dead simple in xajax.
I'm not sure I want to steer you down that path but for a php programmer, xajax is a pretty simple method to learn. Jquery is more powerful and extensible though in my opinion.
EDIT2: Far as I can tell you are returning both HTML and javascript to be executed in the same response. Including a javascript in your response doesn't make it get executed. Perhaps you should be serializing your return with JSON so you can eval your javascript to be executed, and assign your innerHTML separately.
Just for reference, the same thing you could do in xajax with just:
$objResponse->addAssign("idhere","innerHTML", "some html");
$objResponse->addScript("somvar = somevar + someothervar");

Categories

Resources