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
}
});
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>
I have this code , iam trying to use javascript to stop executing but its not working with javascript , any suggestions ? Am just trying to stop executing if the return was false from the javascript
if(mysql_num_rows($runzz)==0){
echo "<p align='center'><font size='5'>This Item $code1 - $code2 - ".$rw2['description']. "</br></br> Doesn't Exist In The <u><b>".$rowto['name']."</b></u></br></br> Wanna Add IT ?</font></p>";
?>
<script>
function check(){
var r = confirm("Press a button!");
if (r == true) {
return true;
} else {
return false;
}
}
check();
</script>
<?php
}
$insert="INSERT INTO transfercopy(warehouseidfrom,warehouseidto,qty,itemid,uid)VALUES('$from','$to','$qty','$codeid','$uid')";
$run=mysql_query($insert,$con);
if(!$run)die("error".mysql_error());
I am adding sample code to give you an idea, how you could use AJAX Call with it.
<?php
if(mysql_num_rows($runzz)==0){
echo "<p align='center'><font size='5'>This Item $code1 - $code2 - ".$rw2['description']. "</br></br> Doesn't Exist In The <u><b>".$rowto['name']."</b></u></br></br> Wanna Add IT ?</font></p>";
?>
<script>
function check(){
var r = confirm("Press a button!");
if(r) {
// Add additional parameter
// You could use POST method too. Use whatever make sense to you.
var urlLink = 'http://www.example.com/warehouse/record.php?from=<?php echo $from?>&to=<?php echo $to?>';
$.ajax({
type: 'GET',
url: urlLink,
success: function(data) {
if(data == 'success') {
return 'You have successfully added new record!';
}
},
error: function(data) {
console.log(data);
}
});
} else {
return false;
}
}
check();
</script>
<?php } ?>
<?php
// -- New File: record.php File
//
// You might wanna add the check, that it's the legit request and all the PHP Validation
$form = $_GET['from'];
$to = $_GET['to'];
$qty = $_GET['qty'];
$codeid = $_GET['codeid'];
$uid = $_GET['uid'];
$insert="INSERT INTO transfercopy(warehouseidfrom,warehouseidto,qty,itemid,uid)VALUES('$from','$to','$qty','$codeid','$uid')";
$run=mysql_query($insert,$con);
if(!$run) die("error".mysql_error());
else return 'success';
?>
There are many posts that are made by users, I want each post (or div in this case) to display the background color green or grey depending on the user status (logged in or not).
What I am trying to achieve is while idling on the page, you should see a user going online without refreshing the page
status.php
if (logged_in() === true){
$res8 = mysql_query("SELECT * FROM `users` WHERE status=1 LIMIT 1");
if(mysql_num_rows($res8) > 0){
while($row8 = mysql_fetch_assoc($res8)){
if ($row8['status'] === "1") {
echo "online";
}
}
}
}else {
echo "offline";
}
Main page
$res8 = mysql_query("SELECT * FROM `users` WHERE user_id='".$user_id."' LIMIT 1");
if(mysql_num_rows($res8) > 0){
while($row8 = mysql_fetch_assoc($res8)){
?>
<script type="text/javascript">
$(document).ready(function() {
setInterval(function(){
$.ajax({
url: 'status.php',
datatype:"application/json",
type: 'GET',
success: function(data) {
if (data === "online") {
$('.status').css({background: '#40A547'});
} else {
$('.status').css({background: '#7f8c8d'});
}
}
});
}, 5000);
});
</script>
<?php
}
}
}
echo '<div class="status">TEST</div></a></div>';
This code changes the background color of all the divs but I want it to only target the divs that correspond to the user that logged in (the creator of the post).
Not sure how to make the div have the dynamic styling using ajax.
Any help is much appreciated!
You can use the id user from the database to achieve this. Then add an id to the div corresponding to the user id. For instance :
Ajax Request in success :
$('.status #user'+ dataId).css({background: '#7f8c8d'});
In your HTML :
echo '<div class="status" id="user1">TEST</div></a></div>';
Edit
Your Main page (your AJAX request)
$.ajax({
url: 'status.php',
dataType: "json",
type: 'GET',
success: function(data) {
if (data.message === "online")
{
$('.status #user'+ data.userId).css({background: '#40A547'});
} else // data.message === "offline"
{
$('.status #user'+ data.userId).css({background: '#7f8c8d'});
}
}
});
//...
// HTML looks like...
echo '<div class="status" id="user1">TEST</div></a></div>';
echo '<div class="status" id="user2">TEST2</div></a></div>';
status.php
You set the dataType of your ajax request that you want return Json but it's unclea, your your status.php add the header content-type to json.
<?php
header('Content-Type: application/json'); // So add this
//...
$array = array(); // New variable which would be return as json
if (logged_in() === true) // Your online part
{
$res8 = mysql_query("SELECT * FROM `users` WHERE status=1 LIMIT 1");
if(mysql_num_rows($res8) > 0){
while($row8 = mysql_fetch_assoc($res8)){
if ($row8['status'] === "1") {
$array['message'] = 'online';
$array['userId'] = $row8['user_id']; // Here is the userId (adapt following your code)
}
}
}
}// Your offline part
else {
$array['message'] = 'offline';
}
echo json_encode($array);
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
}
}
});
});
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');
});
});