Getting separate PHP variables using jQuery Ajax - php

My script.js performs a request to get_all.php which has three variables to output (echo) $all_categories, $all_brands and $all_filters. Now I want to manipulate these in three different areas in my index.html.
I want to place $all_categories in <div id="caregories">, $all_brands in <div id="vrands"> and $all_filtesr in <div id="filters">.
How can I place them separately in each div ? I know how to place all of them in one <div> but have no idea how to place each variable, received, separately.
index.php
<?php // Startup ?>
<?php
define('APP_PATH', '../');
define('SYS_PATH', '../system/');
define('STYLES', 'assets/styles/');
define('SCRIPTS', 'assets/scripts/');
require_once SYS_PATH . 'initializers/all.php';
?>
<?php // Controller ?>
<?php
?>
<?php // Viewer ?>
<?php template('header'); ?>
<body>
<div id="static_menu">
<ul>
<li>Categories</li>
<li>Brands</li>
<li>Filters</li>
<li>Social</li>
</ul>
</div>
<hr>
<div id="categories">
<ul></ul>
</div>
<hr>
<div id="brands">
<ul></ul>
</div>
<hr>
<div id="filters">
<ul></ul>
</div>
<hr>
<div id="social">
<ul></ul>
</div>
<hr>
</body>
<?php template('footer'); ?>
script.js
// DOM ready
$(function(){
// get categories, brands, filters and social
$.ajax({
type: "POST",
url: "get_all.php"
}).done(function(data){
// manipulate recieved in three different divs
})
});
get_all.php
<?php // Startup ?>
<?php
define('APP_PATH', '../');
define('SYS_PATH', '../system/');
define('STYLES', 'assets/styles/');
define('SCRIPTS', 'assets/scripts/');
require_once SYS_PATH . 'initializers/all.php';
?>
<?php // Controller ?>
<?php
$result_arr = $category->select_all();
$all_categories = $html->list_anchor_loop($result_arr, 'category');
echo $all_categories
$result_arr = $brand->select_all();
$all_brands = $html->list_anchor_loop($result_arr, 'brand');
echo $all_brands;
$result_arr = $filter->select_all();
$all_filters = $html->list_anchor_loop($result_arr, 'filter');
echo $all_filters;

Have your PHP script send the result as a JSON object (see json_encode).
In your JS, you'll receive an object, say resp, which will have three properties, resp.categories, resp.filters and resp.brands
For more details and specificity, post some code.
In get_all.php :
$result = array(
'categories' => $all_categories,
'brands' => $all_brands,
'filters' => $all_filters
);
echo json_encode($result);
In script.js
$.ajax({
type: "POST",
url: "get_all.php",
dataType : 'json', //specify that data will be returned as JSON
}).done(function(data){
// use data.categories, data.brands, data.filters here
// manipulate recieved in three different divs
})

If your ajax call returns through JSON, it is quiet easy to insert the data into the divs you need:
PHP
<?php
$return = array(
'categories'=>$all_categories,
'vrands'=>$all_brands,
'filters'=>$all_filters
);
echo $_GET['jsoncallback'].'('.json_encode($return).')';?>
JQuery:
<script type="text/javascript">
$.getJSON("URL_TO_PHP?jsoncallback=?",{
/*DATA TO SEND*/
},function(response){
$('#categories').html(response.categories);
$('#vrands').html(response.vrands);
$('#filters').html(response.filters);
});
</script>

You may use a library that does that automatically, like http://phery-php-ajax.net you may pass JSON data directly from PHP while still manipulating the DOM in order. Phery doesn't work with URLs, but with function callbacks, and you may assign to the DIVs from inside PHP itself, like in your case:
<?php
Phery::instance()->set(array(
'get_all' => function($data){
/* globals, initialization, etc*/
$r = new PheryResponse;
$result_arr = $category->select_all();
return
$r
->jquery('#categories')->html($html->list_anchor_loop($result_arr, 'category'))
->jquery('#filter')->html($html->list_anchor_loop($result_arr, 'filter'))
->jquery('#brand')->html($html->list_anchor_loop($result_arr, 'brand'));
}
))->process();
Then call the get_all function from your DOMReady
$(function(){
phery.remote('get_all');
});
Done, everything gets filled for you, without any extra client-side code.

Related

Jquery reload div content on select change using php ajax

OK here is my code
portfolio.php
<select name="portfolio" id="portfolio_dropdown" class="service-dropdown">
<?php foreach($years as $year){ ?>
<option value="<?php echo $year['year']; ?>"><?php echo $year['year']; ?></option>
<?php } ?>
</select>
<div class="loading"></div>
<div id="portfolio">
<div id="port-cont">
<?php foreach($portfolios as $portfolio){ ?>
<div class="video">
<div class="play">
Play
</div>
<iframe src="http://www.youtube.com/v/<?php echo $portfolio['url']; ?>"frameborder="0" allowfullscreen></iframe>
<h3><?php echo $portfolio['title']; ?></h3>
<p><?php echo $portfolio['text']; ?></p>
</div>
<?php } ?>
</div>
</div>
my js code
$("body").on('change','#portfolio_dropdown',function(){
var year = $(this).val();
$.ajax({
type: "POST",
url: "catalog/controller/portfolio.php",
data: "year="+year,
beforeSend: function(){
$(".loading").show();
$("#portfolio").empty();
},
success: function(portfolio_data){
$(".loading").hide();
$("#portfolio").html(portfolio_data);
}
});
});
my portfolio controller file
if(isset($_POST['year'])){
include_once "../../system/validation.php";
include_once "../model/DataBase.php";
include_once "../model/Display.php";
$year = integer($_POST['year']);
$get_portfolio_data = new Display("portfolio");
$portfolios = $get_portfolio_data->getDataByColumnName("year",$year);
include_once "../view/themes/default/template/portfolio_data.php";
exit();
}
My portfolio file "the first one " i get my data with another function that i get my last year(2014) portfolio data
so when i change the year i call my controller file to get the data related to that year
my question here is how to return $portfolios that i got from my controller file so i don't have to change my template file code or include another file as i did
i mean i need to reload my portfolio.php template content
i tried something like this
$("body").on('change','#portfolio_dropdown',function(){
var year = $(this).val();
$.ajax({
type: "POST",
url: "catalog/controller/portfolio.php",
data: "year="+year,
beforeSend: function(){
$(".loading").show();
$("#portfolio").hide();
},
success: function(portfolio_data){
$(".loading").hide();
$("#portfolio").show().load("portfolio" + " #port-cont");
}
});
});
but i don't know how to send my new $portfolios data to the same div without including another template file
Actually i'm little confused how to do this properly
So i hope you got what i want to do :)
You can create a separate portfolio-div.php file that only contains the code you want to replace with, and call that from the $.ajax call.
Or you can add a $_GET parameter like ?skiptemplate=1 to portfolio.php so that when you call the file with that parameter, the surrounding template markup is skipped when the file is called from an ajax call.
If you do not have the opportunity to change the server-side code, you can load the whole template file again, but extract only the #port-cont part to replace the existing content. Don't use load() (which itself will call an URL), use html() instead:
$("#portfolio").show().html(portfolio_data);
(though this will insert all HTML, not only the #port-cont part)
$("#portfolio").html(portfolio_data)
Just pass the parameter into html

Load div content on same page using AJAX in Codeigniter

i am newbie on codeigniter but trying to develop simple CMS on it.
my question is i have a side column in my main CMS view which have several links to other views,what i want to do is to load all the links in main CMS view in center div instead of going to another page every time. I know i can achieve this task through ajax but dont know how to do it on CODEIGNITER.
Here is how i want to acheieve it to my knowledge.
<script type="text/javascript">
function onLinkClick(value){
jQuery('#mang_server').load(value,
function(){alert('Content Successfully Loaded.')}
);
}
</script>
<body>
<div id="main">
<div id="header"> <img src="../img/logo.gif" width="101" height="29" alt="" />
<div id="middle">
<div id="left-column">
<h3>Header</h3>
<ul class="nav">
<?php foreach($ops as $operations)
{$op_name = $operations['admin_op'];
$op_link = $operations['link_to'];
?>
<li><?php echo $op_name ;?></li>
<?php } ?>
</ul>
Take a look on this simple example for ajax in codeigniter:
$.ajax({
url: '<?php echo base_url() ?>/controller_namer/method_name',
type: 'POST',
data: {view_param: "sidebar_html"},
success: function(response){
$('#div_id').html(response);
}
});
Now go to controllers/controller_name.php and create a method method_name;
function method_name() {
// Get Post Data
$View_Name = $this->input->post("view_param");
$this->load->view($View_Name);
// Alternate is create your html here
// ......
}
hope this will help you.
#jogesh_pi
View Portion:
<script>
function onLinkClick(value){
/*Query('#mang_server').load(value,
function(){alert('Content Successfully Loaded.')}
);*/
$.ajax({
url: '<?php echo base_url() ?>/admin/load_view/',
type: 'POST',
data: {view_param: "value"},
success: function(response){
//$('#mang_server').html(response);
alert("response recieved");
}
enter code here
});
}
</script>
<li><?php echo $op_name ;?></li>
Controller Portion : admin
public function load_view($view_name){
$data['view_link'] = $this->admin_model->load_view_model($view_name);
$this->load->view($data);
}
Model portion : load_view_model
public function load_view_model($view_name){
$this->db->where('admin_op',$view_name);
$query = $this->db->get('admin_operations');
if($query->num_rows()>0){
foreach($query->results() as $rows ){
$data['link'] = $rows->link_to;
}
return $data->result_arrays();
}
}

How to integrate AJAX to avoid page redirection of PHP CMS

I have used a CMS built with PHP and MySQL. It works great and I have fully customized it to my liking. The only thing now to do is make a more efficient way of loading the data. When a user wants to select an article I want the browser to stay on the same exact page/url without reloading or redirecting. Here is a demo of the CMS: DEMO LINK
For example, the above line of code was exerted from the homepage.php script. It is an anchor tag for the user to select to view the whole content of a particular article, which was only partially displayed in the homepage. When this link is clicked, the user is directed away from the homepage and taken to the article's specific URL. How can I get the full article content page to load inside of the homepage and hide the original homepage content to avoid the page redirect problem. Is this something that can be done with this particular CMS? I can provide any PHP script from the CMS if needed. Thanks in advance.
ARCHIVE.php SCRIPT:
<?php foreach ( $results['articles'] as $article ) { ?>
<li>
<h2>
<span class="pubDate"><?php echo date('j F Y', $article->publicationDate)?></span><br><?php echo htmlspecialchars( $article->title )?>
</h2>
<p class="summary">
<?php if ( $imagePath = $article->getImagePath( IMG_TYPE_THUMB ) ) { ?>
<a href=".?action=viewArticle&articleId=<?php echo $article->id?>">
<div class="floated_child0" style="background-repeat:none; background-image:url('<?php echo $imagePath?>');"></div></a>
<?php } ?>
<?php echo htmlspecialchars( $article->summary )?> (more)
</p>
</li>
<?php } ?>
If you can get the content of the article using ajax and put that content below that title of that article, for ex let say you have a php function in backend which you can call to get the content of article given the article id then you can make a GET ajax request to get the article content and put in the desired div. something like:
<script language="javascript">
$("#view_more").click(function(){
var dataString = "id="+article_ID;
$.ajax({
type: "GET",
url: 'http://myhost.com/articles/getArticleContent',
data: dataString,
success: function(response) {
$('div #description').html(response);
}
});
return false;
});
</script>
update:27-11-2012
you can try something like this, if that helps you understanding better. it may not be exactly what you want but I hope it will help you understanding how you can proceed.
<?php foreach ( $results['articles'] as $article ) { ?>
<li>
<h2>
<span class="pubDate"><?php echo date('j F Y', $article->publicationDate)?></span><br><?php echo htmlspecialchars( $article->title )?>
</h2>
<p class="summary" id="<?php echo $article->id?>">
<?php if ( $imagePath = $article->getImagePath( IMG_TYPE_THUMB ) ) { ?>
<a href=".?action=viewArticle&articleId=<?php echo $article->id?>">
<div class="floated_child0" style="background-repeat:none; background-image:url('<?php echo $imagePath?>');"></div></a>
<?php } ?>
<?php echo htmlspecialchars( $article->summary )?> (more)
</p>
</li>
<?php } ?>
<script language="javascript">
function viewFullArticle(article_ID){
var dataString = "id="+article_ID;
$.ajax({
type: "GET",
url: 'http://myhost.com/articles/getArticleContent',
data: dataString,
success: function(response) {
$('p #'+article_ID).html(response); //assuming response is everything you want to display within summary paragraph
}
});
return false;
};
</script>

Jquery events for ajax post after DOM is loaded

I'm having trouble getting post DOM created elements to inherit jquery events.
As I understand it, on() should take care of this - but I can't get it working for elements created inside my form-sumbit 'post' call.
I have also tried: $("form").on("sumbit",function() {
$(document).ready(function(){
$('p.dev_summary').on("click",function() {
$(this).next().toggle();
});
$("form").submit(function() {
var dev_text = $('textarea').attr('value');
$.ajax({
type: "POST",
url: "composite/submit_dev",
data: "dev_text=test",
success: function(){
var $content = $('<div class=insert_dev id></div><p class=dev_summary>Some Text</p>');
$content.insertBefore( $('div.insert_dev');
}
});
return false;
});
});
Thank you in advance.
HTML/PHP as requested (codeigniter):
<div class="composite_wrapper">
<?php foreach($development as $row): ?>
<div class="insert_dev" id="<?php echo $row['orderid'];?>"></div>
<p class="dev_summary"><?php echo 'Summary: ' .$row['text'];?></p>
<div class="development"><?php echo $row['text']?></div>
<?php endforeach ?>
<?php
$attributes = array('style' => 'display: none');
?>
<?php echo form_open('#',$attributes); ?>
<?php echo validation_errors(); ?>
<p>
<label for="dev_text">Development:</label>
<br />
<?php echo form_textarea('dev_text'); ?>
</p>
There are 2 implementations of on(). One allows binding directly to elements but those elemnts must exist, and does not account for futures.
The other method is a delegation method. You delegate the handler to a higher level elementt or the document. This method catches the event as it bubbles
$(document).on('click', 'p.dev_summary', function ......
Look at optional selector in on() docs
http://api.jquery.com/on/
There is a really good detailed read for how jQuery handled these event handlers:
http://www.elijahmanor.com/2012/02/differences-between-jquery-bind-vs-live.html
Like the above poster said, you are using the on selector in the way of handling for the bind handler. But you should be using it for delegate or live.
You might like to try bind:
http://api.jquery.com/bind/

change the content of div after submitting data to mysql

i am new to ajax . i want to submit a data with the help of ajax and then get the new data replacing the old one in the same div as of which the old data was .
here is the jquery for sliding tab
$(document).ready(function() {
// Vertical Sliding Tabs
$('div#st_vertical').slideTabs({
// Options
contentAnim: 'slideH',
contentAnimTime: 600,
contentEasing: 'easeInOutExpo',
orientation: 'vertical',
tabsAnimTime: 300
});
});
ajax
function addhubs()
{
var group =$('#customhubs').val();
var user=$('#loginuser').val();
$.ajax({
type:"GET",
url: 'mfrnds.php?val='+group+'&& loguser='+user,
success: function(html){
}
});
}
the div i want to replace data
<div id="st_vertical" class="st_vertical">
<div class="st_tabs_container">
<div class="st_slide_container">
<ul class="st_tabs">
<?php $sql=mysql_query("select * from groups");
while($ab=mysql_fetch_array($sql))
{
$gpID[]=$ab['group_id'];
$gp=$ab['group_id'];
$gpName=$ab['group_name'];
?>
<li><?php echo $gpName;?></li>
<?php
}
?> </ul>
</div> <!-- /.st_slide_container -->
</div> <!-- /.st_tabs_container -->
and the mfrnds.php of the ajax call file contains query to update the new data.
$user=$_GET['loguser'];
$group=$_GET['val'];
$sql=mysql_query("insert into groups (group_name) values ('$group')");
how can i update the div in the above . plz help me .m stuck badly luking for solution from 4 days. thanks
Note that in your addhubs function you should only add one & in your url and concatenate everything without spaces in between such as below.
When the ajax call has finished it returns the contents of the page you requested (mfrnds.php) in the html variable. So you can simply select the div you want and enter the html as you can see below. So here we go...:
Your Page
<html>
<body>
<script>
$(document).ready(function() {
setupTabs();
});
function setupTabs() {
// Vertical Sliding Tabs
$('div#st_vertical').slideTabs({
// Options
contentAnim: 'slideH',
contentAnimTime: 600,
contentEasing: 'easeInOutExpo',
orientation: 'vertical',
tabsAnimTime: 300
});
}
function addhubs() {
var group = $('#customhubs').val();
var user = $('#loginuser').val();
$.ajax({
type:"GET",
url: 'mfrnds.php?val=' + group + '&loguser=' + user,
success: function(html) {
//Get div and display the data in there
$('div.st_slide_container).html(html);
//As your slide effect is gone after you updated this HTML, redo your slide effect:
setupTabs();
}
});
}
</script>
<!-- Vertical div -->
<div id="st_vertical" class="st_vertical">
<div class="st_tabs_container">
<div class="st_slide_container">
<ul class="st_tabs">
<?php
$sql = mysql_query("select * from groups");
while($ab = mysql_fetch_assoc($sql)) {
$gp = $ab['group_id'];
$gpName = $ab['group_name']; ?>
<li>
<a href="#stv_content_<?=$gp?>" rel="v_tab_<?=$gp?>" class="st_tab ">
<?php echo $gpName;?>
</a>
</li>
<?php
}
?>
</ul>
</div> <!-- /st_slide_container -->
</div> <!-- /st_tabs_container -->
</div> <!-- /st_vertical -->
</body>
</html>
So in your mfrnds.php you should have a PHP script that uses the val and loguser GET variables and updates the database. After the database has been updated you should return the updated HTML like the following:
*mfrnds.php
<?php
$user = $_GET['loguser'];
$group = $_GET['val'];
$sql = mysql_query("insert into groups (group_name) values ('$group')"); ?>
<ul class="st_tabs">
<?php
$sql = mysql_query("select * from groups");
while($ab = mysql_fetch_assoc($sql)) {
$gp = $ab['group_id'];
$gpName = $ab['group_name']; ?>
<li>
<a href="#stv_content_<?=$gp?>" rel="v_tab_<?=$gp?>" class="st_tab ">
<?php echo $gpName;?>
</a>
</li>
<?php
}
?>
</ul>
Note though that this code is basically meant as an example, I don't know what you want to do exactly in mfrnds.php etc, but I hope this gives you a good idea!
It looks like you are almost there.
In your mfrnds.php file add a line to grab the updated rows
use:
PSEUDOCODE
"SELECT * FROM groups"
for each row in groups
echo "<div> groups.name groups.category </div"
and then in your callback function
success: function(html){
$('.st_tabs').html(html); //replace the html of the sttabs div with the html echoed out from mfrnds.php
}

Categories