jQuery is not overwriting text coming from php include - javascript

I have a php file coming from a global assets folder, in the footer I have this:
<?php
include('../global/includes/footer_template.php');
?>
and in that template I have something like this:
<a href="<?php echo $legalUrl;?>"target="_blank">
<?php echo ($isLangSpanish?'Nota Legal':'Legal Notices');?>
</a>
so in the view you will see 'Legal Notices', for one of the pages the client is asking me to uncapitalize the 'N' in Notices. So I did this with jQuery
<?php
include('../global/includes/footer_template.php');
?>
<script type="text/javascript">
$(document).ready(function(){
$('.footer p a').text().replace('Notices', 'notices');
});
</script>
And it works in the browser console:
But I can't see that change in the view.
What can I do?
NOTE:
I can't change the footer template in the assets because it's been used for other projects.

You have to assign the value back.
$(document).ready(function(){
$('.footer p a').text($('.footer p a').text().replace('Notices', 'notices'));
});
a little cleaner:
$(document).ready(function(){
var link = $('.footer p a'),
updatedText = link.text().replace('Notices', 'notices');
link.text(updatedText);
});

Posting an alternative solution using a callback to text(),
$('.footer p a').text(function(){
return $(this).text().replace('Notices', 'notices')
});
.text( function )
A function returning the text content to set. Receives the index position of the element in the set and the old text value as arguments.

Related

How To use PHP variable in jQuery (in Wordpress plugin)

This is wordpress plugin code The following code works, but no text comes into the modal window. Error is this enter image description here
<?php
$phpvariabletext = get_post_meta( $post_id, '_billing_satis_sozlesme', true );
// $phpvariabletext large text along with html codes
?>
<a class="classa" id="view" onclick="openmodal()"> Show Contract </a>
<script type="text/javascript">
var content = '<?php echo $phpvariabletext; ?>';
var newmodal = new tingle.modal();
function openmodal() {
newmodal.open();
newmodal.setContent(content);
}
</script>
You can use PHP variable in JQuery/Javascript easily check below steps
1) Stored PHP variable value in HTML input tag as type hidden
<input type="hidden" value="<?php echo $phpvariabletext;?>" id="phpvariable">
2) After assign variable value in HTML input tag. You can get value in JQuery/Javascript.
<script type="text/javascript">
var content = $('#phpvariable').val();
var newmodal = new tingle.modal();
function openmodal() {
newmodal.open();
newmodal.setContent(content);
}
</script>
Creating extra DOM elements solely to transport a value is needless extra markup.
I always pass php data to javascript as json_encode() output (without manually quoting) because it will automatically double-quote your string and escape any of the double-quotes in the actual data.
<a class="classa" id="view" onclick="openmodal()"> Show Contract </a>
<script type="text/javascript">
let newmodal = new tingle.modal();
function openmodal() {
newmodal.open();
newmodal.setContent(<?= json_encode(get_post_meta($post_id, '_billing_satis_sozlesme', true)); ?>);
}
</script>
The above technique outputs the php value using php "short tags".
P.s. you could also consider removing the inline js function call and use an event listener in your js to keep all of the behaviors/events in one place.

appending elements in jquery

i am trying to append a div to other div here :
<script>if($(window).width()>500){
$("body").append("<?php include('includes/middle.php') ?>");
}
</script>
Which becomes:
<script>if($(window).width()>500){
$("body").append("<div class='middle'>
<div class='middleOne'>
<a href='http://localhost/jhandwa/story/11-illustrations-that-perfectly-capture-how-life-changes-when-we-grow-up'>
<img src='https://files.brightside.me/files/news/part_31/310360/12086810-10111660-1-0-1487765591-1487765607-0-1488442321-0-1488458395-1488458410-650-1-1488458410-650-0c369e17e2-1488484030.jpg'>
<div class='miniTitle'>11 Illustrations That Perfectly Capture How Life Changes When We Grow Up<br /><span>2017-03-17 17:12:36</span></div>
</a>
</div>
<div class='middleOne'>
<a href='http://localhost/jhandwa/story/10-things-you-didnt-know-about-the-us-secret-service'>
<img src='https://www.whitehouse.gov/sites/whitehouse.gov/files/images/first-family/44_barack_obama%5B1%5D.jpg'>
<div class='miniTitle'>10 Things You Didn't Know About<br /><span>2017-03-17 15:15:29</span></div>
</a>
</div>
<div class='middleOne'>
<a href='http://localhost/jhandwa/story/who-is-actually-dumb-and-dumber-after-watching-these-crime-serials'>
<img src='https://s-media-cache-ak0.pinimg.com/originals/36/45/e6/3645e66b26b611a30fabf923f7247d23.jpg'>
<div class='miniTitle'>Who is Actually 'dumb' and 'dumber' after this? <br /><span>2017-02-28 00:00:00</span></div>
</a>
</div>
</div>");
}
</script>
what am i doing wrong here? i feel its something wrong because of double or single quotes.why isn't it working?
Updating my original answer:
First, you need to wrap your code in document.ready(). It should append when the dom is ready.
Second, it is not working because your outputted HTML is on multiple lines. If you look at your console, you would see the following errors:
Uncaught SyntaxError: Invalid or unexpected token
There are many ways to solve this issue, the simplest would be to use template literals, this means you should wrap your code within backtick.
$(document).ready(function () {
if ($(window).width() > 500) {
$("body").append(`<?php include('includes/middle.php') ?>`);
}
});
However, this solution may not be compatible with all browsers as this feature has been introduced in ES6.
A much better way would be to call the sidebar.php via ajax.
$(document).ready(function () {
if ($(window).width() > 500) {
$.get("includes/middle.php", function (data, status) {
$("body").append(data);
})
}
});
This script can not execute because your PHP file have multiple line. And multiple line will make your JS syntax wrong.
You need include this php file in a hidden script, and use jQuery to get this div content and append into body.
And as #Hyder B say, you need put this script execute when document has been ready.
You can try this way:
<div id="included_content" style="display:none">
<?php include('includes/middle.php') ?>
</div>
<script>
$(document).ready(function() {
if($(window).width() > 500){
$("body").append($("#included_content").html());
}
});
</script>
Try this:
if($(window).width()>500){
$.ajax({
url: 'includes/middle.php',
success: function(html) {
$("body").append(html);
}
});
}
Based on this answer and as you directly echo inside the included page, you can use backtick (`) to wrap multiline string in js properly.
<script>
$(document).ready(function() {
if($(window).width()>500){
$("body").append(`<?php include('includes/middle.php'); ?>`);
}
});
</script>

pass parameter with out page reload php

I want to access php id on the same page for this i want something like this:
<a onclick='showDialog_update()' href='follow_event.php?id=$customer->id'\">
but i want to show popup and not want the page to get refresh so i can show my result on my popup on the same page.
i already tried this jquery code but its not working for me
<a href="javascirpt:void(0)" rel='$customer->id' class="showpopup">
$(".showpopup").click(function(ev)
{
var getid = $(this).attr('rel');
alert(getid);
ev.preventDefault();
}
Please try this code.
You must echo the php variable into the a tag
asdf
<!-- jQuery cdn source, can be skipped -->
<script
src="https://code.jquery.com/jquery-1.12.4.min.js"
integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="
crossorigin="anonymous"></script>
<script>
$(
$(".showpopup").click(function(ev)
{
var getid = $(this).attr('rel');
alert(getid);
ev.preventDefault();
})
);
</script>

Random button that reload a div or script not page using jquery or javascript

I'm really new at this and I need a random button on my page that would show a new line of information in a div every time someone click on the random button. I was also wondering if there is over 800 lines is it possible to put it in an outside file as txt or html.
Here is what I got so far and well it doesn't work and I'm getting confuse... Please help
<script type="text/javascript" src="jquery-2.2.0.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#text').hide();
$('a#random').click(function(){
$('#text').toggle();
})
function RndText() {
var rannum= Math.floor(Math.random()*textarray.length);
document.getElementById('#text').innerHTML=textarray[rannum];
}
var textarray = [
"Hello",
"How are you",
"Good Bye"
];
$("#text").load()
})
</script>
<body>
<div id="text">Line to Show</div>
RANDOM
</body>
Uh. Pretty much this:
$('a#random').click(function(){
$('#text').toggle();
RndText(); //you're good
});
Although I will point out that RndText() uses document.getElementById when it could use $("#text") instead. (there's a .html() method that will write the value instead of the .innerHTML property).
document.getElementById is also not currently working because you used "#text" instead of "text", jQuery uses CSS selectors, getElementById does not.
Add execution of RndText when you clicks on Random button.
$('a#random').click(function(){
$('#text').show();
RndText();
})
This will give you a button and you can run this code by clicking the button below. However, I did not quite understand you second part of the question: 800 lines in separate file, what do you wanna do with it? Tell me so that I can helo you further...
Editted:
<?php
$data = file_get_contents('demo.txt');
$lines= split("\n",$data);
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script type="text/javascript">
var textarray = <?php echo json_encode($lines); ?>;
function RndText() {
var rannum= Math.floor(Math.random()*textarray.length);
$('#text').text(textarray[rannum]);
console.log(textarray[rannum]+" "+rannum+" "+textarray.length);
}
$(document).ready(function(){
$('#text').hide();
$('#random').click(function(){
$('#text').show();
RndText();
});
});
</script>
<body>
<div id="text"></div>
<button id="random">RANDOM</button>
</body>

Solution for changing' img id' with 'document.getElementById' when selecting from auto generated list

Solution for changing image id when selecting from auto generated list
This code:
<?php foreach(glob('pano/*.png') as $filename):?>
<li><?php $path_parts = pathinfo ($filename); echo $path_parts['filename'], "\n";?> </li>
<?php endforeach; unset( $filename);?>
Generates a screen with a button for each of the files. The function chgpano:
function chgpano()
{
ima = document.getElementById("tonto");
init();
}
Changes the img Id assigned to variable "ima". The contents of "tonto" need to reflect the image selected.
The following cannot work, but does show the intent:
function chgpano()
{
img id="tonto" src= ('pano/'+ variable with text from button selected)
ima = document.getElementById("tonto");
init();
}
I saw a similar question but it was rejected as being unclear
Try this:
// PHP can look like
$liA = '';
foreach(glob('pano/*.png') as $f){
$path_parts = pathinfo($f);
$liA .= "<li><a href='javascript:chgpano($f)'>{$path_parts['filename']}></a></li>";
}
echo $liA;
// JavaScript can look like + some goodies
var doc = document; // get in the habit of declaring variables
function E(e){
return doc.getElementById(e);
}
var tonto = E('tonto');
function chgpano(f){
tonto.src = f;
}
I would use external JavaScript, putting the <script> tag at the bottom of the body. Alternatively, you would put the <script> tag in the <head> and run onload.
as mentioned in the comment the purpose of id in html is for one single element..
so i would use class or the new data-TAG.
to reuse the php script also for other scripts/sites i would scan the folder and convert everything to json.(simple array containing all the paths of the png's)
here is a example using javascript 1.7 (modern html5 browsers)
to handle multiple elements with one handler.
scanForPNGs.php
echo json_decode(glob('pano/*.png'));
index.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
img{width:100px;}
img.IMA{opacity:0.3;}
</style>
<script>
var box;
function ajax(a,b,c){c=new XMLHttpRequest;c.open('GET',a);c.onload=b;c.send()};
function display(){
box.innerHTML='<img src="'+JSON.parse(this.response).join('"><img src="')+'">';
}
function whatever(e){
e.target.classList.toggle('IMA');// activate & deactivate
//or
//e.target.dataset['IMA']=e.target.dataset['IMA']=='ON'?'OFF':'ON';
}
window.onload=function(){
box=document.getElementsByTagName('div')[0];
box.addEventListener('click',whatever,false);
ajax('scanForPNGs.php',display);
}
</script>
</head>
<body>
<div></div>
</body>
</html>
inside the whatever function you can add whatever proprieties or functions to the element that you click.
in my case i just change the opacity.
the trigger is the image itself.
i did not test this code...to be sure test it with chrome.
example
http://jsfiddle.net/8jeDS/1/
Thanks Guys & Gals. This fixed it:
<?php
foreach(glob('pano/*.png') as $filename):$path_parts = pathinfo ($filename); $id_front = $path_parts['filename'];?>
<li> <a onclick = "javascript:chgpano('<?php echo $id_front ?>')"><?php echo $id_front, "\n";?></a><img id= <?php echo $id_front ?> src= <?php echo$filename ?> style="display:none"></li>
<?php endforeach; unset( $filename);?>
As you can see I put the same variable being used to assign the image id into the function parameter.
Now the variable ima contains the img id
function chgpano(blah)
{
ima = document.getElementById(blah);
init();
}
I had to move the variable difinition out side the div otherwise the function parameter was getting filled before the variable was defined.

Categories

Resources