I have a script which loads several pages (views/home.php, views/about.php, views/contact.php etc):
$(document).ready(function() {
$('#content').load('views/home.php');
$('ul#nav li a').click(function(e) {
var pageq = $(this).attr('href');
$('#content').load('views/' + pageq + '.php');
document.title = $(this).attr('rel');
//to get the ajax content and display in div with id 'content'
$.ajax({
url:'views/'+pageq+'.php',
success: function(data){
$('#content').html(data);
}
});
//to change the browser URL to 'pageq'
if(pageq!=window.location){
window.history.pushState({path:pageq},'',pageq);
}
return false;
});
});
But it works only with html, for ex. <h1>Home</h1>.
Now I would add some variables to this pages. For example in setup.php there's a variable $page. How to display <h1>$page['title']</h1> ?
I tried with include('config/setup.php'); but it doesn't work.
I also tried this in my .js file: $.get('config/setup.php', { x : y });, but I don't know how to pass this variables and what is the best approach.
EDIT - navigation:
<?php
try{
$pdo = new PDO("mysql:host=localhost;dbname=mysite", 'root','root');
}
catch(PDOException $e) {
echo $e->getMessage();
}
$sql = "SELECT * FROM posts ORDER BY id";
$stmt = $pdo->prepare($sql);
$stmt->execute();
?>
<ul class="nav navbar-nav" id="nav">
<?php
while ($row = $stmt->fetch(PDO::FETCH_OBJ)) {
$sub_sql = "SELECT * FROM submenu WHERE cat_id=:id";
$sub_stmt = $pdo->prepare($sub_sql);
$sub_stmt->bindParam(':id',$row->id,PDO::PARAM_INT);
$sub_stmt->execute();
?>
<li class="dropdown <?php selected($path['call_parts'][0], $row->slug, 'active') ?>"><?php echo $row->title; ?>
<?php
if($sub_stmt->rowCount()) {
?>
<ul class="dropdown-menu" role="menu">
<?php
while ($sub_row = $sub_stmt->fetch(PDO::FETCH_OBJ)) {
?>
<li><?php echo $sub_row->sub_name; ?></li>
<?php
}
?>
</ul>
<?php
}
?>
</li>
<?php
}
?>
</ul>
make sure you have "json" in your jQuery ajax statement
php:
$myVar = $_POST['myVar'];
echo json_encode(array( "var_1"=>$var1, "var_2"=>$var2 ));
javascript:
var myVar = 'xyz';
$.post('config/setup.php', { myVar:myVar }, function(data) {
var var_1 = data.var_1,
var_2 = data.var_2; //<< matches w/ php above
}, "json");
Related
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>
Here is my code:
<div class="category" id="<?php echo $cat->term_id; ?>"><?php echo $cat->cat_name; ?> </div>
$(".category").click(function(){
var categ = $(this).attr('id');
alert(categ);
ajax({
type:'POST',
url:'http://myweb.com/rel_notes/?page_id=238',
data:'cat='+categ,
success:function(data) {
if(data) {
} else { // DO SOMETHING
}
}
});
});
and the code behind the page which is receiving the posted data (http://myweb.com//rel_notes/?page_id=238) is here:
<?php
if (isset($_POST['cat']))
{
$cat_id = $_POST['cat'];
echo "<script>alert('$cat_id')</script>";
}
else
$cat_id = NULL;
?>
Problem: It didn't get the value in $cat_id. I tried changing $_POST to $_GET but that didn't work too. So kindly help me where am i missing something?
$.ajax({
type:'POST',
data: {cat: categ},
url:'http://myweb.com//rel_notes/?page_id=238',
error: function() {
alert("Data Error");
},
success:function(data) {
if(data) {
} else {
}
}
});
This is not good way dude.
None can make alert on server side.
You are doing alert code on the server side.
Just replace
<?php
if (isset($_POST['cat']))
{
$cat_id = $_POST['cat'];
echo "<script>alert('$cat_id')</script>";
}
else $cat_id = NULL;
?>
by
<?php
if (isset($_POST['cat']))
{
echo $cat_id = $_POST['cat'];
}
else {
echo $cat_id = "";
}
?>
and alert the code like
$(".category").click(function(){
var categ = $(this).attr('id');
alert(categ);
ajax({
type:'POST',
url:'http://myweb.com/rel_notes/?page_id=238',
data:'cat='+categ,
success:function(data) {
if(data != "") {
alert(data);
}else { // DO SOMETHING
}
}
});
});
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.
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
}
});
jQuery:
$(document).ready(function(){
$(".reload").click(function() {
$("div#update").fadeOut("fast")
.load("home.php div#update").fadeIn("fast")
});
});
PHP:
function statusUpdate() {
$service_query = mysql_query("SELECT * FROM service ORDER BY status");
$service_num = mysql_num_rows($service_query);
for ($x=1;$x<=$service_num;$x++) {
$service_row = mysql_fetch_row($service_query);
$second_query = mysql_query("SELECT * FROM service WHERE sid='$service_row[0]'");
$row = mysql_fetch_row($second_query);
$socket = #fsockopen($row[3], $row[4], $errnum, $errstr, 0.01);
if ($errnum >= 1) { $status = 'offline'; } else { $status = 'online'; }
mysql_query("UPDATE service SET status='$status' WHERE sid='$row[0]'")
or die(mysql_error());
?>
<ul><li style="min-width:190px;"><?php echo $row[1]; ?></li>
<li style="min-width: 190px;" title="DNS: <?php echo $row[2]; ?>">
<?php echo $row[3] . ':' . $row[4]; ?></li>
<li class="<?php echo $status; ?>" style="min-width:80px;"><div id="update">
<?php echo $status; ?></div></li></ul>
<?php
}
}
?>
<?php statusUpdate(); ?>
I have a button which I press (refresh) and that will then refresh the #update id to hopefully fadeOut all the results, and then fade in the new results... issue is it fades them out okay, but when it brings them back, it's just div on div and div and looks really messy - does not do what it's meant to do (would have to upload a picture to give further information).
In the short, what I want to happen is when you hit the update, they will all fade and then fade in with updated values from the php... I made the php/mysql into a function so then I could call it when i hit that refresh button, thinking that would work, but I don't know how to do that...
Thank-you in advance,
Phillip.
Javascript
$(document).ready(function(){
$(".reload").click(function() {
$("div#update").fadeOut("fast");
$.ajax({
url:'home.php',
data:{type:'getStatus'},
type;'post',
success:function(data){
$('div#update').html(data).fadeIn('fast');
}
});
});
});
php page format
<?php
$type= $_POST['type'];
if($type=="getStatus")
{
//get statuses from data base and return only formatted statuses in html
}
else
{
//your page codes here
//like tags <html>,<body> etc, all regular tags
//<script> tags etc
}
?>
.load("home.php div#update").fadeIn("fast")
That's wrong. You need to use,
$('div#update').load('home.php', function(data) {
$('div#update').html(data).fadeIn("fast");
});
Make sure your PHP file works properly by calling it directly and confirming that it returns the results properly.
Reference : http://api.jquery.com/load
Try this
var $data = $('div#update');
$data.fadeOut('slow', function() {
$data.load('home.php div#update', function() {
$data.fadeIn('slow');
});
});
Just for the reference, it will be better to add an additional page in the same directory (eg: phpcode.php) and then put your php code also in there! then try this:
var $data = $('div#update');
$data.fadeOut('slow', function() {
$data.load('phpcode.php div#update', function() {
$data.fadeIn('slow');
});
});