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/
Related
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
Here I have an .ajax function within a PHP function, like this:
function phpFunction($ID) {
print "<script>
$('.uparrow').click(function(){
request = $.ajax({
etc... the rest isn't important.
Anyway, the class .uparrow is an html element that runs this .ajax function when clicked. The other thing you should know is that this function: phpFunction() is called a few times in the document, like this:
phpFunction(1)
phpFunction(2)
phpFunction(3)
However, the problem is that when I load phpFunction(), and I click on the .uparrow element, the .ajax call is made on behalf of each instance of phpFunction() that follows the one whose element I clicked on.
So if I clicked on the .uparrow of phpFunction(1), I would also be virtually clicking on the .uparrows of phpFunction(2) and phpFunction(3). Essentially, I need .uparrow to just be a local class that only applies to the instance of phpFunction() that is currently being called.
The only solution I could think of is to replace .uparrow's class name with something unique to each call of this function. The only difference between each instance of phpFunction() is their input $ID and I was thinking I could redefine .uparrow as:
class = '$ID.uparrow'
or
class = $ID + 'uparrow'
But that doesn't work. So how do I make sure that when I click on .uparrow within phpFunction(1), that the .ajax function only gets called that one time?
This is pretty confusing to explain and probably to understand, so please tell me if there's something that needs elaboration.
Let's say you have a list of elements, and when you click one of them, you want to do an ajax call.
click me
click me
<script>
$(function(){ //on DOM ready
$('.uparrow').on('click', function(){
//do ajax call
$.ajax({
url: 'url here'
type: 'post|get'
data: $(this).attr('data-id'), // you only send the ID of the clicked element
... callbacks, etc
})
});
})
</script>
Now you only have a function that makes an ajax call and takes the parameter to send from the element you clicked.
I hope this is what you wanted to achieve
Try something like this
$('[class="uparrow"]').click( function () {
var request = $.ajax({
// Your ajax call
});
});
this will execute ajax on the clicked element with .uparrow class
HTML
<a class="uparrow" href="#" data-ajax="I'm the first element">Click Me</a>
<a class="uparrow" href="#" data-ajax="I'm the second element">Click Me</a>
<a class="uparrow" href="#" data-ajax="I'm the third element">Click Me</a>
JS:
$('[class="uparrow"]').click(function () {
var currentAjax = $(this).data('ajax')
console.log(currentAjax);
});
And the DEMO
Do not call your php function multiple times. Just one time is sufficient.
Modify the markup of your .uparrow element to include the id like so:
<a class="uparrow" data-id="<?php echo $id; ?>" href="#">TextM/a>
Then re-write your php function like so:
function phpFunction() { /* no need to pass the ID */ ?>
<script>
$(function(){
$(document).on('click', '.uparrow', function(){
$.ajax({
url: 'URL',
type: 'POST'.
data: $(this).attr('data-id')
})
});
})
</script>
<?php } ?>
Call your phpFunction like so:
phpFunction();
UPDATE
<!doctype html>
<html>
<head>
<title>trop</title>
<meta charset='utf-8'>
<link rel='stylesheet' href='css/postStyle.css' />
<link href='http://fonts.googleapis.com/css?family=Exo+2:400,300,200|Homenaje&subset=latin,latin-ext' rel='stylesheet' type='text/css'>
<link rel='shortcut icon' href='http://icons.iconarchive.com/icons/visualpharm/icons8-metro-style/256/Music-Note-icon.png'>
<script src='../jquery.js'></script>
<script type='text/javascript' src='../script.js'></script>
</head>
<body>
<?php
$ids = array(1,2,3); // IDs of the posts you want
$result = mysql_query("SELECT * FROM all_posts WHERE ID IN($ids)");
while ($data = mysql_fetch_array($result)){
?>
<div class='post' style='width:470px'>
<h3><?php echo $data['Title']; ?></h3>
<div class='date'><?php echo $data['DateTime']; ?></div>
<iframe width='470' height='300' src='http://www.youtube.com/embed/WF34N4gJAKE' frameborder='0' allowfullscreen></iframe>
<p><?php echo $data['Body']; ?></p>
<div class='postmeta1'>
<p><a href='<?php echo $data['DownloadLink']; ?>' target='_blank'>DOWNLOAD</a></p>
</div>
<div class='verticalLine' style='height:39px'></div>
<div class='postmeta2'>
<p class='uparrow' data-id="<?php echo $data['id']; ?>">▲</p>
<div class='votes'>3</div>
<p class='downarrow'>▼</p>
</div>
<div class='verticalLine' style='height:39px'></div>
<div class='postmeta3'>
<div class='tags'>
<p><?php echo $data['Tags']; ?></p>
</div>
</div>
</div>
<?php } ?>
<script>
var request;
$('.uparrow').click(function(){
request = $.ajax({
url: 'votesHandler.php',
type: 'post',
data: { add : '1', ID : $(this).attr('data-id') }
});
request.done(function (response, textStatus, jqXHR){
alert('Voted!');
});
request.fail(function (jqXHR, textStatus, errorThrown){
alert(
'Oops, something went wrong'
);
});
request.always(function () {
alert('Done.');
});
});
</script>
</body>
</html>
I'm building a website where the admin can make settings for the website. I would like the admin settings page to have a similar "feel" as the rest of the website, which has some nice looking jQuery features.
On the admin site there's a hidden div, which is shown when one of six links has been clicked. I'd like the content of the hidden div to change content before showing itself. I'm not sure how to do this. I could have a div box for every link on the page. But this becomes pretty cumbersome since I'd need to repeat my css and jquery for every link. I imagine that this, somehow, can be done with some javascript/jquery code that determines which link that was click and then decides which php function to call inside the hidden div. Then the php could "echo" out the content of the div, which then could be shown.
How could one do this?
My HTML/jQuery code is as follows:
--- The html links ---
<table id="settings">
<tr>
<td>
<img src="images/folder.gif" alt="" height="100"/>
</td>
<td>
<img src="images/folder.gif" alt="" height="100"/>
</td>
<td>
<img src="images/folder.gif" alt="" height="100"/>
</td>
----- The Hidden div -----
<div id="dashboard_box">
<div class="dashboard_inside">
<form action="#" method="post">
<p style="font-size:20px; font-weight: bold;">Change color</p>
</br>
<fieldset>
<? load_content1();?>
</fieldset>
</form>
</div>
</div>
---- jquery code (working)----
var mouse_is_inside = false;
$(document).ready(function() {
$(".action").click(function() {
var loginBox = $("#dashboard_box");
if (loginBox.is(":visible"))
loginBox.fadeOut("fast");
else
loginBox.fadeIn("fast");
return false;
});
$("#dashboard_box").hover(function(){
mouse_is_inside=true;
}, function(){
mouse_is_inside=false;
});
$("body").click(function(){
if(! mouse_is_inside) $("#dashboard_box").fadeOut("fast");
});
});
You probably want to use ajax to load the content from the server. Take a look at jquery's .load() method: http://api.jquery.com/load/
You could include a data attribute per link:
<a class="action" data-content="content.php?method=load_content1"></a>
<a class="action" data-content="content.php?method=load_content2"></a>
js would look something like this:
$(".action").on('click', function() {
$("#dashboard_box fieldset").load($(this).data('content'), function() {
var loginBox = $("#dashboard_box");
if (loginBox.is(":visible"))
loginBox.fadeOut("fast");
else
loginBox.fadeIn("fast");
}
return false;
});
Then, in your content.php file you could check the method parameter in the url to determine what content to return.
My php is a little rusty, but something like this:
<?
call_user_func($_GET['method']); // i'm not sure how safe this is. you may want to be more explicit
?>
You can just add data attribute in each of your link's
<a href="#" data-url="content1.php" ..
Then on click of any of the a you can get the php to be called.
$('a').on('click',function(){
var phpFunctionToCall = $(this).data('url');
});
You probably need to make ajax call to load content into your fieldset As this <? load_content1();?> run's on server and javascript have no control over it.
Thanks for all the help. this is what I ended up doing.
--- HTML ---
<a class="action" data-content="content.php?method=load_content2"></a>
---Jquery---
var mouse_is_inside = false;
$(document).ready(function() {
$(".action").click(function() {
var phpFunctionToCall = $(this).data('content');
$('#indhold').load(phpFunctionToCall);
var loginBox = $("#dashboard_box");
if (loginBox.is(":visible"))
loginBox.fadeOut("fast");
else
loginBox.fadeIn("fast");
return false;
});
$("#dashboard_box").hover(function(){
mouse_is_inside=true;
}, function(){
mouse_is_inside=false;
});
$("body").click(function(){
if(! mouse_is_inside) $("#dashboard_box").fadeOut("fast");
});
});
--- PHP (shortened)---
function load_settings_panel($settingOnRequest) {
return $settingOnRequest;
}
$result = call_user_func('load_settings_panel', $_GET['method']);
echo($result);
I am very new with Ajax.
i am using the following javascript function to get the value from the list those user select the li.
but using this function each time the page is reloading. i am trying to use ajax using this function.how can i use ajax with this need syntax.
My function:
<script type="text/javascript" language="javascript">
function pagelim(index)
{
var page_lim=$('#page_num li').get(index).id;
self.location="<?php echo get_option('head'); ?>"+'?details&limit=' + page_lim ;
}
</script>
<script type="text/javascript" language="javascript">
function dateby(index)
{
var date_by=$('#sort-by-date a').get(index).id;
var cls=document.getElementById(date_by).className;
if(date_by=="ASC")
{
date_by="DESC";
}
else
{
date_by="ASC";
}
self.location="<?php echo get_option('head'); ?>"+'?details&sort=' + date_by ;
}
</script>
Value get from list:
<div class="sort-links">
<span class="by-date" id="sort-by-date">Sort by: <a href="#" id='<?php _e($sort_by)?>' class='<?php _e($class)?>' onclick="dateby($(this).index())" >Date</a>
</span>
//list to select value
<span id="view-on-page">View on Page: <?php if($lim=="") { _e($limit); } else { _e($lim); } ?>
<ul id="page_num">
<li id="5" onclick="pagelim($(this).index())">5</li>
<li id="10" onclick="pagelim($(this).index())">10</li>
<li id="15" onclick="pagelim($(this).index())">15</li>
</ul>
</span>
</div>
Welcome to the wonderful world of functional programming.
I'm assuming you are doing a "get" request based on "index" which is a url? If that's the case, then you need to provide a callback.
$('#page_num li').get(index. function(id) {
var page_lim = id; // assuming that's what you sent back.
self.location="<?php echo get_option('head'); ?>"+'?details&limit=' + page_lim ;
});
Notice that you have to put everything in a function that is called after the ajax request is finished. I'm assuming that all you are sending back from the request is the id you need.
jQuery AJAX calls are asynchronous, meaning that the the function $(...).get(url, callback); returns a value BEFORE the AJAX call has finished. That callback function only happens after the AJAX call is completed. I'd advise some time spent with the jQuery API documentation.
You might also Google "javascript functional programming" and see if you can get an explanation of how JavaScript (and thus jQuery) does not always return the value you expect from functions. It's very different from other languages like PHP or ASP.NET in that regard.
Hi hope this will help you... Create a div (say "MyDiv") and put all the elements which you want to change dynamically(without page refresh)... Then try jQuery.load() method...Like
<div id = "MyDiv">
<div class="sort-links">
<span class="by-date" id="sort-by-date">Sort by: <a href="#" id='<?php _e($sort_by)?>' class='<?php _e($class)?>' onclick="dateby($(this).index())" >Date</a>
</span>
//list to select value
<span id="view-on-page">View on Page: <?php if($lim=="") { _e($limit); } else { _e($lim); } ?>
<ul id="page_num">
<li id="5" onclick="pagelim($(this).index())">5</li>
<li id="10" onclick="pagelim($(this).index())">10</li>
<li id="15" onclick="pagelim($(this).index())">15</li>
</ul>
</span>
</div>
</div> //end of MyDiv
Then change your script like
<script type="text/javascript" language="javascript">
function pagelim(index)
{
var page_lim=$('#page_num li').get(index).id;
$("#MyDiv").load("<?php echo get_option('head'); ?>"+'?details&limit=' + page_lim);
}
</script>
<script type="text/javascript" language="javascript">
function dateby(index)
{
var date_by=$('#sort-by-date a').get(index).id;
var cls=document.getElementById(date_by).className;
if(date_by=="ASC")
{
date_by="DESC";
}
else
{
date_by="ASC";
}
$("#MyDiv").load("<?php echo get_option('head'); ?>"+'?details&sort=' + date_by);
}
</script>
Please note that I havnt tested this...
Its very simple to use jQuery to perform AJAX requests... So pls refer this page
Try binding to the click event of your links. This way you can remove any inline javascript and its all neatly contained in your function.
$("li a").click(function() {
//should alert the id of the parent li element
alert($(this).parent.attr('id'));
// your ajax call
$.ajax({
type: "POST",
// post data to send to the server
data: { id: $(this).parent.attr('id') }
url: "your_url.php",
// the function that is fired once data is returned from your url
success: function(data){
// div with id="my_div" used to display data
$('#my_div').html(data);
}
});
});
This method means your list elements would look something like,
<li id="5">5</li>
This doesn't look ideal though as id="5" is ambiguous.
Try something like,
<li class="select_me">5</li>
then your click event binding can look like this,
// bind to all li elements with class select_me
$("li.select_me").click(function() {
// alert the text inside the li element
alert($(this).text());
});
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.