why the code below doesn't do its job ?
I just need POST via javascript id content on click btn.
this code works properly in many other situations but not here that i'm using twitter bootstrap modal.
thanks.
<button id="<?php echo $id; ?>" class="btn btn-warning" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<span class="glyphicon glyphicon-trash"></span> delete id
</button>
<script type="text/javascript">
//delete id
$(document).on('click','.btn-warning',function(){
var element = $(this);
var del_id = element.attr("id");
var info = 'id=' + del_id;
if(confirm("are you sure ?")){
$.ajax({
type: "POST",
url: "page.php",
data: info,
success: function(){ window.location.href = "/logout.php"; }
});
}
return false;
});
</script>
PHP
if($_POST['id']){
$id=$_POST['id'];
$id = mysql_real_escape_string($id);
...
info = {'id' : del_id };
Try to send data as array.
First, I think you should be using isset(variable) in the PHP:
if (isset($_POST['ID'])
{
...
Second, it doesn't work because you need to set the data and a key -> value array.
data: {id: "ID_NUMBER"}
Look over the examples on Jquery's site: https://api.jquery.com/jQuery.ajax/
I would also suggest using a unique ID property or a new/unique class proverty, and then using that to add the onClick event.
Related
Basically what I have is a lot of <a> tags which are queried from a database. They are displayed and when a user clicks on one of the tags then it fires an ajax function. Right now one button does the work of all the buttons.
The tags look like this:
<a value='<?php echo $setit ?>' class='button' setdata='<?php echo
$setit ?>'><?php echo $setit ?></a>
And the ajax function looks like this:
$(document).ready(function(){
$(".button").click(function(event){
var data1=$(this).data('setdata');
$.ajax({
url: "set_freq.php",
type: "POST",
data: {"set_freq":data1},
success: function(data){
data = JSON.stringify(data);
console.log(data);
}
});
});
});
I'm thinking that I need to make the button id-s unique so the function can only get the correct button value. Am I on the right track? How can it be done?
There is no need to make the ids of your buttons unique. You could simply use
$('.button').click(function(e) {/*ajax*/});
to query all buttons. Note that you have to query using a . (for class names) instead of a # (for ids). Inside of the function $(this) will always refer to the link that was clicked.
On the other hand your id's should be unique. If you do not mind that they change on every refresh, you might use uniqueid:
<a id="<?= uniqueid(); ?>" ... >
Else your database should have an unique index that you might use. But i think there is no reason to set an id at all since your JavaScript is fine without.
$("#button") targets an element with id="button" but you certainly want to target element with class="button" as seen in your HTML... So you should replace the # with a dot, just like in CSS. $(".button")
Also, you do not need to use ID for this, even if you have multiple buttons, the eventHandler receives this as the target element, so you'll always have access to the "current" data.
Also I think you have wrong format for data property.
The right is here:
<a value='<?= $setit ?>' class='button' data-set='<?= $setit ?>'><?= $setit ?></a>
Just change your a tag as follows.
<a class='button' data-setdata='<?php echo $setit ?>'><?php echo $setit ?></a>
Replace your tag :
<a value='<?php echo $setit ?>' class='button' setdata='<?php echo
$setit ?>'><?php echo $setit ?></a>
To:
<a class='button' id='setit'><?php echo $setit ?></a>
and replace your ajax function :
$(document).ready(function(){
$(".button").click(function(event){
var data1=$(this).data('setdata');
$.ajax({
url: "set_freq.php",
type: "POST",
data: {"set_freq":data1},
success: function(data){
data = JSON.stringify(data);
console.log(data);
}
});
});
});
To :
$(document).ready(function(){
$(".button").click(function(event){
var data1 = document.getElementById("setit").innerHTML
$.ajax({
url: "set_freq.php",
type: "POST",
data: {"set_freq":data1},
success: function(data){
data = JSON.stringify(data);
console.log(data);
}
});
});
});
I know similar questions to this have been asked before but I don't see an answer that suits my question. I have a div that triggers a jquery script which stores an id. I can get the id into a variable in the jquery but I want to then assign that id to a PHP variable that exists on the same page.
So far this is what I've got. Here is my div that exists in index.php:
echo '<div id="'.$unit_id.'" class="dropdown unit '.$unit_size.' unit-'.$unit_number.' '.$unit_status.' data-unit-id-'.$unit_id.'">';
And here is my jquery that I call in from functions.php:
<script>
$('.unit.available').click(function(){
var unit_id = $(this).attr('id');
$.ajax({
type: 'post',
data: {id: unit_id}, //Pass the id
});
});
</script>
I want to pass the unit_id into a variable on index.php called $getID but I can't seem to find a way of getting in there. I've tried using post but there really isn't a form being submitted. It's just a dive being clicked on.
You must change your id in your <div> and set it to fetch the variable sent by jQuery. Other than that, your jQuery script looks fine.
Here's how I would do it:
# Fetch the variable if it's set.
<?php $unit_id = (isset($_POST["id"])) ? $_POST["id"] : null; ?>
# Echo it as the id of the div.
<div id = "<?= $unit_id; ?>" class = "dropdown unit"></div>
EDIT:
The PHP code above is equal to:
# Fetch the variable if it's set.
<?php
if (isset($_POST["id"])):
$unit_id = $_POST["id"];
else:
$unit_id = null;
endif;
?>
Assign id to div id attribute like this, Use:
<div id="<?php echo $unit_id; ?>" class="dropdown unit"></div>
Try this hope it will work
<div id="<?php echo $unit_id;?>" class="dropdown unit"></div>
<script>
$('.unit.available').click(function(){
var unit_id = $(this).attr('id');
$.ajax({
type: 'post',
'id='+unit_id, //Pass the id
});
});
</script>
What you mean by this '$unit_id' in div ID. Just put the code in PHP Tag, while working with PHP in HTML pages use the code inside PHP tags.
Availale PHP tags : <?php echo $unit_id ?> (or) <?=$unit_id ?> (short tag).
Change your div with :
<div id="<?=$unit_id ?>" class="dropdown unit"></div>
or
<div id="<?php echo $unit_id ?>" class="dropdown unit"></div>
Then your script will be work
<script>
$('.unit.available').click(function(){
var unit_id = $(this).attr('id');
// to check whether value passing or not
console.log(unit_id);
$.ajax({
type: 'post',
data: {id: unit_id}, //Pass the id
});
});
</script>
Good day sir/ma'am I am a new programmer, I would like to ask how to post data like the functionality of form that when submitting the form the URL in action will display using javascript.
"WITHOUT USING A FORM" or using xmlHTTP that not return to main page
sample is
HTML
<input type="button" value="revise" onclick="revisetask(<?php echo $id; ?>)">
JS
function revisetask(idtask)
{
//In this function sir i would like to post here
}
Im very sorry if my english is too bad.. thanks in advance :D
You can use javascript for submitting the values of input boxes,
to do so,
write a javascript function which will read all your input boxes values into javascript variables,
Prepare a URL, and call that URL using window.location.href
function SubmitMyForm
{
var Firstname = document.getElementbyId('FirstName').value;
var Lastname = document.getElementbyId('LastName').value;
var URL="myDBoperations.php?firstname="+Firstname+"&lastname="+Lastname;
window.location.href= URL;
}
On the operations form you will receive these value in GET.
Hope this will help you.
U can use ajax for this. U don't need a form for ajax post, and it won't refresh the page too.
Below is an example code
<input type="text" id="test_name" />
<input type="button" value="Submit" obclick="save_this()" />
<script type="text/javascript">
function save_this(){
var text = $('#test_name');//stores te value in text field
$.ajax({
url: 'http://example.com/test.php',//your URL
type: 'POST',
data: { text: text },
success: function(data){
alert(data);
}
});
}
</script>
test.php
<?php
echo $_POST['text'];
As I've seen in this code:
<input type="button" value="revise" onclick="revisetask(<?php echo $id; ?>)">
I assume and believe that the reason why you don't want to use form because you want your $id to be submitted through javascript/jquery. But alternatively, you could just do it this way:
HTML:
<form method = "POST" action = "updatetask.php">
<input type = "hidden" value = "<?php echo $id; ?>" name = "taskid" id = "taskid"/>
<input type = "submit" value = "UPDATE" name = "updatebutton">
</form>
PHP:
<?php
$taskid = $_POST['taskid'];
?>
In the above code I just set the type hidden and which contains the value of your $id in which would be post in your Php file.
UPDATE:
If it still doesn't fit to what you want then you could just have this other alternative which will be using the GET method: <a href = "updatetask.php?id='<?php echo $id; ?>' REVISE </a>"
That's the only option you have. and if you don't want to show the id in your url then you could just use URL Rewriting (refer to this link: https://www.addedbytes.com/articles/for-beginners/url-rewriting-for-beginners/)
Hope this helps.
I am playing around with a todo list I learned online. Trying to add ajax into it.
Works well when I try to add an item. When an item is added there's a button says 'Mark as done' so I can click on it and then there will be a 'Delete' button which is used to delete the item from the list and database.
Adding with ajax works fine but after adding, if I click on 'Mark as done' button, the page goes to the url of done-ajax.php?as=done&item=110
where 110 is just the id of the item in database.
I have to go back to the index page. And when I go back to index page the item will be marked done already because the 'Mark as done' worked but somehow would go to the url instead of staying in the index page.
This is one of the problems found that I have no idea where to look for the result.
Another problem is if I add the item and refresh the page then clicked 'Mark as done' it wouldn't go to the url instead the ajax works and a 'delete' button would show up but some how the delete button wouldn't work. I have to refresh the page in order for the 'delete' button to work with ajax.
I checked the attributes and looked around the codes but couldn't seem to find where is causing the problem.
my index codes are as below
<div class="list">
<h1 class="header">ET's To do lists.</h1>
<?php if(!empty($items)): ?>
<ul class="items">
<?php foreach($items as $item): ?>
<li>
<span class="item<?php echo $item['done'] ? ' done' : '' ?>">
<?php echo $item['todoText']; ?>
</span>
<?php if($item['done']): ?>
Delete Task
<?php endif; ?>
<?php if(!$item['done']): ?>
Mark as done
<?php endif; ?>
</li>
<?php endforeach; ?>
</ul>
<?php else: ?>
<p class="empty">You haven't added any items yet.</p>
<ul class="items"></ul>
<?php endif ?>
<form class="item-add" action="add.php" method="post">
<input type="text" name="todoText" placeholder="Type a new item here." class="input" autocomplete="off" required>
<input type="submit" value="Add" class="submit">
</form>
</div>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="js/ajax.js"></script>
my ajax.js file
$(document).ready(function() {
//Action when submit is clicked
$(".submit").click(function(e){
var todoText = $("input[name='todoText']").val();
e.preventDefault();
//Ajax for adding todoText
$.ajax({
method: "POST",
url: "add-ajax.php",
data: {todoText: todoText},
dataType: "json"
})
.done(function(data){
$('p.empty').empty();
$('input.input').val('');
$('ul.items').append('<li>'+todoText+' '+
'<a href="done-ajax.php?as=done&item=' + data.id +
'" class="done-button">Mark as Done</a></li>');
})
});
//Action when done button is clicked
$(".done-button").click(function(e){
e.preventDefault();
//making sure only work with the current element
var $clicked = $(this);
//get the href attribute value and parse it to get the item # which is the item's id
var attrValue = $clicked.attr('href');
var parseAttrValue = attrValue.split('&');
var parseItem = parseAttrValue[1].split('=');
var item = parseItem[1];
//Ajax for Mark as Done Button
$.ajax({
method: "GET",
data:{as: 'done', item: item},
url: "done-ajax.php"
})
.done(function(){
$clicked.prev().addClass('done');
$clicked.removeClass('done-button').empty();
$clicked.addClass('delete-button').text('Delete Task');
$clicked.removeAttr('href');
$clicked.attr('href','delete-ajax.php?as=delete&item='+item);
});
});
//Action when delete button is clicked
$(".delete-button").click(function(e){
e.preventDefault();
//making sure only work with the current element
var $clicked = $(this);
//get the href attribute value and parse it to get the item # which is the item's id
var attrValue = $clicked.attr('href');
var parseAttrValue = attrValue.split('&');
var parseItem = parseAttrValue[1].split('=');
var item = parseItem[1];
//Ajax for Mark as Done Button
$.ajax({
method: "GET",
data:{as: 'delete', item: item},
url: "delete-ajax.php"
})
.done(function(){
$clicked.closest('li').remove();
$clicked.remove();
});
});
});
my done-ajax.php file
<?php
require_once 'app/init.php';
if (isset($_GET['as'], $_GET['item']))
{
$as = $_GET['as'];
$item = $_GET['item'];
switch ($as) {
case 'done':
$doneQuery = $db->prepare("
UPDATE phptodolist_items
SET done = 1
WHERE id = :item
AND user = :user
");
break;
}
}
my delete.php file
<?php
require_once 'app/init.php';
if (isset($_GET['as'], $_GET['item']))
{
$as = $_GET['as'];
$item = $_GET['item'];
switch ($as) {
case 'delete':
$doneQuery = $db->prepare("
DELETE FROM phptodolist_items
WHERE id = :item
AND user = :user
");
break;
}
}
(By the way, thanks to few that helped out with the ajax earlier)
Thanks a lot to everyone in advance :D
You are binding your event handlers when the page opens / the DOM is ready, on $(document).ready(). Then you add new items using ajax but the links in these items will not have your event handlers bound to them.
You can use event delegation to make sure that the events are also automatically bound to newly added items.
You can do that changing:
$(".delete-button").click(function(e){
e.preventDefault();
...
to something like:
$(".list").on('click', '.delete-button', function(e){
e.preventDefault();
...
where the $(".list") can be any element that contains the newly added elements and that is on the page when this code executes.
This applies to all event handlers that you want to bind to elements that are not yet on the page when the DOM is ready.
How do I use jquery to remove this div tag created in php? Specifically, After pressing the delete button I want to remove one div. I have several.
Here is my PHP code:
<?php
// For each book...
while ($row = mysql_fetch_assoc($result)){
echo '<div class="task-list" id="div_'.$row['uid'].'"><table>';
echo "<tr>";
echo "<td><b>".$row['title']."</b></td></tr>";
echo "<tr><td>".$row['author']."</td></tr>";
echo '<tr><td><img src="'.$row['image_url'].'" width="50" height="100" /></td></tr>';
echo '<tr><td><button class="btn cmt_list" name="cmtList" id="cmt- '.$row['uid'].'"value = "hide/show"/>Show</button> </td></tr>';
echo '<tr><td><button class="btn btn-danger delete_bk" name="deleteItem" id="'.$row['uid'].'" />Delete</button></td></tr>';
echo "</table></div>";
?>
This is my javascript:
//deleting a book from DB when user clicks "Delete" button
$(".delete_bk").on("click", function() {
var book_id = $(this).attr('id');
$.ajax({
type: "GET",
url: "delete_bk.php",
data: {book_id: book_id}
})
.done(function() {
var id = $(this).attr('id');
$('#div_'+id).remove();
alert("Data deleted");
});
});
Which div you would delete?
In jQuery you can simply do:
$(div_to_remove).remove();
try this one
$(".delete_bk").on("click", function() {
var book_id = $(this).attr('id');
$.ajax({
type: "GET",
url: "delete_bk.php",
data: {book_id: book_id},
success:function(){
$('#div_'+book_id).remove();
alert("Data deleted");
}
})
});
try this
$("#deletebtnid").click(function(e){
$("#divid").remove();
});
$('.task-list').remove();
and if you just want to remove the first div:
$('.task-list').first().remove();
you can add the following code somewhere in your html:
<script>
$(document).ready(function() { $('.task-list').remove(); });
</script
Note:
start with . for class names and # for ids to find elements in jQuery.
Example: $('.YOURCLASSNAME') or $('#YOURID')
try this code
$(document).on('click','.delete_bk', function(){
$('#bookdiv').remove();
});
Try this
$(document).on('click', '.delete_bk', function(){
var id = $(this).attr('id');
$('#div_'+id).remove();
});
Here in line,
<div class="task-list" id="bookdiv"><table>
you need to apply ID like
<div class="task-list" id="div_'.$row['uid'].'"><table>
seems that you have the id "bookdiv" more that once - html ids have to be unique... change div -> add a data-attribute like data-delete="$id_of_your_div" to your button and then:
Example
Html:
<div class="bookdiv task-list" id="book-5813">
Button:
<button class="delete_bk" ... data-delete="#book-5813" />
Delete JS
$(document).on('click','.delete_bk', function(){
var delete = $(this).data('delete');
$(delete).remove();
});