HTML onclick function doesn't call through PHP echo - javascript

Originally I had the following to produce a menu using PHP:
<ul>
<?php
$items = mysqli_query($con, "SELECT DISTINCT item FROM table");
while ($row = mysqli_fetch_array($items)) { ?>
<li><a href='#' onclick='myFunction(<?php echo $row['item'] ?>)'><?php echo $row['item'] ?></a></li><? php
} ?>
</ul>
I had this code inside an index.php page surrounded by html. The is to produce a menu from items in a database. In this form it worked fine and called 'myFunction(string)' which is in a seperate global.js file.
function myFunction(string) {
$('#container').load('php/getContent.php', {string: string});
}
getContent.php is similar to the php above. except it uses a where clause in the query which it extracts from the string.
So my problem arose when I went to clean up the code which produces the menu.
I added the following function to global.js
$(document).ready(function() {
$('#menu').load('php/getMenu.php');
});
getMenu.php looks like this:
$items = mysqli_query($con, "SELECT DISTINCT item FROM table");
echo "<ul class='tab'>";
while ($row = mysqli_fetch_array($items) {
echo "<li><a href='#' onclick='myFunction(".$row['item'].")'>".$row['item']."</a></li>";
}
echo "</ul>"
This works correctly in producing the menu items as before except the onclick function no longer works.
Placing an anonymous inline onclick function did work however so I figured it may be the $(document.ready() inside the global.js file causing issues. I moved the $(document).ready() back into index.php in a script tag to check, still not working.
I originally had the script tags as the last elements in the body so I moved them up into the header to check if that changed anything but that also didn't work.
the header tag looks as follows:
<script src='scripts/jquery-3.0.0.js'></script>
<script src='scripts/global.js'></script>
<script>
$(document).ready(function() {
$('#menu').load('php/getMenu.php');
});
</script>
all my php files are in a subfolder called php and all my js files in a subfolder called scripts.
So firslty, does it matter if I have the $(document).ready() in a js file with other functions, does that mess with the other functions?
Secondly any idea on why the function is no longer being called?
Thanks in Advance.

This is a problem I had too. When you generate elements after the DOM fully loads the onclick wont work anymore.
In my case I used:
$('parent of element which is in DOM').delegate('element', 'event', function(){
});
And worked.
Take a look at jQuery API http://api.jquery.com/delegate/
In your case your php should be like:
$items = mysqli_query($con, "SELECT DISTINCT item FROM table");
echo "<ul class='tab'>";
while ($row = mysqli_fetch_array($items) {
echo '<li>'.$row['item'].'<input class="sql_input" hidden="hidden" value="'.$row['item'].'"></li>';
}
echo '</ul>';
And your Javascript:
function load_file(value){
$('#container').load('php/getContent.php', {string: value});
}
$('parent of .tab').delegate('.tab li a', 'click', function(){
var get_value = $(this).find('.sql_input').val();
load_file(get_value);
});

Related

Using Javascript function to hide button inside PHP

I am currently writing a website where I want to hide the the supervisor editing button if the supervisor field = N. I am able to get the query to display the correct output but I can't get the button to hide. Can anyone help me get it to hide whenever the page loads. I also under stand I should be using PDO's but we have not been taught that sadly.
HTML & PHP
<?php
$supervisorstatus = mysql_fetch_assoc($supervisorresult);
echo $supervisorstatus['supervisor'];
if($supervisorstatus !='Y') {
echo '<script type="text/javascript">',
'closesup();',
'</script>'
;
}
?>
JavaScript
function closesup(){
document.getElementById('supervisor').style.visibility="hidden";
}
Supervisor is the element id for the button.
This is how your code would be
<?php
$supervisorstatus = mysql_fetch_assoc($supervisorresult);
echo $supervisorstatus['supervisor'];
if($supervisorstatus['supervisor'] !='Y') {
echo '<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#supervisor").hide();
});
</script>';
}
?>
I gave a example of implementation above but if you need to see it separate Here is the code to hide your supervisor id
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#supervisor").hide();
});
</script>
$supervisorstatus contains an array. You probably want: if($supervisorstatus['supervisor'] !='Y') {

wordpress - php and javascript dont go well together

I know some HTML and CSS but zero JAVA or PHP. I would like to insert LineIt button into my functions.php in WordPress:
The code goes like this:
<img src="imgpath" alt="LINE it!" />
Unfortunately this will display only the line link without my permalink. The_Permalink will be display as text not as dynamically taken URL.
I tried to do something like this:
<img src="linkin" width="[Width of Button]" height="[Height of Button]" alt="LINE it!" />'
But of course that didn't work. Oh and I don't want to use tags <script >.
Could help?
Thanks
Here is the function in my functions.php that I'm trying to modify with custom "LineIT" button:
function show() {
$return = '<aside class="show1 show2">'
. show_content() .
'<div class="show-box">'
. apply_filters('show_filter', show_rander()) .
'<div class="show3">'
. getIcons() .
'</div></div>**<img src="linkin" width="[Width of Button]" height="[Height of Button]" alt="LINE it!" />**<div style="clear:both;"></div>'
. show_content()
. show_content2() .
'</aside>
return apply_filters('show_buttons', $return);
}
according to the document at https://codex.wordpress.org/Function_Reference/the_permalink, the the_permalink() function is usually applied in the template within The Loop. Whereas functions.php is usually provide convenient functions and register them for the future use or register in The Loop.
So put the_permalink() in functions.php might not work as what you expected.
The general template files are like home.php, page.php or category-6.php(which will provide specific template for the category with id as 6).
In these files, the Loop usually is like:
<?php
if(have_posts()){
while(have_posts():
the_post();
the_content();
?>
//here you can add the link
<img src="imgpath" alt="LINE it!" />
<?php
endwhile;
endif;?>
Please refer to this page https://codex.wordpress.org/The_Loop_in_Action for further knowledge of the loop.
if you really want to use the functions.php, I would suggest using the other function get_permalink($id) and get_the_title($id) which will get the permalink of the post by the id and add a function for it. so the function will be:
function get_line($id){
$url = get_permalink($id);
$title = get_the_title($id);
return '<img src="imgpath" alt="LINE it!" />';
}
and then call the function in The Loop of the template.
To learn more about wordpress template, please refer https://developer.wordpress.org/themes/basics/template-hierarchy/
As suggested by #lhrec_106 I have used 3rd option and modified code works like a charm. Thanks!
I have inserted function get_line($id) before my function and then simply entered
. get_line($id) inside my custom function. Button works and share via Line my dynamically generated url.
Thank you

Targeting dynamic id's within a javascript file

In a php file I have tags with dynamic id's.
Example:
<ul id="<?php echo 'ul_'.$xx; ?>">
<li id="test_li">...</li>
</ul>
In a separate JavaScript file I am wanting to use the load function and target that div.
$('<?php echo 'ul_'.$xx; ?>').load('../includes/myphpfile.inc.php #test_li');
My question is, how could I load that php within a JavaScript file?
Notes:- The reason I have it set up this way is due to looping multiple ul's. I just want my ajax file to refresh the li's within the specific ul I am inside of.
Edit: If I use classes instead of Id's it adds my newly inserted rows into all of the ul's with the same class. If I use a plain Id it only works on the first ul. Further explaining why I need to target the way I am.
Unable to find a solution using the path I was on, I looked for alternate methods. Worked out I could add the event in the php file on the submit form button click.
The reason I wasn't using this method at first was because the code was running before it submitted to the DB and therefore was always behind in relation to the new data being submitted.
To my surprise I fixed this by just duplicating the line of code.
<script>
$("<?php echo '#enter_submit_button'.$linkid ?>").click(function(){
/*1*/
$('#<?php echo 'ul__'.$linkid; ?>').load('../includes/pursuit.inc.php <?php echo '#li__'.$linkid; ?>');
$("<?php echo '#insert_new'.$linkid; ?>").fadeOut();
/*2 with delay*/
$('#<?php echo 'ul__'.$linkid; ?>').delay( 800 ).load('../includes/pursuit.inc.php <?php echo '#li__'.$linkid; ?>');
});
</script>
I honestly couldn't say exactly why this works but the logic behind trying the method came from hoping that the double load would pick up the latest submission.
The simplest answer would be to put your JavaScript code into the PHP file inside
<script></script> tags, i.e, just before closing your <body> tag, do this:
<script type="text/javascript">
$('<?php echo 'ul_'.$xx; ?>').load('../includes/myphpfile.inc.php #test_li');
</script>
But if you must use an external js file, then you could do this:
Create a (.php) file and write:
<?php
header("Content-type: application/javascript");
?>
// your js code with php inside (as you would do in HTML)
var othervar='<?php echo $phpVar; ?>';
//<?php //some php ;?>
Then, in your main (html/php) file, put in:
<script src='myjs.php' type='application/javascript'></script>
Hope that solves it.

How do I implement AJAX into CodeIgniter?

I am trying to understand the process of implementing AJAX Query into my CodeIgniter application. The goal is to a have a clickable division (button) in a view. When this div is clicked the AJAX query is called and retrieves 5 movies from my DB and displays them in the view. Right now I have a main page with search button, this search button orders my DB by ID and then retrieves the 1st 5 movies from the DB and displays them on a new page. The function I am trying to implement should retrieve the next 5 movies and replace the 1st 5 movies without reloading the page.
Below is all the code I assume you should take a look at, due to its necessity. Under each part of the code a short summary is provided. And at the end I try to explain what I don't understand and what I am asking you to help with.
Main Page - Controller xampInstallFolder/htdocs/application/obs/controllers/main.php
public function generate_suggestions() {
$this->db->order_by("id","desc");
$pages = $this->db->query('SELECT * FROM movies LIMIT 5');
$data['pages'] = $pages;
$this->load->view('results_v', $data);
}
This function is called when my Search button on the main page is clicked. Right now it doesn't accept any criteria for the query it only retrieves the first 5 movies in the db. Then I take the movies and store them in the pages array and load the new view with the array provided in data
Results Page - View *xampInstallFolder/htdocs/application/obs/views/results_v*
<div id="listA">
<table>
<!-- Function that splits the array in $pages into the first 5 movie suggestions -->
<?php foreach ($pages->result() as $row): ?>
<a style="display:block" href="<?php echo base_url('core/detail/'.$row->id) ?>">
<div id="suggested" onmouseover="" style="cursor: pointer;">
<div id="info">
<p><b><?php echo $row->name ?></b></p>
</div>
<div class="details">
<p><?php echo $row->summary ?></p>
</div>
</div
</a>
<?php endforeach; ?>
</table>
</div>
<div id="next_btn" style="display: block;">
<p>Click here to display next 5 movies</p>
</div>
I have a div listA where I display the 5 movies using a for each loop on the pages array. I have much more div and information, but I was trying to keep it simple.
Javascript xampInstallFolder/htdocs/ASSETS/obs/js/myscripts.js
$( "#next_btn" ).click(function() {
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("listA").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getnext5.php?q="true);
xmlhttp.send();
});
In the head of my results view I link the javascript with this function. It triggers when the next_btndiv is clicked. I got the code from w3schools and from what I understood you need to provide the element in which the result is displayed (listA) and the file where the query is stored (getnext5.php)
getnext5.php Where do I put this file?
$con = mysqli_connect('localhost','root','root','obs2');
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"obs2");
$sql="SELECT * FROM user WHERE id > 5";
$result = mysqli_query($con,$sql);
echo "<table>";
while($row = mysqli_fetch_array($result))
{
<a style="display:block" href="<?php echo base_url('core/detail/'.$row->id) ?>">
<div id="suggested" onmouseover="" style="cursor: pointer;">
<div id="info">
<p><b><?php echo $row->name ?></b></p>
</div>
<div class="details">
<p><?php echo $row->summary ?></p>
</div>
</div
}
echo "</table>";
Here is the core function. I tried to adjust the code from w3schools, but I am not sure if it is correct. My DB is called obs2, but I am not sure if I should have it in both mysqli_connect and mysqli_select_db statements. I also know that I have to figure out how to make it always load the next 5 movies in the list, but right now I just force it on id>5. And then I have the style for the $result. I think the table and `while loop are coded properly, but I don't know how to turn the divs, anchors and original php echoes into the same syntax.
If you made this is far thank you very much for reading through. I'd say the only part I need help with is the getnext5.php. Mostly the syntax. And location, where should the getnext5.php file be stored? I don not think that the other parts of the code are wrong. But obviously if you spot anything in there please let me know as well. Again thanks for reading. I'm looking forward to your replies. If you'd need any other information just ask for it Ill add it.
I only read through the last script, and I corrected some mistakes you made. You can put that file anywhere pretty much. You can copy the code and paste it into a controller class or a views page.
<?php // I just decided to start here
mysqli_select_db($con,"obs2");
$sql="SELECT * FROM user WHERE id > 5"; # This is an integer, no quotes necessary.
$result = mysqli_query($con,$sql);
echo "<table>";
while($row = mysqli_fetch_array($result))
{
?> <!-- Note how we stop php right before we start printing html, since you have nested php tags throughout this block of markup -->
<a style="display:block" href="<?=base_url('core/detail/'.$row->id)?>">
<div id="suggested" onmouseover="" style="cursor: pointer;">
<div id="info">
<p><b><?=$row->name?></b></p>
</div>
<div class="details">
<p><?=$row->summary?></p> <!-- Protip, you may use <? and ?> instead of <?php and ?>. You may also use <?= as a shortcut to the "echo" function -->
</div>
</div>
<?php
} // We are opening up our PHP tags again
echo "</table>";
?>
It seems that you're kindof all over the place with your code. Instead of answering your question specifically, I'm going to give you some advice as to how you can use AJAX with codeigniter much easier. I'm not saying this is the best solution, but it's much more organized and clean that what you have going on. Hopefully it will point you on the right direction.
Let's start from the backend and then move towards the front.
First, a method in a controller which queries the movies in the database. Notice the parameters which allow us to ask for any subset of movies, and not just the first 5. (And yes, I'm only including the important lines of code instead of everything.)
public function generate_suggestions($start = 0, $count = 5) {
$pages = $this->db->query('SELECT * FROM movies LIMIT ' . $start . ',' . $count);
// send back the view as a simple HTML snippet (the <table>, perhaps?)
}
Now we need some Javascript that can call this function on the server. Since the function sends back an HTML snippet, we can just stick that snippet of html code into the page. JQuery makes all of this very easy, so you can avoid the complicated XMLHttpRequest stuff.
<script type="text/javascript">
var nextstart = 6;
var movies_per_page = 5;
$( "#next_btn" ).click(function() {
// this next line makes the ajax call for us, and the inline function
// is called when the response comes back from the server
$.get("controller/generate_suggestions/"+nextstart+"/" + movies_per_page,
function(data) {
// data is what comes back from the ajax call
// here it is the snippet of html, so let's display it as is
$( "#listA" ).html(data);
nextstart += movies_per_page; // so that the next click will load the next group of movies
});
});
</script>
Now we just need to populate the table when the page first loads, and you can do that by calling the same ajax call on page load with a similar $.get ajax call.
Once you understand all of this and have it working, then you should look into JSON, as it is a much better way of transferring data with ajax. And jQuery makes working with JSON much easier, too.

JQuery not changing the content of div from even numbered links?

Thanks for taking the time to look at this post.
So I have managed to do my task to a point.
I am pulling data from a database called posts with the following fields: id, account_name, data, heading, subheading, videos, voice_notes, music, images, post_date, date_for_post.
So This is the process:
1 - Pull data from db and put into array
2 - Make unordered list from array with links
3 - when link is clicked, fill content div with that posts data.
Now it will load the specific posts data on odd numbered links, but on even numbered links it wont load the data into the container? using the same method? I have re-ordered the lists and still, even numbered list items just wont work. Am I doing something wrong?
I have also tried putting in a blank list item in between the posts to see if it were the list items themselves that were not calling the function, but it seems that it is only the even links.
I don't know how else to explain it, here is my code:
<?php
$connection=mysql_connect('localhost', 'username', 'password');
if (!$connection) { die('Not connected : ' . mysql_error());}
// Set the active MySQL database
$db_selected = mysql_select_db('dbname', $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
$query = "SELECT * FROM posts";
$result = mysql_query($query);
if(!$result){
die('Invalid query' . mysql_error());
}
$posts = array();
while($line = mysql_fetch_array($result, MYSQL_ASSOC)){
$posts[] = $line;
}
?>
<!doctype html>
<html>
<head>
<script type="text/javascript" src="js/ajax.js"></script>
<script type="text/javascript" src="js/content.js"></script>
</head>
<body>
<div id="content">some data</div>
<div id="links">
<ul>
<?php
foreach ($posts as $post) {
$data = "'".$post['data']."'";
echo '<li>'. $post['date_for_post'] .'</li>';
}
?>
</ul>
</div>
</body>
and the getContent function:
function getContent(element, data){
$(element).text(data);
}
I cannot figure out why. here is a graphical representation of whats happening:
I have tried inserting black list items to see if it was the actual even list items not calling the function, but it is the even list items with the content inside that wont work, if that makes sense?
Please help as I have no clue what is going on and how to fix it.
Thanks in advance!
UPDATE
it seems to be that the longer posts dont display, the shorter do. I have the data type in the database set to text, not varchar. So where is the issue with size? Is there a maximum size I am allowed to put through the JQuery function? Or in the database? Because it shows in the database, but not on the post
I think the problem is with quotes and double quotes here in your code:
$data = "'".$post['data']."'";
echo '<li>'.$post['date_for_post'] .'</li>';
Check the source of generated HTML page. There should be incorrect 'li' tags. I suggest change your code to this:
$data = $post['data'];
echo '<li>'.$post['date_for_post'] .'</li>';
Hope it helps.
Also, check if the quotes in text from database are causing this problem.
It's hard to see what's going on, try to provide a jsfiddle. Even though you are using php, you can create a manual feed of json data and test out the javascript. To make it less confusing, have the data stored in a ...
<script>
$(document).ready(function () {
var dbObj = <?php $post ?> // $post object to be formatted in json
var render;
for (obj in dbObj) {
render = render + '<li><a href="#" onclick=getContent("#content", ' + obj.data + '");>' +obj.date+ '</a></li>'
$('#links ul').append(render);
});
</script>
If that works and you really want to have the php print out the list, then you can replace it with the php foreach; these days, developers are allowing the client-side to render templates/html and at least you'll know the js works this way! :-)
<?php
foreach ($posts as $post) {
echo '<li><a href="#" onclick=getContent("#content", "'. $post["data"] .'");>'. $post['date_for_post'] .'</a></li>';
}
?>

Categories