I have a simple webpage which generates a random quote from my database upon refreshing the page. I wish to implement some AJAX and JQuery in order to generate quotes via the button rather than having to refresh the page. I have done some research but I am not sure how to implement this in Codeigniter. My current code is below...
Page controller:
public function index() {
$this->load->model('quote_model', '', TRUE);
$data['quotes'] = $this->quote_model->getRandom();
$this->load->view('home', $data);
}
The view:
<?php include ('layout/header.php'); ?>
<div class="container-fluid">
<div class="row">
<div class="col-md-4 quote-holder">
<img src="application/assets/alan1.jpg" alt="..." class="img-circle img-responsive">
<br>
<blockquote class="text-center">
<p><?php echo $quotes[0]['quote']; ?></p>
<footer class="text-center"><?php echo $quotes[0]['character_name']; ?> in <cite title="Source Title"><?php echo $quotes[0]['series_name']; ?></cite></footer>
</blockquote>
<button type="button" class="btn btn-default center-block">Generate quote</button>
</div>
</div>
<?php include ('layout/footer.php'); ?>
Here is the function in the model I am retrieving the data from:
function getRandom() {
$query = $this->db->query("
SELECT * FROM quotes, characters, series
WHERE quotes.series_id = series.series_id AND quotes.character_id = characters.character_id
ORDER BY rand()
LIMIT 1
");
return $query->result_array();
}
Should I simply be using something like this?
$("button").click(function(){
$.get( "Page/index", function( data ) {
//output data to page element...
}
});
getI would do something like: controller:
public function callme()
{
$this->load->model('quote_model);
$data['quotes'] = $this->quote_model->getRandom();
}
Then in my footer:
condole.log("click button")
var_url = "controller/callme" // the url to the controller and method
$.get({
url: url
})
But meh, im bad at programming and even worse at jquery :D
Make hidden input for offset
<button onclick="showmore()" value="showmore" />
<input type="hidden" name="offset" id="offset" value="15"/>
Now Your Ajax Call
function showmore(){
$.ajax({
url:my_controller/showmore,
data:{
offset :$('#offset').val()
},
type:json,
success :function(data){
$('#show-more').prepand(data.view)
$('#offset').val(data.offset)
}
})
}
Your Controller
function showmore(){
$limit = '10';
$offset = $this->input->get('offset');
$result = $this->yourmodel->getdata($offset,$limit);
$data['view'] = $result;
$data['offset'] =$offset +10;
echo json_encode($data);
}
Your Model
$query = $this->db->get('your_table', $limit, $offset);
$data=$query->result_array();
return $data;
Related
I have a div which contains a button(Book it).When I press the button I want to add to the current url the id of the item I clicked on.Then get that id to pop up a box with clicked item data without refreshing the page, because I need to pop up in the current page.
Here it gets the treatments Id
<div class="treatments">
<ul>
<?php
global $treatments;
foreach($treatments as $treatment){
echo ' <li>'.$treatment['name'].'</li>';
};
?>
</ul>
<div class="line"></div>
</div>
<div class="treatment-items">
<?php
global $iController;
$items;
if(isset($_GET['treatmentID'])){
$items = $iController->getItemByTreatmentId($_GET['treatmentID']);
}else{
$items = $iController->getItemByTreatmentId(4);
}
foreach($items as $item){
echo '
<div class="col-30 items">
<div>
<p>'.$item['id'].'</p>
<img src="'.$item['img_url'].'" alt="'.$item['name'].'" />
<h3>'.$item['name'].'</h3>
<p>'.$item['time'].' min</p>
<p>'.$item['price'].'$</p>
<input type="hidden" id="hidden_input" name="id_item" value="'.$item['id'].'">
<a class="bookBtn" id="btn"><button>BOOK IT</button></a> // when I press this button I want that box to pop up
</div>
</div>
';
}
?>
</div>
Pop up box
<div class="bookDetails">
<div class="details">
<?php
global $iController;
$itemm;
if(isset($_GET['id_item'])){
$itemm = $iController->getItemById($_GET['id_item']);
}
echo'
<h1>Book your treatment</h1>
<p>Treatment Name : '.$itemm['name'].'</p>
<p>Treatment Time :'.$itemm['time'].' </p>
<p>Treatment Price : '.$itemm['price'].'</p>
';
?>
<form action="" method="POST">
<label for="date">Choose your date:</label>
<input type="date" for="date" name="date"><br>
<input type="submit" value="Cancel" id="cancel">
<input type="submit" value="Book Now">
</form>
Jquery code
$(".bookBtn").click(function(){
$(".bookDetails").show();
})
getItemById function
public function getItemById($id){
$sql="SELECT * FROM treatments_item WHERE id=$id";
echo $id;
$items = mysqli_query($this->connection,$sql);
$returnArray = array();
if($items){
while($row = mysqli_fetch_assoc($items)){
array_push($returnArray, $row);
}
return $returnArray[0];
}else{
echo'It doesn't work';
}
}
You can use ajax or mix php and javascript like this:
<script>
$(document).ready(function() {
<?php session_start(); ?>//Remove session_start
if (!<?php $_GET(['id'])?'true':'false'; ?>) {
alert something
} else {
something ..
}
});
</script>
hope this was helpful. :)
<div class="treatment-items">
<?php
global $iController;
$items;
if(isset($_GET['treatmentID'])){
$items = $iController->getItemByTreatmentId($_GET['treatmentID']);
}else{
$items = $iController->getItemByTreatmentId(4);
}
foreach($items as $item){
echo '
<div class="col-30 items">
<div>
<p>'.$item['id'].'</p>
<img src="'.$item['img_url'].'" alt="'.$item['name'].'" />
<h3>'.$item['name'].'</h3>
<p>'.$item['time'].' min</p>
<p>'.$item['price'].'$</p>
<input type="hidden" class="id_item" value="'.$item['id'].'">
<div class="bookBtn"><button>BOOK IT</button></div> // when I press this button I want that box to pop up
</div>
</div>
';
}
?>
Note: Never use id same name in one Page i.e., id="hidden_input" // In for loop same name will be generated. It will create bug down the line. Same goes for Input name, instead use class.
$(document).ready(function(){
$('body').on('click','.bookBtn',function(){
var treatmentID = $(this).siblings('.id_item').val();
// $(this) --> it will read the data of the property you have clicked
// .siblings --> adjacent class with name ('.id_item')
$.ajax({
url: 'treatments.php',
type: "get", //send it through get method
data: {
treatmentID: treatmentID
},
success: function(response) {
//operation to show the data in div
//e.g., $('#divId').html(data.name);
$(".bookDetails").show();
}
});
})
})
I have created an image gallery using the PHP code below, which will retrieve the images from a database. Now I want to add a delete symbol to the images so that I can delete it after getting retrieved from the database. Kindly help me out. How can i do this?
<div class="header">
<h2>
GALLERY
<!--<small>All pictures taken from unsplash.com</small>-->
</h2>
<hr/>
<div class="body">
<div id="aniimated-thumbnials" class="list-unstyled row clearfix">
<?php
//Include database configuration file
include('dbConfig.php');
//get images from database
$query = $db->query("SELECT * FROM images ORDER BY uploaded_on DESC");
if($query->num_rows > 0){
while($row = $query->fetch_assoc()){
$imageThumbURL = 'images/thumb/'.$row["file_name"];
$imageURL = 'images/'.$row["file_name"];
?>
<a href="<?php echo $imageURL; ?>" data-fancybox="group" data-caption="<?php echo $row["title"]; ?>" >
<img src="<?php echo $imageThumbURL; ?>" alt="" />
</a>
<?php }
} ?>
</div>
</div>
</div>
you can add a delete button simply like
<?php
//Include database configuration file
include('dbConfig.php');
//get images from database
$query = $db->query("SELECT * FROM images ORDER BY uploaded_on DESC");
if($query->num_rows > 0){
while($row = $query->fetch_assoc()){
$imageThumbURL = 'images/thumb/'.$row["file_name"];
$imageURL = 'images/'.$row["file_name"];
?>
<a id="imageid-<?=$row[0]?>" href="<?php echo $imageURL; ?>" data-fancybox="group" data-caption="<?php echo $row["title"]; ?>" >
<img src="<?php echo $imageThumbURL; ?>" alt="" />
<div class="delete" data-imgId="<?=$row[0]?>">Delete</div>
</a>
<?php
}
}
?>
then handle the click of that button and an ajax call like
$(".delete").click(function(e){
var rowId = e.target.dataset.imgId;
$.ajax({
method: 'DELETE',
url: "", // url to delete
data: {image_id: rowId}
success: function(){
$('imageid-'+rowId).hide();
}
});
});
here it will pass the image id as a parameter to the api call, and will hide the image once the api call is success.
if($query->num_rows > 0) {
while($row = $query->fetch_assoc()) {
$imageThumbURL = 'images/thumb/'.$row["file_name"];
$imageURL = 'images/'.$row["file_name"];
?>
<a href="<?php echo $imageURL; ?>" data-fancybox="group" data-caption="<?php echo $row["title"]; ?>" >
<img src="<?php echo $imageThumbURL; ?>" alt="" /></a>
<!-- HERE YOU CREATE SPAN AND GIVE IMAGE ID AS DATA ID
<span class="deleteImage" data-id="<?=$row[0]?>">Delete Image</span>
<?php }
And Ajax Call is As follow
$(".deleteImage").click(function(){
$.ajax({
//PAGE THAT DELETE IMAGE
url: "delete_image_page.php",
context: document.body,
data: {data:data}
success: function(){
//ON SUCCESS WHAT YOU WANT TO DO
$(this).addClass("done");
}
});
});
NOTE: For more information read this Documentation.
And you should have to readthis post before asking this type of question.
This is a small example. Basically, on a click of a button you would call an AJAX method to send the image name you want deleted. The request needs to be sent to another PHP file that will receive the request, process it, and return a response. Based on the response we get we will know if the method was successful.
You need an additional Javascript file to hold the AJAX function, and a additional PHP file to handle the request and return a response.
Your PHP file:
<div class="header">
<h2>GALLERY</h2>
<!--<small>All pictures taken from unsplash.com</small>-->
<hr/>
<div class="body">
<div id="aniimated-thumbnials" class="list-unstyled row clearfix">
<?php
//Include database configuration file
include('dbConfig.php');
//get images from database
$query = $db->query("SELECT * FROM images ORDER BY uploaded_on DESC");
if($query->num_rows > 0)
{
while($row = $query->fetch_assoc())
{
$imageThumbURL = 'images/thumb/'.$row["file_name"];
$imageURL = 'images/'.$row["file_name"];
echo '<div class="imageContainer">
<a href="'.$imageURL.'" data-fancybox="group" data-caption="'.$row['title'].'" >
<img src="'.$imageThumbURL.'" alt="" />
</a>
<input type="button" onclick="deleteImage(\''.$row["file_name"].'\')" value="Delete" />
</div>';
}
}
?>
</div>
</div>
</div>
The Javascript file:
// Send the `fileName` of the image
function deleteImage(fileName)
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
// This `if` underneath is success. It means we got a response back
if (this.readyState == 4 && this.status == 200)
{
if(this.responseText == "OK")
{
alert('Success, deleted: ' + fileName + ' Response: ' + this.responseText);
}
else if(this.responseText == "Not OK")
{
alert('Picture: ' + fileName + ' was not deleted.');
}
}
};
// For example you send a request to deleteImage.php sending `fileName` info
// - deleteImage.php just needs to echo the response to answer back
xhttp.open("GET", "deleteImage.php?fileName=" + fileName, true);
xhttp.send();
}
The other PHP file, deleteImage.php (the AJAX request receiver):
<?php
$con = ... // Here goes DB connection data
if(isset($_GET['fileName']) && $_GET['fileName'] != '')
{
// Clean the input
$clean['fileName'] = mysqli_real_escape_string($con, $_GET['fileName']);
// Do something
}
// if successful echo 'OK';
// if not successful echo 'Not OK';
?>
I have some url which i add some item to another page (cart page) but by refreshing page and it works fine, now i tried to do it with Ajax, so i created an ajax function to call this URL it works and it adds my item.
Now the problem is i have to reload the other page (cart page) to see the product. So how to do to refresh this page after adding the item, i mean after calling this URL.
The Url : <?php echo Mage::helper('checkout/cart')->getAddUrl($_product, $params); ?>
cart.phtml
...
<div class="row">
<div class="col-md-6">
<div class="product-qty">
<div class="custom-qty">
<div class="btn-plus">
<button type="button" class="reduced items" onclick="minusQty('<?php echo $_product->getId() ?>')">
<i class="fa fa-minus"></i>
</button>
<input name="qty" id="qty-<?php echo $_product->getId()?>" maxlength="12" value="1" title="Qté" class="input-text qty" type="text">
<button type="button" class="increase items" onclick="plusQty('<?php echo $_product->getId() ?>')">
<i class="fa fa-plus"></i>
</button>
</div>
</div>
</div>
</div>
<?php $params = array('qty'=>2) // the input value ?>
<div class="col-md-6">
<button type="button" title="<?php echo $this->__('Add') ?>" class="button btn-cart pull-left-none" onclick="addToCartAjax('<?php echo Mage::helper('checkout/cart')->getAddUrl($_product, $params); ?>')" >
<span><span><?php echo $this->__('Add') ?></span></span>
</button>
</div>
</div>
//JS PART
<script type="text/javascript">
function addToCartAjax(addUrl) {
jQuery.ajax ({
url: addUrl,
type : 'GET',
})
}
</script>
EDIT:
Content of cart.phtml
<div class="row">
<div class="col-main col-lg-12">
<div class="cart">
<fieldset>
...
<tbody>
<tr class="first odd"><td>Item1</td></tr>
<tr class="last even"><td>Item2</td></tr>
</tbody>
...
</fieldset>
</div>
</div>
</div>
EDIT2:
Action controller
public function addAction()
{
if (!$this->_validateFormKey()) {
$this->_goBack();
return;
}
$cart = $this->_getCart();
$params = $this->getRequest()->getParams();
try {
if (isset($params['qty'])) {
$filter = new Zend_Filter_LocalizedToNormalized(
array('locale' => Mage::app()->getLocale()->getLocaleCode())
);
$params['qty'] = $filter->filter($params['qty']);
}
$product = $this->_initProduct();
$related = $this->getRequest()->getParam('related_product');
/**
* Check product availability
*/
if (!$product) {
$this->_goBack();
return;
}
$cart->addProduct($product, $params);
if (!empty($related)) {
$cart->addProductsByIds(explode(',', $related));
}
$cart->save();
$this->_getSession()->setCartWasUpdated(true);
/**
* #todo remove wishlist observer processAddToCart
*/
Mage::dispatchEvent('checkout_cart_add_product_complete',
array('product' => $product, 'request' => $this->getRequest(), 'response' => $this->getResponse())
);
if (!$this->_getSession()->getNoCartRedirect(true)) {
if (!$cart->getQuote()->getHasError()) {
$message = $this->__('%s was added to your shopping cart.', Mage::helper('core')->escapeHtml($product->getName()));
$this->_getSession()->addSuccess($message);
}
$this->_goBack();
}
} catch (Mage_Core_Exception $e) {
if ($this->_getSession()->getUseNotice(true)) {
$this->_getSession()->addNotice(Mage::helper('core')->escapeHtml($e->getMessage()));
} else {
$messages = array_unique(explode("\n", $e->getMessage()));
foreach ($messages as $message) {
$this->_getSession()->addError(Mage::helper('core')->escapeHtml($message));
}
}
$url = $this->_getSession()->getRedirectUrl(true);
if ($url) {
$this->getResponse()->setRedirect($url);
} else {
$this->_redirectReferer(Mage::helper('checkout/cart')->getCartUrl());
}
} catch (Exception $e) {
$this->_getSession()->addException($e, $this->__('Cannot add the item to shopping cart.'));
Mage::logException($e);
$this->_goBack();
}
}
I assume when you add an item to the cart you get some kind of response from your server about current items of the cart, if not you have to implement that on the server side first
add this to your function :
function addToCartAjax(addUrl){
$.ajax({
url: addUrl,
type: 'GET',
})
.done(function(response ) {
//response - this is the response from the server
});
}
I don't know exactly what your server returns if it is html than in .done closure do this :
.done(function(response ) {
// response - this is the response from the server
$('.YourCartContainer').html(response);
});
so if your server returns an html snippet that contains your cart items than you should insert in as html into your cart div container , but if the server returns a Json response with items than you have to loop through them with jquery and format appropriately here an example , however again I don't know what your server returns so just apply the technique :
.done(function(response ) {
// response - this is the response from the server
var htmlResult = '';
$.each(response, function( item ) {
htmlResult += '<p>'+ item.name + '</p><br>'
});
$('.YourCartContainer').html(htmlResult);
});
So here I looped through the json and created some simple html where you get all the item names that are inside the cart, hope this helped ! if You need more info regarding your case specifically than please post what your server response looks like !!
How do I let AJAX know what I have checked with checkbox? I have a list of categories that are selected from a database. So how do let the AJAX know what I have checked?
This is my search PHP:
<div class ="search-category-container">
<div class ="search-category-header featured-header">
<label class ="featured-font">category</label>
</div>
<div class ="search-category-content">
<?php
$result=mysqli_query($connection,"SELECT * FROM category");
while($row= mysqli_fetch_array($result)) { ?>
<label class="checkbox category-list ">
<input type="checkbox" name="category_list[]" value="<?php echo $row['name']; ?>" form="search-form"><?php echo $row['name']; ?>
</label>
<?php
}
?>
</div>
</div>
This is my search function using on search before without AJAX. Now I was trying to use AJAX to get data can I use back the function?
<?php
if($filter == "post" && $time == "all" && $status == "all" && isset ($_POST['category_list'])) {
foreach ($_POST['category_list'] as $category) {
$result = mysqli_query($connection, "SELECT * FROM category WHERE name IN ('$category')")or die(mysqli_error($connection));
while($row= mysqli_fetch_array($result)) {
$getCategory = $row['id'];
$getPostIDRow = mysqli_query($connection, "SELECT * FROM post_category WHERE category_id = '$getCategory'") or die(mysqli_error($connection));
while($row2= mysqli_fetch_array($getPostIDRow)) {
$getPostID = $row2['post_id'];
$result2 = mysqli_query($connection,"SELECT * FROM post WHERE title LIKE '%$search%' AND id = '$getPostID'") or die(mysqli_error($connection));
$count2 = mysqli_num_rows($result2);
if($count2>0) {
while($row2= mysqli_fetch_array($result2)) {
$postID = $row2['id'];
$result3 = mysqli_query($connection, "SELECT * FROM user_post WHERE post_id = '$postID'") or die(mysqli_error($connection));
while($row3 = mysqli_fetch_array($result3)) {
$getUserName = mysqli_query($connection, "SELECT * FROM user WHERE id = '".$row3['user_id']."'")or die(mysqli_error($connection));
while($row4 = mysqli_fetch_array($getUserName)) {?>
<div class ="post-container" id="search-container">
<div class ="post-header-container">
<div class ="post-header">
<a href ="post.php?id=<?php echo urlencode($row2['id']);?>&user=<?php echo $row3['user_id']; ?>">
<p class ="post-header-font"><?php echo ($row2['title']); ?></p>
</a>
</div>
<div class ="post-user">
<p class ="faded-font">by : <?php echo $row4['username']; ?></p>
</div>
</div>
<div class ="post-content-container">
<p class ="post-content-font">
<?php echo ($row2['summary']); ?>
</p>
</div>
<div class ="post-info-container">
<div class ="post-info">
<span class ="glyphicon glyphicon-eye-open"> views: <?php echo ($row2['views']);?></span>
</div><div class ="post-info">
<span class ="glyphicon glyphicon-pencil"> answers:</span>
</div><div class ="post-info">
<span class ="glyphicon glyphicon-ok"> status: <?php echo ($row2['status']);?></span>
</div>
</div>
</div><?php
}
}
}
}
}
}
}
?>
This is AJAX search function
$(document).ready(function(){
function search() {
var searchWord = $("#search").val();
var filter = $("#filter:checked").val();
var time = $("#time:checked").val();
var status = $("#status:checked").val();
$.ajax({
type:"post",
url:"searchFunction.php",
data:"search="+searchWord+"&filter="+filter+"&time="+time+"&status="+status,
success:function(data) {
$("#searchContainer").html(data);
$("#search").val("");
}
});
}
$("#searchButton").click(function(){
search();
});
$("#search").keyup(function(e){
if(e.keyCode == 13) {
search();
}
});
});
To answer you ajax question I highly recommend changing your code to use the 'form' DOM for user experience and easier maintenance, just fyi and use the serialize function which will also send out the 'checked' checkboxes.
https://api.jquery.com/serialize/
function search() {
var postData = $('myForm').serialize(); // i.e <form id="myForm">
$.ajax({
type:"post",
url:"searchFunction.php",
data: postData,
success:function(data) {
$("#searchContainer").html(data);
$("#search").val("");
}
});
}
That will do all the work for you automatically instead of having to run a bunch of jQuery selection calls and putting together the HTTP query your self. If you ever need to know what your ajax is running. Go in inspector mode of your browser and look for "Network" tab, click that and you should see the ajax call to that search file, with everything you need to know. What HTTP request and response headers are and body.
P.s make sure you return false on the submit event and that the name of the fields on your HTML form match the $_POST key names for the ajax.
$("#myForm").on('submit', function(){
search();
return false;
});
Good luck!
First time AJAX attempt.....
I am attempting to update a based on a selection made with a button.
I am currently just alerting the ID back, as that is all I can figure out what to do.
Is it possible to put the file my_page.php into the div with class "populated_info"?
Then when I press a different button, the page will function will run again, and populate the div with the new result. I have the my_page.php already built and running based on the ID, just can't get it to render in the correct place.
HTML:
<form name="gen_info">
<div class="body">
<div class="row">
<div class="col-md-2">
<table width="100%" class="border_yes">
<tr>
<td>
Last Name, First Name
</td>
</tr>
<?php
$result = mysqli_query($conn,"SELECT * FROM general_info");
while($row = mysqli_fetch_array($result))
{
$CURRENT_ID = $row['ID'];
$firstName = $row['firstName'];
$lastName = $row['lastName'];
?>
<tr>
<td>
<button type="button" class="btn btn-default custom" onclick="function1('<?php echo $CURRENT_ID;?>')"><?php echo $lastName.', '.$firstName; ?></button>
<!-- button that will run the function -->
</td>
</tr>
<?php
}
?>
</table>
</div>
<div class="col-md-10 populated_info"> <!-- WHERE I WOULD LIKE THE UPDATED INFORMATION -->
</div>
</div>
</div>
</form>
AJAX:
<script>
function function1(ID) {
$.ajax({
type: "POST",
url: "functions/my_page.php",
data: "ID="+ID,
success: function(resp){
alert(resp); //how to get this to put the page back into the right spot?
},
error: function(e){
alert('Error: ' + e);
}
});
}
</script>
Your approach:
With regards to your button, I'd suggest separating the inline Javascript handler to keep your HTML and Javascript separate. I'll use a custom data attribute to store the ID here:
<button type="button" class="btn btn-default custom mybutton" data-id="<?php echo $CURRENT_ID;?>">
<?php echo $lastName . ', ' . $firstName; ?>
</button>
Then jQuery:
$('.mybutton').click(function() {
var ID = $(this).data('id');
function1(ID);
});
Your AJAX request:
You can shorten that whole function and use $.load() to get the data into your div:
function function1(ID) {
// Get the output of functions/my_page.php, passing ID as parameter, and
// replace the contents of .populated_info with it
$('.populated_info').load('functions/my_page.php', { ID: ID });
}
Doesn't look like you need a callback function here, but if you do you can put it in after the data parameter. A useful application of a callback here might be for your error handler. See here how to implement one.
An an aside, if you're just getting data, you should probably be using the GET HTTP method instead of POST.
if you successfully get the response from the server just replace alert(resp) with $('.populated_info').html(resp);
<script>
function function1(ID) {
$.ajax({
type: "POST",
url: "functions/my_page.php",
data: "ID="+ID,
success: function(resp){
$('.populated_info').html(resp);
},
error: function(e){
alert('Error: ' + e);
}
});
}
</script>