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

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>';
}
?>

Related

Pass PHP variable from one page to another to get correct item from button [duplicate]

This question already has answers here:
PHP Pass variable to next page
(9 answers)
Closed 1 year ago.
I have 2 pages, content.php & pagecontent.php, and in content.php I display products info from database into table tags and inside has a grid of 2 rows and 3 columns that I echo descriptions of the products into. One of the grids row holds a button with and thumbnail image over it so that it would link or send user to pagecontent.php for that specific product info page. On pagecontent.php the user will be able to add the product/s to a cart/wishlist(not there yet, future stuff).
Ok so far on content.php I've been able to display all products from database, from the query and while loop, works, I was able to change stuff in database and changes would happen on content.php. I've had no success on passing a variable or id with $_GET, and I believe that's what I would want to use for this case. Also don't think my ajax is correct or it's missing things. I was trying to figure out how the button would get the products PartsID (1,2,3,etc...) from database, PartsID is the column name, to later be called when clicked then pass it to pagecontent.php to get correct product info from button. If there's a better way then the way I have the being used then let me know.
content.php
<?php
$stmt = $pdo->query("SELECT * FROM Parts");
while ($product = $stmt->fetch(PDO::FETCH_ASSOC)) {
?>
<td>
<?php
echo '<button type="button" class="testButton" onclick="test()">
<img src="images/APA802AC.jpg">
</button>';
?>
</td>
<td class="td-manufacturer">
<h6>MANUFACTURER</h6>
<p>
<?php
echo $product["Manufacturer"];
?>
</p>
</td>
<script type="text/javascript">
function test(itemid) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200)
{
window.location.assign("pageContent.php").innerHTML = xhr.responseText;
}
}
xhr.open("GET", "pageContent.php?id=" + itemid, true);
xhr.send();
}
</script>
pagecontent.php
This page has tables as well but no grids. I need to get previous page button clicked PartsID(1,2,3,etc...) here and display that products info where I echo $row.
<div class="productInfo">
<h2 class="productTitle">
<?php
echo $row["PartTitle"];
?>
</h2>
</div>
<td>
<?php
echo $row["Availability"];
?>
</td>
<td>
<?php
echo $row["Price"]
?>
</td>
I would really hope for some detailed help please. I've tried all sorts of different variations of code and research, learning as I go with little time I have, new to php and javascript/ajax so go easy on me please. I hope I was clear and makes sense. Thanks!
First of all, your line
window.location.assign("pageContent.php").innerHTML = xhr.responseText;
is not doing what you think it is doing. "location.assign" loads a different page. Haven't tried myself to see if that will through an error to console for the innerHTML dereferencing, but you should check the network tab in your browser, most probably you will see 2 calls to pageContent: one with parameter (your ajax call) and 2nd one without (your location.assign call).
Secondly, if you have a multipage php application, you probably dont need ajax, as the page content is generated on the server side and after that it becomes static. Ajax is more suited for a single page applications with dynamic content.
w/o changing your application code too much, try to remove the ajax call and use only window location:
<script type="text/javascript">
function test(itemid) {
window.location.assign(_your_base_url_ + "pageContent.php?id=" + itemid)
}
</script>
I believe that would allow you to see the parameter on the server side in $_GET query.
P.S. I havn't been doing php lately so the above answer is more or less a concept. You may have to check php documentation for how to access the parameters. And reading some tutorials on this subject is not such a bad idea, as it seems that you do have some gaps in understanding the overall concept of doing web applications with php.

PHP get information from database when echoed html code is clicked

In my code, I am retrieving data from the database using a while loop so i can have all the $FormData['fullname'] in the db.
What i want to do is, have each name display on the page and also have clickable so when someone clicks a name, it gets their user_id and pulls up information about them.
The problem i am having is that I can't figure out a way to make a it so where i can get the user_id when the user clicks a name. I tried putting a "name" in the button attribute and I checked if isset() but that didn't work.
If someone can properly figure out a way for me to basically, display all the fullnames in my database and when someone clicks a name, it pulls up information about them that is stored in the database. Here is my code
$stmtGet = $handler->prepare("SELECT * FROM formdata");
$stmtGet->execute();
while($formData = $stmtGet->fetch()){
echo "<button name='name'>$formData[fullname]</button>";
if($_SERVER['REQUEST_METHOD'] =="POST"){
if(isset($_POST['name'])){
echo "ok";
}else{
echo "bad";
}
}
}
As far i can see you are trying hit a button inside the while loop , i would not say its a bad approach , but i will suggest you not to do that . and from your code i can see you have lack of understanding post and get request learn from here . and other than this you need to know the transition of web url . how its actually works . anyway , i have given a sample code without . i hope it will help you understanding this concept.
$stmtGet = $handler->prepare("SELECT * FROM formdata");
$stmtGet->execute();
while($formData = $stmtGet->fetch(PDO::FETCH_ASSOC)){
$id = $formData['formdataid'];
echo "<a href='somepagename.php?infoid={$id}'>". $formData['fullname']."</a></br>";
}
now in the somepagename.php file or in the same page you can actually show the details information for instance
if(isset($_GET['infoid'])){
$stmt = $handler->prepare("select * from formdata where formdataid='"$_GET['infoid']"'");
$qry = $stmt->execute();
$row = $qry->fetch(PDO::FETCH_ASSOC);
echo "<p>id =".$row['formdataid']."</p></br>";
echo "<p>id =".$row['name']."</p></br>";
echo "<p>id =".$row['email']."</p></br>";
echo "<p>id =".$row['address']."</p></br>";
code is not executed , it may have semicolon or comma error warning . you have to fix those on your own . this example above shown you only the way it works .
if still you have problem ask , or see the documentation
I should stress that this is not production code and you should totally validate the data input coming in before posting queries to your DB. You can do something like this.
<?php
// Connect
$connection = mysqli_connect('localhost', 'username', 'password', 'database','port');
// Grab all users
$sql = 'SELECT * FROM users';
$users = mysqli_query($connection, $sql);
if (($_SERVER['REQUEST_METHOD'] == 'POST') && !empty($_POST['user_id'])) {
$query = "SELECT * FROM users WHERE user_id = {$_POST['user_id']};";
$user = mysqli_fetch_assoc(mysqli_query($connection, $query));
}
?>
// This only runs if our $user variable is set.
<?php if (isset($user)) : ?>
<?php foreach ($user as $key => $value) : ?>
<span><?= print_r($value) ?></span>
<?php endforeach; ?>
<?php endif; ?>
// Display all users in a dropdown and when the button is clicked
// submit it via post to this page.
<form action="<?= $_SERVER['PHP_SELF'] ?>" method="post">
<select name="user_id">
<?php foreach ($users as $user) : ?>
<option value="<?= $user['user_id'] ?>"><?= $user['name'] ?></option>
<?php endforeach; ?>
</select>
<button type="submit">Submit</button>
</form>
This is going to refresh your page every time. If you want to have an interactive page you are going to need to use JavaScript/AJAX to update the page elements without reloading the page. This example just demonstrates how you can achieve this with PHP and HTML.
you need to know about server-side language(php) and client-side language(javascript).
php runs before page loaded. it cannot runs when click something by itself(with ajax, it can).
most interactions without page move runs with javascript.
in your case, there are two methods.
store all information into hidden input or button's attribute. and get them by user_id via javascript.
use ajax to call another php that can select informations you need by user_id.
both use javascript or jquery. so you must learn about them.

Clickable HTML list to query db and output to <div>

Bear with me; this is my first StackOverflow question. I'm having trouble writing a proper algorithm. Perhaps doing all this to "force" it means I'm over-complicating a simple concept, but it's also very likely I'm just unaware of the fix.
I'm building an experimental cookbook that reads from a database and displays in the browser. I created a list (note: NOT a <ul> or <ol> element) that is populated by <span> items generated by a PDO query to the database. These spans reference the name of each recipe in the database.
<p>
<?php
$recList = $pdo->query('SELECT name FROM Recipe');
$rowCount = $recList->rowCount();
echo 'There are ' . $rowCount . ' recipes currently in our database!';
echo '<br /><br />';
while ($row = $recList->fetch()) {
echo '<span class="recName"';
echo '>' . $row['name'] . "</span><br />";
}
?>
</p>
I then created a scrolling div element:
<div id="recWindow">
<!-- Display recipe queried from the database here -->
<?php require("$DOCUMENT_ROOT/$rec_source"); ?>
</div>
I would like the user to be able to click on the recipe names generated by php and the chosen recipe to display within the <div>. Choosing different recipes should not cause the page to reload.
I feel like the answer lies in an AJAX request to a php file listening for a variable containing the recipe to display, but that's where I'm stuck. Somehow I need to pass the php list items a unique identifier that is recognized by javascript, which in turn handles the onclick change in the div by passing that identifier BACK to php to query the database. While typing that out, I'm almost certain that I've over-complicated this entire process.
I thought of using a dropdown select menu and a GET request, but I'd like to retain the clickable names function if possible.
Answers that conclude my proposed method is too "dirty" and point me in a better direction are completely acceptable. I'm happy to provide any necessary information I left out. Thank you so much in advance.
Environment: Virtual LAMP (CentOS7, MariaDB)
Try something like this
<p>
<?php
$recList = $pdo->query('SELECT name FROM Recipe');
$rowCount = $recList->rowCount();
echo 'There are ' . $rowCount . ' recipes currently in our database!';
echo '<br /><br />';
while ($row = $recList->fetch()) {
echo '<span class="recName" data-id="' . $row['id'] . '"';
echo '>' . $row['name'] . "</span><br />";
}
?>
</p>
<div id="recWindow">
<!-- Display recipe queried from the database here -->
<?php require("$DOCUMENT_ROOT/$rec_source"); ?>
</div>
<script type="text/javascript">
$(document).ready(function() {
$("body").on("click", "recName", function() {
//* get id of required recipe
var recId = $(this).attr("data-id");
//* send ajax-request to back-end
$.ajax({
url: "/get-recipe.php",
method: "GET",
data: {
id: recId
},
success: function(respond) {
//* put recipe-data into container
$("#recWindow").html(respond);
}
});
});
});
</script>
I hope, it shows you the main idea

HTML onclick function doesn't call through PHP echo

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);
});

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.

Categories