jQuery Sortable with Ajax and mySQL - php

Hey I've created a sortable list for the backend of my site to organize my categories and I have it all working so it runs an update SQL statement with Ajax and it saves my data without a reload, but the order number that I'm displaying in my backend from the database doesn't change until I reload, any help would be great, thanks in advance!
PHP
<?php
$sql = "SELECT cat_id, cat_name, cat_slug, cat_status, cat_order, sta_id, sta_name
FROM app_categories LEFT JOIN app_status
ON app_categories.cat_status = app_status.sta_id
ORDER BY cat_order ASC";
if($result = query($sql)){
$list = array();
while($data = mysqli_fetch_assoc($result)){
array_push($list, $data);
}
foreach($list as $i => $row){
?>
<div class="row" id="page_<?php echo $row['cat_id']; ?>">
<div class="column two"><?php echo $row['cat_name']; ?></div>
<div class="column two"><?php echo $row['cat_slug']; ?></div>
<div class="column two"><?php echo $row['cat_status']; ?></div>
<div class="column two"><?php echo $row['cat_order']; ?></div>
</div>
<?php
}
}
else {
echo "FAIL";
}
?>
jQuery with Ajax call
$(document).ready(function(){
$("#menu-pages").sortable({
update: function(event, ui) {
$.post("ajax.php", { type: "orderPages", pages: $('#menu-pages').sortable('serialize') } );
}
});
});
And my ajax.php which does my update
<?php
parse_str($_POST['pages'], $pageOrder);
foreach ($pageOrder['page'] as $key => $value) {
$sql = "UPDATE app_categories SET `cat_order` = '$key' WHERE `cat_id` = '$value'";
if(query($sql)) {
echo "YES";
}
else {
echo "NO";
}
}
?>

You don't appear to have any kind of code for handling the front-end update. The easiest thing to do would be to add a callback in your ajax post and have the server send back the update information as json data.
So ajax.php would look more like
<?php
parse_str($_POST['pages'], $pageOrder);
foreach ($pageOrder['page'] as $key => $value) {
$sql = "UPDATE app_categories SET `cat_order` = '$key' WHERE `cat_id` = '$value'";
if(query($sql)) {
$orderSql = "SELECT cat_id, cat_name, cat_slug, cat_status, cat_order, sta_id, sta_name
FROM app_categories LEFT JOIN app_status
ON app_categories.cat_status = app_status.sta_id
ORDER BY cat_order ASC";
if($result = query($sql)){
echo json_encode(mysqli_fetch_assoc($result));
return;
}
} else {
echo json_encode( array('result' => 'failure'));
}
}
(Yeah, it's ugly and untested but you get the idea.)
Your javascript would then look something like
$.post("ajax.php", { type: "orderPages", pages: $('#menu-pages').sortable('serialize') }, function(res){
if (typeof res.result !== undefined && res.result === 'failure'){
alert('failed!');
return;
} else {
$.each(res, function(i, item){
$("#page_" + item.cat_id).find('div:eq(3)').html(item.cat_order);
});
}, 'json' );
Which again is terrible, but hopefully conveys the point.
Alternatively you could simply update the number in the sort div whenever it is moved. That would look like:
$("#menu-pages").sortable({
update: function(event, ui) {
$.post("ajax.php", { type: "orderPages", pages: $('#menu-pages').sortable('serialize') } );
$('.row').each(function(i){
$(this).find('div:eq(3)').html(parseInt(i) + 1);
});
}
});
Also not test, and that's assuming cat_sort is 1-indexed and not missing any values etc etc.

Related

Displaying images based on the selected ids using codeigniter

How to display images based on selecting ids.While adding portfolio images i am inserting data into two tables as portfolio table and portfolio_tags table.
I am having three tables portfolio,tags and portfolio_tags.
portfolio
=============
portfolio_id image_path
1 image.png
2 imag.png
3 images.png
4 img.png
5 imagess.png
Tags table:
==========
tag_id tag_name
1 All
2 CMS
3 DESIGN
portfolio_tag
=============
portfolio_id tag_id portfolio_tag_id
1 1 1
1 2 2
2 3 3
3 1 4
I will be fetching all the tags data as well as the portfolio data.While opening the page it will display all the data related to all the tags.But when we select particular only the information related to that tag to be displayed.
Ex:If i select CMS it should display only that information relation to CMS and if i select DESIGN only the information related to that tag should be displayed.
Can any one suggest me how to do that.
Here is my code.
Controller:
public function index()
{
$this->load->model('portfolio_model');
$data["records2"] = $this->portfolio_model->get_portfolio();
$data["records3"] = $this->portfolio_model->get_tags();
$data['mainpage'] = "portfolio";
$this->load->view('templates/template',$data);
}
Model:
function get_portfolio($limit, $start)
{
$this->db->limit($limit, $start);
$this->db->Select('portfolio.*');
$this->db->From('portfolio');
$this->db->where(array('portfolio.status'=>1));
$q=$this->db->get();
if($q->num_rows()>0)
{
return $q->result();
}
else
{
return false;
}
}
function get_tags()
{
$this->db->Select('tags.*');
$this->db->From('tags');
$q=$this->db->get();
if($q->num_rows()>0)
{
return $q->result();
}
else
{
return false;
}
}
View:
<?php $this->load->view('tagss');?>
<?php
$cnt = 0;
if(isset($records2) && is_array($records2)):?>
<?php foreach ($records2 as $r):?>
<div class="portfolioimages">
<img src="<?php echo base_url();?>admin/images/portfolio/thumbs/<?php echo $r->image_path;?>" />
</div>
<?php
if(($cnt%3) == 0) { echo "<br>"; }
$cnt++;
endforeach; endif;?>
Tags
<?php if(isset($records3) && is_array($records3)):?>
<?php foreach ($records3 as $r):?>
<div class="materials">
<div class="class453">
<?php echo $r->tag_name;?>
</div>
</div>
<?php endforeach ;endif;?>
<script type="text/javascript">
$('.materials a').not('.materials a:first').addClass('opacty');
$('.materials a').click(function(e){
$('.materials a').not(this).addClass('opacty');
$(this).removeClass('opacty');
});
</script>
For showing filtered images on clicking different tagNames, we can use ajax. So at first we need to create a new function in the Controller class which would display the fetched images url for the tag_id as the json object.
Add the function below to you controller.
public function tag_data($id){
$this->load->model('portfolio_model');
$data = array();
$tagged_result = $this->portfolio_model->get_tag_images($id); // call to model function
$tagged_images = array();
foreach($tagged_result as $tag){
$tagged_images[] = $tag->image_path;
}
echo json_encode($tagged_images);
}
In the code above I've called the function get_tag_images($id) which fetches all the images url from the database which are related to the tag_id.
Append the code below to the model class
public function get_tag_images($id){
$query = $this->db->select('image_path')->from('portfolio_tag')->join('portfolio',"portfolio_tag.portfolio_id = portfolio.portfolio_id")->where("tag_id", $id)->group_by('portfolio.portfolio_id')->get();
if($query->num_rows() > 0)
return $query->result();
else
return false;
}
Now we have to make some changes in the tags view.
View:
<?php
$cnt = 0;
if(isset($records2) && is_array($records2)):?>
<div id="portfolio">
<?php foreach ($records2 as $r):?>
<div class="portfolioimages">
<img src="<?php echo base_url();?>admin/images/portfolio/thumbs/<?php echo $r->image_path;?>" />
</div>
<?php
if(($cnt%3) == 0) { echo "<br>"; }
$cnt++;
endforeach; ?>
</div>
<?php endif;?>
Edit Tags view:
<?php if(isset($records3) && is_array($records3)):?>
<?php foreach ($records3 as $r):?>
<div class="materials">
<div class="class453">
<a href="javascript:void(0)" class="read_more12">
<span style="display:none"><?php echo $r->tag_id; ?></span> // this contains the tag_id
<?php echo $r->tag_name;?>
</a>
</div>
</div>
<?php endforeach ;endif;?>
Ajax -
<script type="text/javascript">
$('.materials div a').click(function(e){
e.preventDefault();
var tagId = $(this).find('span').html();
var url = '<?php echo base_url('portfolio/tag_data/'); ?>'+ tagId;
var $this = $(this);
$.ajax({
type: 'POST',
url: url,
data: {'tagid': tagId},
success: function(data){
var taggedImgs = $.parseJSON(data);
var inc = 0;
var unTag = [];
var portfolioImages = $('.portfolioimages a img').map(function(){
var url = $(this).attr('src').split('/');
return url[url.length-1];
});
$('.portfolioimages a img').each(function(e){
imgUrl = $(this).attr('src').split('/');
var imgPath = imgUrl[imgUrl.length-1];
// compare the tagged image with portfolio images url
if($.inArray(imgPath, taggedImgs) == -1){
// image doesn't matched
$(this).remove();
}
});
jQuery.each(taggedImgs, function(idx, tagImg){
var flag = false;
if($.inArray(tagImg, portfolioImages) == -1){
// image doesn't exist
$('#portfolio').append("<div class='portfolioimages'><a href='<?php echo base_url('index.php/portfolio'); ?>' target='_blank'><img src='<?php echo base_url('admin/images/portfolio/thumbs/'); ?>/"+tagImg+"'></a></div>");
}
});
},
error: function(err){
alert("Some error occured! "+ err);
}
})
})
</script>

Load the next 10 record via Ajax Search Box using PHP MySQL and JQUERY

I have see the example about search box using JQuery and mysql, But the view more function no work. how to improve the program. When i click the view more i can see the next 10 record. Thanks
<script type="text/javascript">
$(document).ready(function()
{
$("#keywords").keyup(function()
{
var kw = $("#keywords").val();
if(kw != '')
{
$.ajax
({
type: "POST",
url: "search.php",
data: "kw="+ kw,
success: function(option)
{
$("#results").html(option);
}
});
}
else
{
$("#results").html("");
}
return false;
});
$(".overlay").click(function()
{
$(".overlay").css('display','none');
$("#results").css('display','none');
});
$("#keywords").focus(function()
{
$(".overlay").css('display','block');
$("#results").css('display','block');
});
});
</script>
<div id="inputbox">
<input type="text" id="keywords" name="keywords" value="" placeholder="Type Your Query..."/>
</div>
</div>
<div id="results"></div>
<div class="overlay"></div>
we extract the value of that key and send it to the search.php
<?php
include('db.php');
//file which contains the database details.
?>
<?php
if(isset($_POST['kw']) && $_POST['kw'] != '')
{
$kws = $_POST['kw'];
$kws = mysql_real_escape_string($kws);
$query = "select * from wp_posts where post_name like '%".$kws."%' and (post_type='post' and post_status='publish') limit 10" ;
$res = mysql_query($query);
$count = mysql_num_rows($res);
$i = 0;
if($count > 0)
{
echo "<ul>";
while($row = mysql_fetch_array($res))
{
echo "<a href='$row[guid]'><li>";
echo "<div id='rest'>";
echo $row['post_name'];
echo "<br />";
echo "<div id='auth_dat'>".$row['post_date']."</div>";
echo "</div>";
echo "<div style='clear:both;'></div></li></a>";
$i++;
if($i == 5) break;
}
echo "</ul>";
if($count > 5)
{
echo "<div id='view_more'><a href='#'>View more results</a></div>";
}
}
else
{
echo "<div id='no_result'>No result found !</div>";
}
}
?>
press the view more result will not show more result.
If I'm not mistaken, you want to bring next 10 with ajax ?
This situation behaves as a pagination,
You have to store the current click count in javascript . WÄ°thout clicking more button, the variable of clickCount is 0, when you click more ,then your variable clickCount=1 ,
while sending ajax , send clickCount to the php.
$.ajax
({
type: "POST",
url: "search.php",
data: "kw="+ kw+"&clickCount="+clickCount,
success: function(option)
{
$("#results").html(option);
}
});
You can query with limit&offset (clickCount )*10, itemCountForEachMoreClick = limit 0,10
when click more
limit 10,10
when click one more
limit 20,10. Do not forget to reset clickCount on keyPress !
php Side
$count = isset($_REQUEST["clickCount"])? $_REQUEST["clickCount"]:0;
$limitAndOffset = $count*10.",10";
$query = "select * from wp_posts where post_name like '%".$kws."%'
and (post_type='post' and post_status='publish') limit ".$limitAndOffset ;

AJAX not separating JSON string

I'm using a star ratings system to display rating data from SQL. Each item that can be rated has unique identifyer variable $id and each rating in ratings tabl has unique identifyer $storyidr. I would like this script to display:
the average rating
the number of times the item has been rated.
The values are retirevable but they display on the page together and I can't see how to seperate them. FOr example, for an item that has an average rating of 4 and has been rated 200 times. when user clicks the data returns via AJAX looking like:
For 'response1' 4"200"
For 'response2' 4"200"
I would like to be able to seperate them to look like:
For 'response1' 4
For 'response2' 200
html page
<div id="products" style="">
<div class="rateit" data-storyidr="<?php echo $id; ?>">
</div>
<div class="averagevote">
<div style="display:block;" id="response<?php echo $id; ?>"><?php echo $avgratep; ?></div><br>
<div style="display:block;" id="response2<?php echo $id; ?>">RaTeD <?php echo $rankcount; ?> TiMeS</div>
</div>
</div>
<?php endwhile; mysqli_close($connection); ?>
<script type ="text/javascript">
$('#currentslide .rateit').bind('rated reset', function (e) {
var ri = $(this);
var value = ri.rateit('value');
var storyidr = ri.data('storyidr');
ri.rateit('readonly', true);
$.ajax({
dataType : 'json',
url: 'rate.php',
data: {storyidr: storyidr, value: value},
type: 'POST',
success: function (data) {
$('#response'+storyidr).replaceWith('Avg rating ' + data.avg + '/5');
$('#response2'+storyidr).replaceWith('Rated ' + data.cnt + ' times');
},
error: function (jxhr, msg, err) {
$('#response').append('<li style="color:red">' + msg + '</li>');
}
});
});
</script>
PHP
<?PHP
$storyidr=$_POST['storyidr'];
$mysqli = mysqli_connect($dbhost,$dbusername,$dbpasswd,$database_name) or die ("Couldn't connect to server.");
if (mysqli_connect_errno($mysqli))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "INSERT INTO ratings (storyidr, rank, entry_date) VALUES ('$_POST[storyidr]','$_POST[value]',now());";
$sql .= "SELECT AVG(rank) AS avrank, COUNT(rank) AS countrank FROM ratings WHERE storyidr = $storyidr";
if($mysqli->multi_query($sql))
{ $mysqli->next_result();
if ($result = $mysqli->store_result())
{
$data = mysqli_fetch_assoc($result);
$avrank = $data['avrank'];
$countrank = $data['countrank'];
$avrankr = round($avrank,2);
if(is_null($avrank)){$avrank ="null";}
echo json_encode(array('avg' => $avrankr, 'cnt' => $countrank));
}
}
?>
You should only use json_encode() once and only echo the result of that function. Doing it more than once invalidates your json:
else
{
$results = array();
$results['av'] = $avrankr;
$results['cnt'] = $countrank;
echo json_encode($results);
}
Then, in your javascript, you can access data.av and data.cnt directly:
$('#response'+storyidr).replaceWith('Avg rating ' + data.av +'/5');
$('#response2'+storyidr).replaceWith(data.cnt);
You could also set the dataType parameter in your ajax call as mentioned by #barell, but normally jQuery will figure that out correctly already.
Edit: To avoid the undefined errors you are getting you should do something like:
$results = array('status' => 'fail');
...
if () {
...
if ($result)
{
$results['status'] = 'success';
$results['av'] = $avrankr;
$results['cnt'] = $countrank;
}
}
echo json_encode($results);
Now you can check for data.status first in the success callback of your ajax call and take the appropriate action:
success: function (data) {
if (data.status === 'fail') {
// show a warning message somewhere, this is just an example
alert('No results found!');
} else {
$('#response'+storyidr).replaceWith('Avg rating ' + data.av + '/5');
$('#response2'+storyidr).replaceWith('RaTeD ' + data.cnt + ' TiMeS');
}
},
I think the problem is you don't set the correct header. In the php file, before any output, put this:
header('Content-type: text/json');
And also, instead of write two objects, write it as an array:
echo json_encode(array('avg' => $avrankr, 'cnt' => $countrank));
Now it should work
Then, in your Javascript you will access this data like this:
$('#response'+storyidr).replaceWith('Avg rating ' + data.avg +'/5');
$('#response'+storyidr).replaceWith(data.cnt); // Suppose you want the count here

Populating multiple dependent drop downs from database

I have 2 drop-down menues. The first I populated with possible continents and want the second drop-down to what include all countries depending on the continent that was selected in the first menu. I have only 1 mysql table with columns: continent --> country. Currently there are all countries from all continents in the drop-down even when a continent was chosen. Thank you for your help!
Here is my code:
HTML
<input type="text" class="autosuggest" id="autosuggest2" placeholder="Select Country...">
<div class="country">
<ul class="result" id="result2"></ul>
</div>
<input type="text" class="autosuggest" id="autosuggest3" placeholder="Select Area...">
<div class="area">
<ul class="result" id="result3"></ul>
</div>
jQuery / Ajax
$(document).ready(function() {
$('#autosuggest1').keyup(function() {
var continent = $(this).attr('value');
$.post('php/dropdown.php', {continent:continent}, function(data) {
$('#result1').html(data);
$('.result li').click(function() {
var result_value = $(this).text();
$('#autosuggest1').attr('value', result_value);
$('#result1').html('');
$('#result1').focusout('');
});
});
});
$('#autosuggest2').keyup(function() {
var country = $(this).attr('value');
$.post('php/dropdown.php', {country:country}, function(data) {
$('#result2').html(data);
$('.result li').click(function() {
var result_value = $(this).text();
$('#autosuggest2').attr('value', result_value);
$('#result2').html('');
$('#result2').focusout('');
});
});
});
});
PHP
require_once '../connect/connectdropdown.php';
if (isset($_POST['continent']) == true && empty($_POST['continent']) == false) {
$continent = mysql_real_escape_string($_POST['continent']);
$query = mysql_query("SELECT DISTINCT `continent` FROM `area` WHERE `continent` LIKE '$continent%'");
while (($row = mysql_fetch_assoc($query)) !== false) {
echo '<li>', $row['continent'], '</li>';
}
}
if (isset($_POST['country']) == true && empty($_POST['country']) == false) {
$country = mysql_real_escape_string($_POST['country']);
$query = mysql_query("SELECT DISTINCT `country` FROM `area` WHERE `country` LIKE '$country%'");
while (($row = mysql_fetch_assoc($query)) !== false) {
echo '<li>', $row['country'], '</li>';
}
}
i wonder if you are still on this. Anyway a couple of things i would suggest:
Do only one query, pass it to json, and give it to javascript.
PHP
require_once '../connect/connectdropdown.php';
$id=0;
$result=array();
$query = mysql_query("SELECT * FROM `area` ");
while (($row = mysql_fetch_assoc($query)) !== false) {
$result[$id]=$row;
$id++;
}
echo json_encode($result);
Javascript
$(document).ready(function() {
var $mysqlData;
$.post('php/dropdown.php', {continent:continent}, function(data) {
//Json Data from server:
alert('JSON data: '+data)
//you can transform the data from PHP-Json to Javascript Object
$mysqlData = jQuery.parseJSON(data)
//now you can access your data like:
alert ('My first continent: '+$mysqlData[0].continent+' and it\'s first country: '+$mysqlData[0].country)
});
$('#autosuggest1').keyup(function() {
//Now you can use $mysqlData inside your logic
})
$('#autosuggest2').keyup(function() {
//You can use $mysqlData here too
})
});
i did not test this code, there might be some errors but that the logic i suggest you to take.

passing params through ajax to php

I know this is a very basic question, but i couldnt figure how to fix the code even after crawling the web for past 1 hour.
I have an unordered list containing the information about the categories in the database, with cat_id as primary key. and a subject table with cat_id as its foreign key, so i want to access the subjects table through ajax request for given category ID. below is the code i used to generate categories. Where i am stuck is, i dont know which DOM element to fetch in order to send the unique id in the url parameter ..
thanks ..
<ul id="search_form">
<?php
$cat = Category::find_all();
foreach($cat as $category) {
echo '<li id="';
echo $category->cat_id;
echo '"><a href="subject.php?id=';
echo $category->cat_id;
echo'">';
echo $category->category;
echo '</a></li>';
}
?>
</ul>
<div id="results">
<!-- ajax contents goes here -->
</div>
the ajax file is
window.onload = init;
function init() {
if (ajax) {
if (document.getElementById('results')) {
document.getElementById('search_form').onclick = function() {
ajax.open('get', 'subject.php?id='+id ); // subject.php?id=
// how will i pass the variable
ajax.onreadystatechange = function() {
handleResponse(ajax);
}
ajax.send(null);
return false;
}
}
}
}
function handleResponse(ajax) {
if (ajax.readyState == 4) {
if ((ajax.status == 200) || (ajax.status == 304) ) {
var results = document.getElementById('results');
results.innerHTML = ajax.responseText;
results.style.display = 'block';
}
}
}
and the subject.php
<?php
//include("tpl/header.php");
include("includes/initialize.php");
?>
<h2></h2>
<?php
if (isset($_GET['id'])) {
$id= mysql_real_escape_string($_GET['id']);
$subject = Subject::find_subject_for_category($id);
foreach($subject as $subj) {
echo $subj->subject_title;
}
} else {
echo "No ID Provided";
}
?>
I have used Jquery to do these kind of things and it works fine for me.
$.ajax({
type: GET,
url: "subject.php",
data: {id: $('#search_form :selected').val()},
success: function(result){
// callback function
}
});

Categories