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());
});
Related
I have this code:
<div class="menuList">
<li><img src="/images/icon/arena.png" alt="">Arena<span class="green"> (+)</span>
</li>
</div>
And i want to remove <span class="green"> (+)</span> after users click that link.
Anyone can help me (php code)?
As already mentioned, PHP is not the ideal language to do this in. But, if you need to use PHP, here is how you could do it.
Set a session variable on the /arena/ page, like this;
<?php
session_start();
$_SESSSION['visited'] = 1;
?>
Then, use PHP to check for the session variable in your HTML code like this:
<div class="menuList">
<li><a href="/arena/"><img src="/images/icon/arena.png" alt="">Arena
<?PHP
If(isset($_SESSION['visited'])){
echo '<span class="green"> (+)</span>';
}
?>
</a>
</li>
</div>
You will need to add session_start() to the top of the page wherever you are accessing session variables, before you output anything to the page (e.g. DOCTYPE declaration.)
in Jquery you may do this like
<script>
$(function(){
$('.menuList').find('a').click(function(){
$(this).children('.green').remove();
});
});
</script>
You can accomplish this by adding this javascript to your page:
<script>
window.onload = function() {
var a = document.querySelector('.menuList a');
a.onclick = function() {
var span = a.querySelector('.green');
a.removeChild(span);
}
}
</script>
OR if you're using jQuery:
<script>
$(document).ready(function(){
$('.menuList').find('a').click(function(){
$(this).find('.green').remove();
});
});
</script>
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 have this javascript :
<script type="text/javascript">
$(document).ready(function($) {
$('#target-share ul li').click(function() {
$('input#shareto').val($(this).data('val'));
});
});
</script>
and it really works as I expected. but when I add this another javascript to do drop-down animation, that javascript not working anymore :
<script type="text/javascript">
$(document).ready(function() {
$("#select-shareto a").click(function () {
var newClass = $(this).find("span").attr('class');
var newText = $(this).find("span").text();
$("#select-shareto a").removeClass("selected");
$(this).addClass("selected");
$("a#to-chosen span").removeClass().addClass(newClass).text(newText);
$("a#to-chosen").toggleClass("opened");
$('#select-shareto').slideToggle('fast');
return false;
});
$('a#to-chosen').click(function() {
$(this).toggleClass("opened");
$('#select-shareto').slideToggle('fast', function() {
// Animation complete.
});
});
});
</script>
those javascript actually affected on this HTML code :
<div id="target-share">
<span class="to-admin">Admin</span>
<ul id="select-shareto">
<li data-val="0-1">
<span class="to-Finance">Finance</span>
</li>
<li data-val="1-1">
<span class="to-admin-private">Admin Private</span>
</li>
<li data-val="1-0">
<span class="to-ceo">CEO</span>
</li>
<li data-val="0-0">
<span class="to-ceo-private">CEO Private</span>
</li>
</ul>
<input id="shareto" type="text" value="0-1" name="shareto">
</div><!-- #target-share -->
any idea how to make those 2 javascript works side-by-side? thanks.
$("#select-shareto a").click(function () {
...
return false;
});
Hereby, you stop the further propagation of this event - other handlers for this click event won't be called any more. Instead, use this:
$("#select-shareto a").click(function (e) {
e.preventDefault();
...
});
(Demo at jsfiddle.net)
I'm assuming you tried to insert the code where the comment animation complete is and if so you just need to put the code:$('#target-share ul li').click(function() { $('input#shareto').val($(this).data('val'));});
Your code is already wrapped in a $(document).ready so you don't need another one.
i have a link that contain some data
eg
<li><?php echo $result22['category']; ?></li>
i want this link to pass this $result22['category']; value to the ajax function
am trying this
<script type="text/javascript">
function getcategory(cat)
{
var id = cat.value;
alert("hi" + id);
}
</script>
but its shows hi undefined in alert box
what am doing wrong ?
am not getting correct value of $result22['category']; in alert box
Since cat is an a element, it won't have a value property. Use textContent or innerText (or innerHTML if there could be child elements):
function getcategory(cat) {
var id = cat.textContent;
alert("hi" + id);
}
It's generally only form controls that have a value property (the input element for example).
Why not just do this?
<li><?php echo $result22['category']; ?></li>
<script type="text/javascript">
function getcategory(content) {
alert(content);
}
</script>
Try this..
<li><?php echo $result22['category']; ?></li>
<script type="text/javascript">
function getcategory(cat)
{
//var id = cat.value;
alert("hi" + cat);
}
</script>
I would recomend you output into the function if your are not using a separate javascript file to bind the onClick handler that is :
<li>
<a href="" onclick="getcategory('<?php echo $result22['category']; ?>');">
<?php echo $result22['category']; ?>
</a>
</li>
hello
<script type="text/javascript">
function getcategory(ele) {
var id = ele.innerHTML;
alert(id);
}
</script>