How do I implement AJAX into CodeIgniter? - javascript

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.

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.

Dynamic pages in Wordpress, using database

I'm making by myself a site and I need some help because I'm not so good... All things I learned just by google, forums and blogs. Now I'm stucked in a part of my site very hard for me.
I will ask you step by step and see if I can complete the site with your help.
Sorry if my english is not perfect, I'm Italian.
So, let's go.
I created the site with WordPress, using a theme. I changed the font (directly in the css and not using the guide because my font was not listed), i customized every part by the panel, plugin and by edit directly the code of pages.
I tell you this so you can understand my level.
If i digit "www.mysite.com/xx" (where "xx" is a page that not exist) it go on the 404 page error.
Well, I edited that page too (404.php in the editor of WordPress) with my personal text. I didn't touch htaccess file.
So now my first purpose come.
I want use the page error for create dynamic pages.
In this page i want to write my text and the "xx" word, so i must get it from the link "www.mysite.com/xx".
It should be easy with Java script but I don't know from where to start...
I need to put that word in a Variable because i will need to process it in a second moment.
This is my 404.php code:
<?php
/**
* The template for displaying 404 pages (Not Found)
*/
?>
<?php get_header(); ?>
<div class="row">
<div class="col-md-9">
<section class="content">
<article>
<h2><?php esc_html_e( 'Attenzione', 'iamsocial' ); ?></h2>
<p><?php
$url1 = 'http://www.example.com';
esc_html_e( 'Correttore in fase di ultimazione.', 'iamsocial' ); ?></p><p><?php esc_html_e( 'Vai alla ', 'iamsocial' ); ?> <?php esc_html_e( 'home page.', 'iamsocial' ); ?></p>
</article>
</section>
</div>
<aside class="col-md-3">
<?php get_sidebar(); ?>
</aside>
</div>
<?php get_footer(); ?>
The part of the database is on the next question.
Thank you for your attention.
You don't need Javascript for this. You can do it in PHP with:
$path = $_SERVER["REQUEST_URI"]
That will return the "xx" part of the URL.
If you only need the last part of the URL, like Steven says, you can explode by / and get the last element:
// URL = site.com/page/xx
$page = explode("/", $_SERVER["REQUEST_URI"]); // = /page/xx
$lastEl = end($page); // = xx

Fetch altered data after page is updated

When update button is submitted a function edit_page() is called. This function alter the database table row with new data entered.
This works fine table altered correctly entries are ok.
But problem is that when update button is submitted
1. Entries is database inserted or altered correctly.
2. But when page reloads content of this updated page remains as it is as previous or like before updation on front end or just after submission.
My code:
<?php
function edit_page()
{
add_cat();
global $page_id;
?>
<?php
if (isset($_GET['page_action']) && ($_GET['page_action'] == 'edit'))
{
$page_id = $_GET['post'];
}
?>
<?php
$page_id = $_GET['post'];
$result = mysql_query("SELECT * FROM pages WHERE page_id = '$page_id'"); //execute the SQL query and return records
$row = mysql_fetch_array($result);
$page_title = $row['page_title'];
$page_content = $row['page_content'];
?>
<form method="post" action="" name="edit_page" class="edit_page">
<h4>Page Title:</h4> <input type="text" name="title" class="title" placeholder="Add title of the Page" required value="<?php echo $page_title;?>"/><br/>
<h4>Page Content:</h4><br/>
<textarea cols="80" id="content" name="content" rows="10"><?php echo $page_content;?></textarea>
<input type="hidden" name="page_edits" value="yes" />
<input type="submit" name="edit_page" class="button" value="Update"/>
<?php
save_edits(); }
function save_edits()
{
if (isset($_POST['edit_page']) && $_POST['page_edits'])
{
$page_id = $_GET['post'];
$page_id = $_GET['post'];
$page_title = $_POST['title'];
$page_content = $_POST['content'];
$date = date('Y-m-d h:i');
$query = "UPDATE pages SET page_title='$page_title', page_content='$page_content', date_gmt='$date' WHERE page_id = '$page_id'";
$result = mysql_query($query) or die("Unable to create Page: " . mysql_error());
}
}
?>
<div class="right_sidebar">
<?php edit_page();?></div>
Finally, my mean is that i just want functionality like wordpress in which when update button is clicked just after that we see updated data.
You're doing PHP the procedural way here. That means the statements are executed one after another so the problem lies in the way you place your statements.
In your code, you are displaying the form first and only then updating it, so that's why the previous values get fetched although update is happening only later.
Solution: The function save_edits() and its call should come first followed by edit_page().
Another important thing in terms of security, you are directly inserting the value you get from the address bar. Right now the way it is, someone can drop your whole table by writing in a piece of code. You could use mysql_real_escape_string() to prevent it (although not totally) or better yet:
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
Lastly, you are not closing your <form> tag.

Clean way to Template an HTML code block that only takes title/content parameters, where content may be large and littered with new-lines

I am using Accordion (jQuery) on my school webserver. Currently, my coding-scheme uses PHP/HTML/CSS/Javascript. I started noticing an opportunity for automation/templating when writing the entries for the Accordion modules. I write the following code:
<h3>Title</h3>
<div class="nobg">
<p class="nobg">
<!-- Entry text -->
</p>
</div>
so I am looking for pointers for the best way to template that code based on the following needs:
Adjustable parameters: Title, Content
When making new modules with a large content 'parameter', the creation of that parameter should maintain readability.
Since I am already on PHP, I was thinking maybe some sort of template function:
<? php accordion_entry("Title", "Entry Text" ?>
But the text is usually a lot of HTML: like the following:
PDF
<p>
The release date is 2007 but the pinout seems to check out (I did some small verifications with my PCB). Also, the reference documents are all valid!
</p>
I would like to write that HTML myself in the designated spot where the module will eventually manifest as a whole. Perhaps even cooler would be something like this:
<accordion-entry title="Title">
PDF
<p>
The release date is 2007 but the pinout seems to check out (I did some small verifications with my PCB). Also, the reference documents are all valid!
</p>
</accordion-entry>
I have no idea how to get started creating such a mechanism, or if it's too much trouble to bother.
I found my temporary solution, until someone comes along with something better! Please review! I am no PHP Expert!! :D
The PHP Function:
<?php
function accordionEntry($title, $entry)
{
echo '<h3>' . $title . '</h3>';
echo '<div class="nobg">';
echo ' <p class="nobg">';
echo $entry; // <!-- Entry text -->
echo ' </p>';
echo '</div>';
}
?>
The PHP function call:
<?php accordionEntry(
"GSM0107IG001 - Integration Manual",
'PDF
<p>
The release date is 2007 but the pinout seems to check out (I did some small verifications with my PCB). Also, the reference documents are all valid!
</p>');
?>
Create a partial, and load your content into it along with settings
accordian.phtml (just use .html if you want, doesn't really matter)
<accordion-entry title="<?php $title ?>">
<?php $content ?>
</accordion-entry>
page.html
<div><?= renderPartial('accordian.phtml',array(
'title'=>'GSM0107IG001 - Integration Manual',
'content' => '<p>your html</p>'
)); ?>
partial.php
function partial($partial, $settings){
//will load html from indicated file, and merge passed settings and content into place before returning all $html
// this allows the reuse of the 'partial()' function for other snippets
$template = file_get_contents($partial);
//$settings should be an array, and then your keys can be extracted as variables that match the $settings variables (such as $title) that exist in the .html partial file
extract($settings); //will assign any keys in your array, such as 'title' to php variables of the same name... so in this case $title, and $content
echo $template;
}

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