I have code like this:
$(".delete").live('click', function() {
var commentContainer = $(this).parent();
var id = $(this).attr("id");
var string = 'id='+ id ;
$.ajax({
url: "<?php echo site_url('messages/delete') ?>",
type: "POST",
data: string,
cache: false,
success: function(){
commentContainer.slideUp('600', function() {$(this).remove();
$('.messages').fadeOut('2000', function(){$(this).remove();
$('#messages').load("<?php echo site_url('messages/show') ?>", function(){
$(this).fadeIn('2000')
});
});
});
}
});
return false;
});
$('.delete').confirm(
{
msg: 'You are about to delete this message. Are you sure?<br>',
buttons: {
separator: ' - '
}
});//message deleting
When activated for the first time it is working (when I try to delete message, question is asked and if I say yes, message is deleted). When data again shown, when I click delete it is deleting message without asking. What is the problem?
It looks like you'll have to register the confirm plugin after every ajax load as it isn't using live internally.
Easiest way would be to move the code into its own function and call that inside the load callback and on page load.
function deleteConfirmSetup() {
$('.delete').confirm(
{
msg: 'You are about to delete this message. Are you sure?<br>',
buttons: {
separator: ' - '
}
});//message deleting
}
$(".delete").live('click', function() {
$.ajax({
url: "<?php echo site_url('messages/delete') ?>",
type: "POST",
data: string,
cache: false,
success: function(){
commentContainer.slideUp('600', function() {$(this).remove();
$('.messages').fadeOut('2000', function(){$(this).remove();
$('#messages').load("<?php echo site_url('messages/show') ?>", function(){
$(this).fadeIn('2000');
deleteConfirmSetup(); // Add function call here
});
});
});
}
});
return false;
});
deleteConfirmSetup(); // Also call function here to setup initially
Clearly the "confirm" plugin doesn't operate with live and instead is using bind.
When the element is added, it doesn't have the confirmation bindings but does have the live ones, so it'll just delete.
You could attempt to re-call the confirm plugin in your success function after the new content is loaded, modify the plugin, do it yourself manually, or find a new plugin that's a bit better thought-out.
I haven't used the confirm plugin, but a slightly irritating hack to make this work as you want might be to do this:
var bindBackup = jQuery.fn.bind;
jQuery.fn.bind = jQuery.fn.live;
before you run .confirm(). Then just restore it afterwards:
jQuery.fn.bind = bindBackup;
I haven't tried it, but the live function doesn't implement bind in it's source, so I don't see a reason why it won't work.
Related
I'm attempting to first make an AJAX request from a social API and append the results with a button inside the div that will save the corresponding item in the array to my firebase database. For example,
I have my AJAX request - I cut out about 75% of the actual code that isn't needed for the question.
$.ajax({
type : 'GET',
url : url,
dataType : "jsonp",
cache: false,
success : function(data){
console.debug(data);
vids = data.response.items;
for(var i in vids) {
dataTitle = vids[i].title;
ncode = "<div class='tile'><img src='"+ vids[i].title "'/></a><button class='btn' type='button' onClick='saveToDatabase()'>Save</button></div>";
$('#content').append( ncode )
And then I have my function that I want to save the 'title' of the object the button was appended with to the firebase database.
var dataTitle;
function saveToDatabase() {
ref.push({
title: dataTitle
});
}
The issue is that when the button is clicked it posts a random title from inside the array instead of the title of the item the button was appended with... How can I bind the buttons function to the correct dataTitle?
I'm not sure if that makes sense so please let me know if clarification is needed. Thanks in advance for any help you can provide!
This fails because you are iterating the entire list and assigning them to a global variable. The result is not random at all--it's the last item in the list, which was the last to be assigned to the globar variable.
Try using jQuery rather than writing your own DOM events, and utilize a closure to reference the video title.
function saveToDatabase(dataTitle) {
ref.push({
title: dataTitle
});
}
$.ajax({
type : 'GET',
url : url,
dataType : "jsonp",
cache: false,
success : function(data) {
console.debug(data); // console.debug not supported in all (any?) versions of IE
buildVideoList(data.response.items);
}
});
function buildVideoList(vids) {
$.each(vids, function(vid) {
var $img = $('<img></img>');
$img.attr('src', sanitize(vid.title));
var $button = $('<button class="btn">Save</button>');
$button.click(saveToDatabase.bind(null, vid.title));
$('<div class="tile"></div>')
.append($img)
.append($button)
.appendTo('#content');
});
}
// rudimentary and possibly ineffective, just here to
// point out that it is necessary
function sanitize(url) {
return url.replace(/[<>'"]/, '');
}
I actually just ended up passing the index to the function by creating a global array like so. It seems to be working fine... any reason I shouldn't do it this way?
var vids = []; //global
function foo() {
$.ajax({
type : 'GET',
url : url,
dataType : "jsonp",
cache: false,
success : function(data){
console.debug(data);
vids = data.response.items;
for(var i in vids) {
ncode = "<div class='tile'><img src='"+ vids[i].title "'/></a><button class='btn' type='button' onClick='saveToDatabase('+i+')'>Save</button></div>";
$('#content').append( ncode )
} //end ajax function
function saveToDatabase(i) {
ref.push({
title: vids[i].title
});
}
I am working with Concrete-5 CMS, I have an issue in passing value form view to controller.In my application I am using following code for displaying employee role.
foreach($rd as $data){
echo "<tr><td>".$data[role_name]."</td><td>".$data[role_description]."</td><td>Edit</td><td>".$ih->button_js(t('Delete'), "deleteRole('".$data['role_id']."')", 'left', 'error')."</td></tr>";
}
<input type="hidden" name="rno" id="rno" />
script:
$delConfirmJS = t('Are you sure you want to remove this Role?'); ?>
<script type="text/javascript">
function deleteRole(myvar) {
var role = document.getElementById('rno');
role.value = myvar;
if (confirm('<?php echo $delConfirmJS ?>')) {
$('#rolelist').submit();
//location.href = "<?php echo $this->url('/role/add_role/', 'delete', 'myvar')?>";
}
}
</script>
html code
I did edit operation by passing role_id through edit action. But, In case of delete i should ask for a conformation, so I use java script to conform it and call the href location and all.
But i don't know how to pass the role_id to script and pass to my controller. how to achieve this task?
thanks
Kumar
You can pass value to server using ajax calls.
See the following code. Here We use a confirm box to get user confirmation.
function deleteEmployee(empId){
var confirm=confirm("Do you want to delete?");
if (confirm)
{
var url = "path/to/delete.php";
var data = "emp_id="+empId;
$.ajax({
type: "POST",
url: "otherfile.php",
data: data ,
success: function(){
alert("Employee deleted successfully.");
}
});
}
}
In delete.php you can take the employee id by using $_POST['emp_id']
You can do it easily by using jquery
var dataString = 'any_variable='+ <?=$phpvariable?>;
$.ajax({
type: "POST",
url: "otherfile.php",
data: dataString,
success: function(msg){
// msg is return value of your otherfile.php
}
}); //END $.ajax
I would add an extra variable in to the delete link address. Preferrably the ID of the row that you need to be deleted.
I don't know Concrete-5 CMS. But, i am giving you the general idea
I think, you are using some button on which users can click if they want to delete role.
<td>".$ih->button_js(t('Delete'), "deleteRole('".$data['role_id']."')", 'left', 'error')."</td>
My suggestion,
add onClick to button
onClick="deleteEmployee(roleId);" // roleId - dynamic id of the role by looping over
Frankly speaking dude, i dont know how you will add this to your button that i guess there would surely be some way to simply add this to existing html.
And now, simply use Sajith's function
// Sajith's function here
function deleteEmployee(empId){
var confirm=confirm("Do you want to delete?");
if (confirm){
var url = "path/to/delete.php";
var data = "emp_id="+empId;
$.ajax({
type: "POST",
url: "otherfile.php",
data: data ,
success: function(){
alert("Employee deleted successfully.");
}
});
}
}
I want to keep a record of every click that occurs within a specific DIV and child DIVS on page. The client should not be aware of this. Inside of the div is a link to an external website.
Client clicks link inside div > ajax inserts record in db > client is sent to site of link clicked
PHP on page
include('quotemaster/dbmodel.inc.php');
if(isset($_POST['dataString'])) {
clickCounter();
}
PHP Model Function
function clickCounter() {
global $host, $user, $pass, $dbname;
try {
$DBH = new PDO("mysql:host=$host;dbname=$dbname",$user,$pass);
$stmt = $DBH->prepare("INSERT INTO clickcounter (counter) VALUES (1)");
$stmt->execute();
}
catch (PDOException $e) {
echo $e->getMessage();
}
}
AJAX POST
$(function() {
$("body").click(function(e) {
if (e.target.id == "results" || $(e.target).parents("#results").size()) {
//alert("Inside div");
ajax_post();
}
});
})
function ajax_post() {
var dataString = 'CC='+1;
$.ajax({ type: "POST", url: "tq/--record-events.inc.php", data: dataString });
}
The problem I am having (I think) is that the AJAX post is not being sent. Any ideas? Thanks!
on your PHP you have
if(isset($_POST['dataString'])) {...
you are expecting a parameter named dataString so you can fix it on your javascript ajax_post function with something like
var postData={dataString:true, CC:1}
$.ajax({ type: "POST", url: "tq/--record-events.inc.php", data: postData });
this way jQuery will create the proper dataString parameter.
Hope this helps
Try changing the POST check to:
if(isset($_POST['CC'])) {
clickCounter();
}
Also, if your DIV contains a link that navigates away from the page, clicking the link may cause the page location to change before the event bubbles down to the body tag. If so, you could try attaching an event to the link which calls preventDefault and therefore allow the event to bubble. If so, you could then detect that the user clicked the link and perform the navigation manually after recording the click. To show code as to how this can be achieved you need to post your full div code (including the link).
To add callbacks to the ajax call:
function ajax_post() {
var dataString = 'CC='+1;
$.ajax({
type: "POST",
url: "tq/--record-events.inc.php",
data: dataString,
success: function(data) {
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
}
});
}
So I have this JavaScript which works fine up to the $.ajax({. Then it just hangs on the loader and nothing happens.
$(function() {
$('.com_submit').click(function() {
var comment = $("#comment").val();
var user_id = $("#user_id").val();
var perma_id = $("#perma_id").val();
var dataString = 'comment='+ comment + '&user_id='+ user_id + '&perma_id=' + perma_id;
if(comment=='') {
alert('Please Give Valid Details');
}
else {
$("#flash").show();
$("#flash").fadeIn(400).html('<img src="ajax-loader.gif" />Loading Comment...');
$.ajax({
type: "POST",
url: "commentajax.php",
data: dataString,
cache: false,
success: function(html){
alert('This works');
$("ol#update").append(html);
$("ol#update li:first").fadeIn("slow");
$("#flash").hide();
}
});
}
return false;
});
});
Try replacing:
var dataString = 'comment='+ comment + '&user_id='+ user_id + '&perma_id=' + perma_id;
with:
var dataString = { comment: comment, user_id: user_id, perma_id: perma_id };
in order to ensure that the parameters that you are sending to the server are properly encoded. Also make sure that the commentajax.php script that you are calling works fine and it doesn't throw some error in which case the success handler won't be executed and the loader indicator won't be hidden. Actually the best way to hide the loading indicator is to use the complete event, not the success. The complete event is triggered even in the case of an exception.
Also use a javascript debugging tool such as FireBug to see what exactly happens under the covers. It will allow you to see the actual AJAX request and what does the the server respond. It will also tell you if you have javascript errors and so on: you know, the kinda useful stuff when you are doing javascript enabled web development.
I am trying to make an admin page using AJAX so when the client updates information in the CKEDITOR it doesn't have to take him to a new page. Getting data from input fields are easy enough using the .val() function, but because textareas are not updated on the fly, I can't use that same function. Heres as far as I got:
// this replaces all textarea tags into CKEDITORS
<script type="text/javascript">
CKEDITOR.replaceAll();
</script>
//this attempts to grab all data from inputs and textareas
$(function() {
$("#submit").click(function() {
var newsTitle = $("#newsTitle").val();
var editNews = CKEDITOR.instances.editNews.getData();
var contactTitle = $("#contactTitle").val();
var editContact = CKEDITOR.instances.editContact.getData();
var linksTitle = $("#linksTitle").val();
var editLinks = CKEDITOR.instances.editLinks.getData();
$.ajax({
type: "POST",
url: "update.php",
data: 'newsTitle='+newsTitle+'&editNews='+editNews+'&contactTitle='+contactTitle+'&editContact='+editContact+'&linksTitle='+linksTitle+'&editLinks='+editLinks,
cache: false,
success: function(){
updated();
}
});
return false;
});
});
the getData() function seemed like it would work because I tested it with alerts and it was grabbing the data from the editors, but once I would try and update, it wouldn't work...
any ideas?
This code replaces the textarea:
<script type="text/javascript">
CKEDITOR.replace( 'TEXTAREA_ID', {
extraPlugins : 'autogrow',
removePlugins : 'resize',
entities : false
});
</script>
In the JS file this is the code and I am using Jquery Validator Plugin:
$(document).ready(function(){
jQuery.validator.messages.required = "";
$("#FormID").validate({
submitHandler: function(){
var ContentFromEditor = CKEDITOR.instances.TEXTAREA_ID.getData();
var dataString = $("#FormID").serialize();
dataString += '&ContentFromEditor='+ContentFromEditor;
$.ajax({
type: "POST",
url: "Yourfile.php",
data: dataString,
cache: false,
success: function(html){
YOU WORK WITH THE RETURN HERE
},
error: function(xhr, ajaxOptions, thrownError){
alert(xhr.responseText);
}
});
return false;
}
});
});
This is the line that most of the time creates the error:
CKEDITOR.instances.TEXTAREA_ID.getData();
After the instances always comes the ID of the textarea.
I have my own config.js that you can get from the ckeditor website or from the examples.
Tage a look at the CKEditor function/adaptor for jQuery
http://docs.cksource.com/CKEditor_3.x/Developers_Guide/jQuery_Adapter
Because setting and retrieving the editor data is a common operation, the jQuery Adapter also provides the dedicated val() method:
// Get the editor data.
var data = $( 'textarea.editor' ).val();
// Set the editor data.
$( 'textarea.editor' ).val( 'my new content' );
With this code, my problems were solved.
I updated the field running ckeditor to be seen in serialize.
$('#form').find('.class').each(function(index) {
$(this).val(CKEDITOR.instances[$(this).attr('id')].getData());
});