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>
Related
Hello there i'm having trouble in getting the id's of a div that is stored in an foreach loop. What i want to do is to get the id one by one in jquery as the ids are looping in the php code.
<script>
$(document).ready(function(){
$(".cat-anchor").click(function(){
var target=('get the id of cat-title class here')
});
});
</script>
<?php
foreach($cat_arr['cat_pro'] as $cat_name){
echo "<div class='cat-back'>";
echo "<a href='#".$cat_name[0]."' class='cat-anchor'>".$cat_name[1]."</a> <br>";
echo "</div>";
}
foreach($cat_arr['cat_pro'] as $mykey=>$myvalues){
echo '<div name="'.$myvalues[1].'" class="cat-title" id="'.$myvalues[0].'">
<h2>'.$myvalues[1].'</h2></div>';
?>
<script>
$(document).ready(function(){
$(".cat-anchor").click(function(){
$(".cat-title").each(function(index, element) {
var target=$(this).attr("id");
});
});
});
</script>
Trying this, you'll get object for each div and use them as as you wish.
<script>
$(document).ready(function(){
$(".cat-anchor").click(function(){
var target = $(this).attr('id');
});
});
</script>
Just Google for how to retrieve an element's attribute from jQuery. The .attr() function will help.
<div class="cat-title" id="1"></div>
<div class="cat-title" id="2"></div>
<div class="cat-title" id="3"></div>
<div class="cat-title" id="4"></div>
<input type="button" class="cat-anchor" value="get ids">
<script type="text/javascript" src="jquery.js"></script>
<script>
$(document).ready(function(){
$(".cat-anchor").click(function(){
var target='';
var divs = $(".cat-title");
for (var i = 0; i < divs.length; i++) {
target += divs[i].id;
};
alert(target);
});
});
</script>
First define a variable which increments till the loop completion and also append the same variable at id="your-div-name'.$i.'" as shown below
$i=1
foreach($cat_arr['cat_pro'] as $mykey=>$myvalues){
echo '<div name="'.$myvalues[1].'" class="cat-title'.$i.'" id="'.$myvalues[0].'">
<h2>'.$myvalues[1].'</h2></div>';
$i++;
}
and then when writing your script just execute the loop as no.of times prev loop executes, simultaneously echo the number for div as here. Hope this is clear!
<script>
$(document).ready(function(){
$(".cat-anchor").click(function(){
<?php
for($j=0;$j<=$i;$j++){
echo 'var target=document.getElementById("cat-title'.$j.'").innerHTML;';
}
?>
});
});
</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 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());
});
I have a PHP page which has a div, the div has a PHP includes which includes this file:
<?php
include('mySql.php');
include('Classes.php');
$targetPage = "blogOutput.php";
$noOfPosts = getNumberOfPosts();
$adjacents = 3;
?>
<link rel="stylesheet" type="text/css" href="Styles/Miniblog.css" />
<script src="Scripts/jQuery.js"></script>
<script type="text/javascript">
var page = 1;
$(".Button").click(onClick());
$(document).ready(onClick());
function onClick() {
alert('called');
$("#posts").load("miniBlog.php", function(response, status, xhr) {
if (status == "error") {
var msg = "Error!: ";
alert(msg);
}
});
page++;
}
</script>
<div class="PostTitle">
<h2>What's New!?</h2>
</div>
<div id="posts">
</div>
<a class="BlogButton" href="">Next</a>
I need the function "onclick" to be called without refreshing the page and resetting the "page" variable in javascript. So far, all I've been able to do is make it run the script once. I think that's wrong too, because it's not loading any content. Here's the page:
<?php
echo "I'm here!";
if (isset($_POST['offset'])) {
$offset = $_POST['offset'];
$posts = getPosts($offset);
}
?>
<div class="BlogPost">
<h3><?php echo $posts[0]->Title; ?></h3>
<p><?php echo $posts[0]->Body; ?></p>
<p class="Date"><?php echo $posts[0]->Date; ?></p>
</div>
<div id="divider"></div>
<div class="BlogPost">
<h3><?php echo $posts[1]->Title; ?></h3>
<p><?php echo $posts[1]->Body; ?></p>
<p class="Date"><?php echo $posts[1]->Date; ?></p>
</div>
So, to clarify: I'm not sure why my ajax call isn't working, and I don't know how to load just the div content and not refresh the entire page. Thanks!
You are not able to see content loaded by AJAX because the page is reloading as soon as you click the anchor. Disable the anchor event by using preventDefault() and this should fix it.
<script type="text/javascript">
var page = 1;
$(document).on('click','.BlogButton',function(e){
// stop page from reloading
e.preventDefault();
$("#posts").load("miniBlog.php", function(response, status, xhr) {
if (status == "error") {
var msg = "Error!: ";
alert(msg);
}
});
page++;
});
</script>
Don't call the function in the click method parameter. You have to put the reference to the handler function.
var handler = function onClick () {...}
$("whatever").click(handler);
Change your code to
var page = 1;
$(document).ready(function(){
$(".Button").click(onClick);
onClick();
};
Use this instead of your code
var page = 1;
$(document).on('click','.Button',function(){
$("#posts").load("miniBlog.php", function(response, status, xhr) {
if (status == "error") {
var msg = "Error!: ";
alert(msg);
}
});
page++;
});
Content dose not look too huge.Can't you just hide div (with content already present in it)& show it onclick.
I have a page in php and all over the page I am using the <a tag to link.
For example:
<?php for($i=1;$i<=5;$++) {?>
<a href="abc.php?ref=<?php echo $i ?>"CLick me No. <?php echo $i ?> </a>
<?php } ?>
What I want to do is once we click on the link, jquery load function should called, like
$('#div1').load('abc.php?ref=1'null, function() {
});
but I can't change the php loop and <a tag ...
Thanks
Give each anchor a common class and an attribute that identifies the value of $i:
...
Then attach an on-click function to them:
$('a.numbered-anchors').click(function(e) {
var i = $(this).attr('anchor-id');
$('#div' + i).load(...);
});
You mean something like this:
"CLick me No. <?php echo $i ?>
$('#yourLink').click(function() {
$('#div1').load('abc.php?ref=1'null, function() {
});
});
Bobby
Something like this maybe :
$('a[href^="abc.php"]').click(function(event){
//do whatever you want
$('#div1').load(event.target.href, null, function() {});
});
PHP:
<?php for($i=1;$i<=5;$++) {?>
<a class="anchor-click" href="#" id="<?php echo $i ?>">CLick me No. <?php echo $i ?></a><br />
<?php } ?>
JS
$(function(){
$(".anchor-click").bind("click", function(event){
event.stopPropagation();
$('#div1').load("abc.php?ref="+$(this).attr("id"), null, function() {
});
});
});