Passing link with parameters with Jquery - php

I have this link:
<a id='delete' href='/add/delete.php?iid=XXXXX'>#</a>
And I want to pass it on through Jquery so the page doesn't refresh. However, I'm having a difficult time making that happen. All of the click events and ajax I've tried with Jquery have been unsuccessful.
Basically, I want the ajax to send delete.php the value in the iid parameter.

Here try this the href='1' is the id you want to delete, also to replace the text it finds the id="d1":
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(function(){
$(".delete").click(function(e){
var del_id = $(this).attr('href');
e.preventDefault();
$.post("/add/delete.php", { iid: del_id } ,function(data){
//change the link to deleted
$('#d'+del_id).replaceWith('Deleted');
});
});
});
</script>
</head>
<body>
<a class='delete' id="d1" href='1'>Delete</a>
<a class='delete' id="d2" href='2'>Delete</a>
<a class='delete' id="d3" href='3'>Delete</a>
<a class='delete' id="d4" href='4'>Delete</a>
</body>
</html>

$(function(){
$("#delete").click(function(e){
e.preventDefault();
$.post("../add/delete.php", { iid: "xxx" } ,function(data){
//do whatever with the result which is in the variable data.
alert(data)
});
});
});
Since it is a delete, use POST. Otherwise some crawlers will crawl your delete page and you will see your tables are empty one fine morning.
EDIT : You can associate the value to be passed with the anchor tag in someway. Ex :Change your id tag to be in this format del-YouIdTobe deleted ( Ex : del-1,del-2 etc..)
<a id='delete' href='#' id="del-1>Delte 1 </a>
<a id='delete' href='#' id="del-2>Delte 2 </a>
<a id='delete' href='#' id="del-3>Delte 3 </a>
Script
$(function(){
$("#delete").click(function(e){
e.preventDefault();
var val=$(this).attr("id").split("-")[0];
$.post("../add/delete.php", { iid: val } ,function(data){
//do whatever with the result which is in the variable data.
alert(data)
});
});
});

Related

ajax and php and sql

I have a list of items on my page from a DB table
I am trying to change the glyphicon when checked
<div class="div1">
<span id=".<?php echo $row['id']; ?>" style="color:black;" class="glyphicon glyphicon-eye-open"> </span>
</div>
this is the script on the top of my page:
<script>
$(document).ready(function(){
$(".div1").click(function(){
$(".div1").load("clicked.php");
});
});
</script>
clicked.php looks like:
<span id="<?php echo $row['id']; ?>" style="color:black;" class="glyphicon glyphicon-ok"> </span>
The problom is the when I click on one item - all the items change there glyphicons
What am I doing wrong?
You just have to remove & add new class:
$(document).ready(function(){
$(".div1").click(function(){
$(this).children('span').removeClass('glyphicon-eye-open');
$(this).children('span').addClass('glyphicon-ok');
//Here you can add ajax call
});
});
There is no need to go all the way to the server to get a new span when all you are doing is removing a class and adding a new class to a span.
Also using the right scope, $(this) will stop it effecting all your div1 elements.
<script>
$(document).ready(function(){
$(".div1").click(function(){
//$(".div1").load("clicked.php");
$(this).children('span').removeClass('glyphicon-eye-open');
$(this).children('span').addClass('glyphicon-ok');
});
});
</script>
And to make the code toggle from one to another on each click
<script>
$(document).ready(function(){
$(".div1").click(function(){
if ( $(this).children('span').hasClass('glyphicon-ok') ) {
$(this).children('span').removeClass('glyphicon-ok');
$(this).children('span').addClass('glyphicon-eye-open');
} else {
$(this).children('span').removeClass('glyphicon-eye-open');
$(this).children('span').addClass('glyphicon-ok');
}
});
});
</script>

AJAX in PHP function is applying to every next instance of the function

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>

click event not call event after load `btn` with `ajax`

I have a page that loaded with ajax complete,
I have buttons on the page (load with ajax), so I want after click the button run an alert event,
I try bind,delegate,live,on Event to attach the Event to handler but no result.
I'm try add test btn manually and that call the event but the buttons that load via ajax not call Event.
My html code:
<body>
<a href='#' class='insert_cm'>test btn</a>
<div class="header"></div>
<div class="wrap">
<div class="rightmenu"></div>
<div class="content">
</div>
</div>
</body>
my JQuery code:
$(function(){
$(".header").load("header.html");
$(".rightmenu").load("sidebar.html");
$.ajax({
type:'POST',
url:'timeline.php',
success:function(data){
$(".content").html(data);
}
});
//insert comment after click the cm-btn
$( ".insert_cm" ).live( "click", function() {
alert( "User clicked on 'foo.'" );
})
});
and the php code:
<?php
include('db_inc.php');
include("myfunc.php");
$functionId=$_POST[functionId];
switch($functionId){
case "":
$music_query = $connection->query("SELECT * FROM music LIMIT 15") or die($connection->error);
while($music = $music_query->fetch_array()){
$music_id=$music['msuic_id'];
$music_thumb =$music['music_thumb'];
$music_name=$music['file_name'];
echo "<div class='music-item'>
<div class='music-avatar'>
<img src=admin/thumb/$music_thumb alt='avatar'>
</div>
<div class='music-post'>
<h3> $music_name <a href='#' class='like_music' >لایک</a></h3>
<p> $music_composer </p>";
$comment_query=$connection->query("SELECT * FROM comments where f_music_id = '$music_id'") or die($connection->error);
while($comments = $comment_query->fetch_array()){
$username = get_username($comments['f_user_id']);
echo "
<div class='username_comment'>
<h4> $username <span>:</span></h4>
$comments[comment];
</div>
";
}
echo "<textarea id='txt_cm' name='txt_cm'></textarea>
<a href='#' class='insert_cm'>insert comment</a>";
}
}
?>
always use $(document).on() for dynamically created element if you want to bind an event to them.
$(document).on("click", ".insert_cm", function() {
alert( "User clicked on 'foo.'" );
return false;
});
the event binder should sit on document level so that it recognize whenever there are more elements added to DOM
more info on $(document).on() : Is it possible to capture keydown globally on dynamically added text inputs?
Use .on() with updated syntax in the jQuery version > 1.8:
$(".content").on( "click",".insert_cm", function() {
alert( "User clicked on 'foo.'" );
})
Syntax:
$(selector/Closest parent).on(event,target,function(){});
That is called EventDelegation!
Where .content reffers to the closest parent element, you can also use document, document.body too.
Try:
$(document).on("click",".insert_cm",function() {
alert("User clicked on 'foo.'");
return false;
});

change the div content based on the $_GET value

I have a main php file where i have a 'navbar' with links to various pages, on click of the 'navbar' item i want the content of the div replace with the respective page.
navbar.php:
<li id="nav-home"><a class="button" href="main.php">Home</a></li>
<li id="nav-attn"><a class="button" href="?nav=page1.php">Page1</a></li>
<li id="nav-tran"><a class="button" href="?nav=page2.php">Page2</a></li>
<li id="nav-mr"><a class="button" href="?nav=page3.php">Page3</a></li>
main.php:
<script>
$(document).ready(function() {
$('#content').load('<?php echo $_GET['nav'] ?>');
});
</script>
With this code am expecting that on click of the navbar item the div content has to change to respective page reference.
what i found is, for example when i click on page1 my url is being changed to main?nav=page1.php, but the script to change the div content is not triggered at all.
Please correct me however i don't want to change the link to '#'.
<script>
$(document).ready(function() {
$('uL#navbar a').click(function(e){
e.preventDefault();
$('#content').load($(this).attr('href'));
});
});
</script>
You may try this
$(document).ready(function() {
$('ul li a.button').on('click', function(e){
e.preventDefault();
$('#content').load($(this).attr('href'));
});
});
You need to use AJAX for it
<script>
$(function(){
$('.button').on('click', function(e){
e.preventDefault();
$('#content').load($(this).attr('href'));
});
})
</script>
<li id="nav-home"><a class="button" href="main.php">Home</a></li>
<li id="nav-attn"><a class="button" href="?nav=page1.php">Page1</a></li>
<li id="nav-tran"><a class="button" href="?nav=page2.php">Page2</a></li>
<li id="nav-mr"><a class="button" href="?nav=page3.php">Page3</a></li>
<div id="content"></div>
Try;
$(document).ready(function() {
$('.button').on('click', function(e){
e.preventDefault();
$('#content').load($(this).attr('href'));
});
});
in your php, change code so that the echo look like;
<li id="nav-attn"><a class="button" href="yourpage.php?nav=page1.php">Page1</a></li>

How can I show array and button by click?

I have a simple table with buttons: <button class='btn btn-info' href='#'>More</button>, and I need that when user click by "More" button then array ($records, for example) and "Less" button will be shown under "More" button. For example, $records[0]="1", $records[1]="2". Please, I don't know JavaScript and JQuery very well, but I need to do it using Ajax. So, I very need your help. Thank you.
UPDATE:
$("button.btn-info").click(function() {
alert('click');
});
It's code for clicking by "More button", but I don't know how to write $records array under this button with "Less" button (which will hide the array by click) at the end.
PHP (sample only):
<?php
$records = array(1,2,3,4,5,6,7);
?>
HTML:
<html>
<body>
<div id="more">
<button>More</button>
</div>
<div id="less" style="display: none;">
<div id="codes" style="border-top: 1px dotted #d0d0d0;">
<?php
for($i=0; $i<count($records); $i++) {
printf("$records[%d] = %d<br />",$i,$records[$i]);
}
?>
</div>
</div>
</body>
</html>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
JS:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var i = 1;
$('div#more button').click(function() {
$('div#less').toggle();
if (i) { $(this).html('Less'); i=0; } else { $(this).html('More'); i=1; }
});
});​
</script>
P.S. Do not forget to include the jQuery plugin or this won't work.
EDIT: There it is jquery.min.js
Demo fiddle: http://jsfiddle.net/fe9wv/
You can use Jquery for this, below is a rough example
Assumptions:
ALL the buttons have an ID(required for fetching data through ajax)
The table cell in which you have the button ,also has a with display style as hidden and class as 'dataspan'
$('.btn-info').live('click',function(){
var id = $(this).attr('id');
$.ajax({
type : "POST",
url: "YOUR TARGET URL",
dataType : "HTML",//you can also use JSON
data : 'id=' + id,
success: function(data)
{
$(this).siblings('.dataspan').html(data);
$(this).siblings('.dataspan').append('<button class="hidedata" value="HIDE"/>');
$(this).siblings('.dataspan').show();
}
});
});
//FOR hiding the data
$('.hidedata').live('click' , function(){
$(this).siblings('.dataspan').hide();
});
Please note that as per the latest JQuery release the .live function has been deprecated, if you are using the latest version I will strongly recommend you to switch to delegate function

Categories