I'm trying to create a todo application using php, ajax and mysql.
There should be a button that, once clicked, deletes the item from the screen and the database, but I don't know how to refer that I want to delete a certain item.
(each item has a unique id in the database, also a text and the ID from the list that contains it)
An example of my html would be something like that:
<ul id="list">
<li class="item">
<div class="draggertab">
<img src="imatges/botofletxa.jpg" width="30" height="30">
</div>
<div class="deletetab">
<img src="imatges/botocreu.jpg" width="30" height="30">
</div> <span>Buy some cookies</span>
</li>
</ul>
And I the javascript code would look like that:
$('.deletetab').live('click', function () {
var result = confirm("Are you sure?");
if (result == true) {
$(this).parent().remove();
}
});
But I don't know how to send (using ajax) the information to another php file (which connects to the database), or which variable should I use.
Sorry if that's a silly question, I'm new at programming!
I don't know how you are rendering the list (ul), suppose it's a foreach loop or something of that kind. You can store each item's ID in a hidden field, so that you can access it's value from js:
<ul id="list">
<li class="item">
<input type="hidden" class="hidden_id" value="render_id_here" />
<div class="draggertab">
<img src="imatges/botofletxa.jpg" width="30" height="30">
</div>
<div class="deletetab">
<img src="imatges/botocreu.jpg" width="30" height="30">
</div> <span>Buy some cookies</span>
</li>
</ul>
js:
$('#list').on('click', '.deletetab', function(){
var result = confirm("Are you sure?");
if (result==true) {
var parent = $(this).parent();
$.ajax({
type: 'POST',
data: { idToDelete: parent.find('.hidden_id').val() }, //Find hidden ID field within parent div and read it's value
url: 'delete.php'
}).done(function() { //success callback
parent.remove();
}).fail(function(qXHR, textStatus) { //error callback
alert('Server responded with error status ' + textSatus);
});
}
});
On the server side you need to search the "idToDelete" parameter in posted data.
First, you can put your item's id on data-id attribute of each item.
<li class="item" data-id="{{ item_id"}}>
// the rest of the html
</li>
Then the javascript
$('.deletetab').click(function() {
var $this, $item;
$this = $(this);
$item = $this.closest('.item');
if (confirm('Are you sure')) {
$.post('url_to_delete.php', {id: $item.attr('data-id')}, function(data) {
$item.remove();
});
}
});
Related
Ultimately I'm wanting the user to click on the Landing Page next to an image on either Print or Mug. Then on the Order Page have the button for Print/Mug be active and then the image that's associated be marked as well.
So I have in Landing Page the following code:
<ul class="dropdown-menu">
<li>
Print
</li>
<li>
Mug
</li>
</ul>
Then in the Order Page the following code:
<div class="img-container1 image-container" image_var="main_image.jpg">
<%= image_tag('main_image.jpg') %>
<div class="wk-after">
<div class="centered-wk">
<span class="fa fa-check-circle check-circle"></span>
</div>
<div class="centered-wk wk-select">
SELECTED
</div>
</div>
</div>
My thought process was to then grab from the Order Page the image_var attribute and make it active.
So far I've been using:
<script>
function toggleActive() {
var activeElements = document.querySelectorAll('image_var');
activeElements.forEach(function (el) {
el.classList.remove('active');
});
btn.classList.add('active');
}
</script>
This isn't working. I don't know what the best way to grab the image_var or a url parameter. What am I missing?
I've also tried:
<script>
function toggleActive() {
var activeElements = document.querySelectorAll('[image-var]');
activeElements.forEach(function (el) {
el.classList.remove('active');
});
btn.classList.add('active');
}
</script>
With an update to the div on the container to be image-var to match. Still not touching the image.
I feel like this should be working with jQuery:
<script>
$(function(){
$.url.attr('image')
$.url.attr('type')
});
</script>
Wouldn't this be pulling out the main_image.jpg and then the print from type?
I have a dinamically generated code as follows which lists some files and let the user delete them by clicking on their links:
<div id="filenames">
<div>
<a id="1" class="delete" href="#1984.xls">1984.xls
</div>
<div>
<a id="2" class="delete" href="#1984.xml">1984.xml
</div>
</div>
Each file has its ID. The list is generated via AJAX when the user uploads the files.
When the user clicks a link, before the file is passed to the "delete.php" call, I would like to have a JSON object that lists all the files like this:
{1 : 1984.xls, 2 : 1984.xml}
I managed to made it using an array
var files = [];
$('#filenames').find('a').each(function() {
files.push($(this).attr('href'));
});
But this simply adds to the array the name of the file which is stored inside href.
I don't know how to find both id and attr and create instead of an array a JSON object as said above.
You can do it in following way:
var files = {};
$('#filenames').find('a').each(function() {
files[$(this).attr('id')] = $(this).attr('href');
});
console.log(files);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="filenames">
<div>
<a id="1" class="delete" href="#1984.xls">1984.xls
</div>
<div>
<a id="2" class="delete" href="#1984.xml">1984.xml
</div>
</div>
You have to create an object using {} (and not array []) then affect the key:value to it as files[key] = value when the key is the id of the link and value represented by the href, check the example below.
Hope this helps.
var files = {};
$('#filenames').find('a').each(function() {
var key = $(this).attr('id');
var value = $(this).attr('href');
files[key] = value;
});
console.log(files);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="filenames">
<div>
<a id="1" class="delete" href="#1984.xls">1984.xls
</div>
<div>
<a id="2" class="delete" href="#1984.xml">1984.xml
</div>
</div>
Use bracket-notation to assign value to the object when key is dynamic!
Initialize files as object({}), not as array as you are expecting result as an object
Note: Use .substr(1); if you are suppose to remove #(first character) from string.
var files = {};
$('#filenames').find('a').each(function(i) {
//files[i] = $(this).attr('href').substr(1);;//For index iteration as key
files[this.id] = $(this).attr('href').substr(1); //For ID attribute as key
});
console.log(files);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="filenames">
<div>
<a id="1" class="delete" href="#1984.xls">1984.xls</a>
</div>
<div>
<a id="2" class="delete" href="#1984.xml">1984.xml</a>
</div>
</div>
Please try this code
var files = [];
item = {}
$('#filenames').find('a').each(function () {
item[$(this).attr('id')] = $(this).attr('href');
});
files.push(item);
console.log(files);
I'm wrapping up results of ajax request on div and appending to main div in a page. SO if the array of results returned empty, I would like to alert user, saying that no result found and also provide a link for them to click on. When they click a pop up box carrying products by category would popup. Important thing to notice here is,the products are derived via php and ajax scripts.
So When I use onclick event or directly, nothing happens!!!. But if I call empty or HTML pop up it would work. Also the same php scripts contained pop up would work if I trigger it on page load or in the ajax success function. SO I dont understand why only with on click it doesn't work?
This is the pop up I want to trigger on 'click' event
<section id="browse-search-popup" class="mfp-hide white-popup">
<h1>Browse Courses</h1>
Can't find what you're looking for? Tell us here!
<h2>First, pick a learning Zone:</h2>
<div class="row">
<div class="small-12 medium-8 large-8 medium-centered large-centered columns">
<ul class="small-block-grid-2 medium-block-grid-2 large-block-grid-2">
<?php
$tutor = new register();
$data = $tutor->get_maincat();
$i=0;
foreach($data as $k=>$v)
{
$i++;
?>
<li><div class="mainCat_<?php echo $i;?>" id="<?php echo $v['main_cat_id'];?>"><?php echo $v['main_cat_name'];?></div></li>
<?php
}
?>
</ul>
</div>
</div>
<h2>Then, pick a field:</h2>
<div class="row">
<div class="small-12 medium-12 large-12 columns" id="cat">
</div>
</div>
<h2>Finally, choose your Course:</h2>
<div class="row">
<div class="small-12 medium-12 large-12 columns" class="choosen_subjects">
</div>
</div>
<div class="row">
<div class="small-12 medium-12 large-12 columns" id="sub">
</div>
</div>
<input type="submit" id="done" value="Done">
</section>
Ajax request
$("#search_tutor").submit(function() {
var data = {
"action": "test"
};
var subject = $("#subject").val();
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "/fetch_tutor.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
$("#contents img.loading").remove();
var sizy = data.length;
if(sizy ==0) {
console.log("sorry, cannot locate");
$(".simply-popup-link").trigger("click");
$("#simply-popup").empty();
//This is where I want to trigger the on click
$("#simply-popup").append("Unable to locate the subject you entered, please <a href='#' onclick='browse("+sizy+")' class='yellow'>Browse</a>");
}
console.log("size= "+data.length);
var j=0;
for (i = 0; i < data.length; i++) {
........................
......................
The browse function:
function browse(param) {
//this would work
/* $(".simply-popup-link").trigger("click");
$("#simply-popup").empty();
$("#simply-popup").append("test only"); */
// but not this
$(".browse-search-popup-link").trigger("click");
}
I tried loading the page into the an empty popup box ($("#simply-popup")) like this but doesn't work either:
$("#simply-popup").load('search/browse.php');
Change
$("#simply-popup").append("Unable to locate the subject you entered, please <a href='#' onclick='browse("+sizy+")' class='yellow'>Browse</a>");
to
$("#simply-popup").append("Unable to locate the subject you entered, please <a href='#' class='yellow browse'>Browse</a>");
write a separate code for this
$('body').on('click', '.browse', function() {
$('.browse-search-popup-link').click();
});
Can't you just call that function after append:
$("#simply-popup").append("Unable to locate the subject.....");
browse(sizy);// call it here.
or when you append it in the element then you can call the click:
$("#simply-popup").append("Unable to locate the subject.....");
$("#simply-popup a").click();
$(document.body).append('browse value is 1');
$(document.body).find('a').click();
function browse(num){ $(document.body).find('p').html("<pre>"+num+"</pre>");}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
log out here:
<p></p>
I have a show/hide for messages which is working. There is a subject and message. I need it to work so that only onClick of the title will the message display. At the moment when I click on the title of the message, it opens the message, but when the message is open, if I click on the message, it hides. As I'm going to be having some links within the message, this doesn't work. I only need onclick of the title to show and hide the message.
HTML/PHP CODE:
<div id="note_container">
<div id='empty_msg' style="display:none;">You do not currently have any notifications in your <span id='box_type'>INBOX</span></div>
<!-- Content -->
<?
if(!empty($notes)):
foreach($notes as $box_type=>$notes_array):
if(!empty($notes_array)):
foreach($notes_array as $note):
$envelope_icon = ($note['opened']==1)?'icon_opened.jpg':'icon_closed.jpg';
?>
<div id="note_<?=$note['note_id']?>" class='hdr_active <?=$box_type?>_item'>
<input type="checkbox" name="notes_chk" value="<?=$note['note_id']?>" class="notes_chk" style="float:right;"/></label>
<div style='display:inline-block;' id='note_<?=$note['note_id']?>' class="note new_note hide">
<img src="images/buttons/<?=$envelope_icon?>" id='note_indicator_<?=$note['note_id']?>' class="note_indicator" width="20" height="19" />
<?=$note['subject']?>
<div id='note_details_<?=$note['note_id']?>' class="details" style="display: none">
<p><?=$note['message']?></p>
</div>
</div>
</div>
<?
endforeach;
endif;
endforeach;
endif;
?>
</div><!-- END NOTE CONTAINER -->
JQuery CODE
$(".note").click(function(){
// get the search values
var id = $(this).attr('id')
var id_array = id.split('_')
var note_num = id_array[1]
if($(this).hasClass('hide'))
{
$(this).removeClass('hide').addClass('show')
$("#note_details_"+note_num).slideDown()
if($(this).hasClass('new_note')){
var notes = [note_num]
$(this).removeClass('new_note')
$("#note_indicator_"+note_num).attr("src","images/buttons/icon_opened.jpg");
$.ajax({
type: "POST",
url: "ajax-redirect.php",
data: { type: 'markRead', notes: notes, page:'ajax.php' }
}).done(function(data) {
$(".notes_chk").removeAttr('checked')
if(data!=1)
{
alert("failed to update the system")
$("#note_indicator_"+note_num).attr("src","images/buttons/icon_closed.jpg");
}
})
}
}
else
{
$(this).removeClass('show').addClass('hide')
$("#note_details_"+note_num).slideUp()
}
})
$('#check-all').click(function(){
$("input:checkbox").attr('checked', true);
});
$('#uncheck-all').click(function(){
$("input:checkbox").attr('checked', false);
});
})
Please read jQuery documentation! For this case you can use native jQuery method toggle
$("div.note").click(function(){
$(this).toggle(); // or some other selector
});
or if .note is link
$("div.note").click(function(e){
e.preventDefault();
$(".your_block").toggle(); // or some other selector
});
Because div with the note class is the parent of the message any events on its children will bubble up to it so you need to prevent that with event.stopPropagation().
I can't test this code(i dont have the raw HTML to do so) but it should represent what needs to be done:
$(".note").children().click(function(e) {
e.stopPropagation();
});
You need to bind a click event to the children of the div with the note class and prevent it from bubbling up.
I have a photogallery produced from a JSViews template with an upvote and downvote button. The OnClick triggers a database update to increment the underlying score. I also need to increment the Score field in the HTML rendered in the page so that it is consistent with the new values in the database.
The code below is my first attempt, but it doesn't work. How could I achieve this?
<script type="text/x-jsrender" id="gallerycat1">
{{for List}}
<ul>
<li data-type="media" data-url="{{:MainImage}}"></li>
<li data-thumbnail-path="{{:Thumbnail}}"></li>
<li data-thumbnail-text>
<p data-link="Score" class="largeLabel"><span id="span-a-{{:ProfileId}}">{{:Score}}</span> {{:FirstName}} {{:LastName}}, {{:Company}}</p>
<p class="smallLabel">Click to vote.</p>
</li>
<li data-info="">
<div class="voting-buttons">
<a href="#" data-link="Score" onclick="upVote('<%= userVoted%>',{{:[ImageId]}},1);">
<img width="30" src="/client/images_webdev/buttons/heart.png" alt="Upvote this" />
</a>
<a href="#" data-link="Score" onclick="downVote('<%= userVoted%>',{{:[ImageId]}},0);">
<img data-link="Score" width="30" src="/client/images_webdev/buttons/thumbs.png" alt="Downvote this" />
</a>
</div>
<p class="mediaDescriptionHeader"><span data-link="Score" id="scorem">{^{:Score}}</span> {{:FirstName}} {{:LastName}}, {{:Company}}</p>
</li>
</ul>
{{/for}}
</script>
Here's the onClick event for voting
function castVote(userVoted, imageId, vote) {
jQuery.ajax({
url: '/client/webservice/voting.asmx/InsertVote',
type: "POST",
data: "{'userVoted':'" + userVoted + "','imageId':" + imageId + ",'vote':" + vote + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
if (response.d == 'True') {
var counter = jQuery('#scorem').text();
if (vote > 0) {
counter++;
} else {
counter--;
}
jQuery('#scorem').text(counter);
upVoteConfirm();
} else {
downVoteConfirm();
}
}
});
I assume you are using JsViews, not just JsRender. Are you calling the link method, or just the render method? The data-link expressions you have above won't work unless you are actually data-linking using JsViews link method.
If you are data-linking, then you need to call $.observable(listItem).setProperty("Score", listItem.Score+1); - and that will automatically update either data-link expressions like <span data-link="Score"></span> or data-linked tags like {^{:Score}}.
See for example http://www.jsviews.com/#jsvplaying, where there are two samples which have "Change" buttons to modify the name property.