I am trying to get the pasted contents of a form text field to trigger an AJAX action which connects to a php script to deal with the data and then sends the relevant response.
The php script is working perfectly so I know the problem isn't there.
The jQuery function also works perfectly, by alerting whatever is pasted into the text field if I do this
$(document).ready(function(){
$('input').on('paste', function () {
var capture = this;
setTimeout(function () {
var url = $(capture).val();
alert (url);
}, 100);
});
});
But when I try to add the AJAX business it all fails.
I'm obviously doing it wrong but I don't know the correct way to do it.
The way I'm calling AJAX is the same method I use in a whole bunch of other scripts and it works fine in those so it must be to do with where it's being called.
I've tried (left off the doc ready to save clutter) :
$('input').on('paste', function () {
var capture = this;
setTimeout(function () {
var url = $(capture).val();
}, 100);
var data = {
'action': 'myAction',
'security': $( '#my-nonce' ).val(),
'url' : url,
'check' : check
};
$.post(myajax.ajaxurl, data, function(response) {
alert(response);
}
});
And also tried :
$('input').on('paste', function () {
var capture = this;
setTimeout(function () {
var url = $(capture).val();
var data = {
'action': 'myAction',
'security': $( '#my-nonce' ).val(),
'url' : url,
'check' : check
};
$.post(myajax.ajaxurl, data, function(response) {
alert(response);
}
}, 100);
});
And I've also tried setting the url var directly in the data var :
var data = {
'action': 'myAction',
'security': $( '#my-nonce' ).val(),
'url' : $(capture).val(),
'check' : check
};
But nothing is working.
I suspect this is to do with the setTimeout function.
Is there a specific way of firing an AJAX call when also using setTimeout?
Just for clarity. I'm trying to trigger an AJAX call on paste event.
try to increase the time, I mean
setTimeout(function(){...
,1000}
try experimenting with different times.
If you get the answer then your post call is eating up the time.
Related
Ajax is not working I have to reload the page to make it work. Because of ajax was not reloading i used location.reload but I don't want this so please anyone can help me out how to make ajax function work. Its removing data but I need to refresh the page to see
$(document).ready(function() {
$('.headertrash').click(function(e){
e.preventDefault();
var trashcartid = this.id;
var splittrash = trashcartid.split('-');
var cartdelid = splittrash[1];
//Ajax Request
$.ajax({
url: 'delusing.php',
type: 'POST',
data: { id:cartdelid },
success: function(response){
// Remove row from HTML Table
$(this).closest('li').fadeOut(300,function(){
$(this).closest('li').remove();
});
//I uses location.reload as alternative
// location.reload();
}});
e.preventDefault();
});
I am going to assume that your request is working and returns success.
From your code and question I am deducing that the actual issue is not with ajax not working but with the li not fading and disappearing.
The issue you are experiencing is due to the this you are using, the way you are using this it means the ajax request, but your intent is to get the element associated with $('.headertrash') to fix your issue:
$(document).ready(function() {
$('.headertrash').click(function(e){
e.preventDefault();
var trashcartid = this.id;
var splittrash = trashcartid.split('-');
var cartdelid = splittrash[1];
var clickedElement = $(this);
//Ajax Request
$.ajax({
url: 'delusing.php',
type: 'POST',
data: { id:cartdelid },
success: function(response) {
// Remove row from HTML Table
clickedElement.closest('li').fadeOut(300,function() {
clickedElement.closest('li').remove();
});
}
});
});
});
See: Ajax (this) not working for more details
I have a table with data and a function to help me get values from rows:
function getRow () {
$('#mytable').find('tr').click( function(){
let fname = $(this).find('td:eq(4)').text();
let start = $(this).find('td:eq(5)').text();
let end = $(this).find('td:eq(6)').text();
.......ajax method () etc
................
}
So far, it has been working perfectly and fetching me the correct data. I had another function elsewhere in the page, where clicking on some links would fetch some data from the server and reload the page to display the new data. Everything was working like clockwork.
Now, I decided that when re-displaying fresh data, instead of reloading the page, it's better to refresh the #mytable div. Indeed, it worked, but alas it spoiled the first function. So basically the function below has introduced a bug elsewhere in the page, and I'm not sure why or how to fix it. It's as if the div refresh has completely disabled the event handler. Any ideas?
$(document).ready(function() {
$(".key").click(function(event) {
event.preventDefault();
var word = event.target.innerHTML;
$.ajax({
url: '.../',
data: {
action : "key",
keyword: word
},
type: 'get',
success: function(data){
$('#mytable').load("/.../../..." + ' #ytable');
},
error: function(e){
console.log(e);}
});
});
});
I have a table with a td that updates when i press a button .pauseDocker
When It's paused I'm reloading the page. Surely there's a smarter way to just refresh just part of the page in this case the table.
$(document).on('click','.pauseDocker' ,function(){
var buttonClicked = $(this);
var containerName = $(this).attr('name');
$.ajax({
type: 'post',
url: '/container/pause',
data: {containerName: containerName},
success: function () {
location.reload();
},
error: function() {
}
});
});
You can get the first parameter of the success callback and this will contain data from the response of your server. Use that to retrieve the changed data and update client side accordingly
I have the following script I've written.
<script>
$(document).ready(function(){
$('a').data('loop',true);
$('body').on('click', 'a', function(event){
console.log($(this).data('loop'));
if ($(this).data('loop') == 'true') {
console.log('hit');
event.preventDefault();
caller = $(this);
$(this).data('loop',false);
var linkref = $(this).attr('href');
var linkpos = $(this).offset();
var screenwidth = $(window).width();
var json_data = JSON.stringify({linkref: linkref, linkpos: linkpos, screenwidth: screenwidth});
$.ajax({
url: "content/submitcontenthandler?handler=core/_dashboard&method=tracking_ping",
method: "POST",
data: "json=" + json_data,
complete: function (jqXHR, status) {
console.log(status);
console.log(caller);
$(caller).click();
}
});
} else {
console.log(event.isDefaultPrevented());
console.log('miss');
$(this).data('loop',true);
}
});
});
</script>
It works, sends me the details I want etc etc. BUT!!!
When I click a link, It fires off the details to me via Ajax, then it's meant to "click" the event again, which it does! but the event does not fire it's normal action. So When clicking a link to another page, I would go to that other page... that's not happening.
If I comment out the line event.preventDefault(); Then the event fires as I would expect...
So to me it looks like the event.preventDefault is executing even though it's not meant to be during the second call...
Sorry if this is a bit complicated to understand. I don't quite understand what's happening myself.
Is it possibly a bug, or is there something that I've done that has caused this?
I didn't think I could, but I have successfully made a jsfiddle for this.
https://jsfiddle.net/atg5m6ym/2001/
You can try this and not worry about the "loop" anymore:
$(document).ready(function () {
$('body').on('click', 'a', function (event) {
event.preventDefault();
var caller = $(this);
var linkref = $(this).attr('href');
var linkpos = $(this).offset();
var screenwidth = $(window).width();
var json_data = JSON.stringify({linkref: linkref, linkpos: linkpos, screenwidth: screenwidth});
$.ajax({
url: "content/submitcontenthandler?handler=core/_dashboard&method=tracking_ping",
method: "POST",
data: "json=" + json_data,
complete: function (jqXHR, status) {
console.log(status);
console.log(caller);
window.location.href = linkref; // Redirect happens here
}
});
});
});
UPDATE
There's a few issues to note here:
1) Some links don't require a redirect (as noted, bootstrap model links that control showing/hiding or within document anchors
To correct this it really depends on the case. Usually bootstrap adds specific classes or data attributes to the links so you can do something like.
$('body').on('click', 'a:not(list of things to exclude)'..
Personally I'd instead define the links I wanted to track as :
<a href=<link> data-tracked='true'...
<script>
$('body').on("click","a[data-tracked='true']"...
Or if you want to track most links with a few exceptions you can:
<a href=<link> data-tracked='false'...
<script>
$('body').on("click","a:not([data-tracked='false'])"...
Or more generally:
<script>
$('body').on("click","a", function () {
if ($(this).attr("data-tracked") == "false" || <you can check more things here>){
return true; //Click passes through
}
//Rest of the tracking code here
});
The following if statement will return true whenever the data-loop attribute exists against an element, regardless of it's value:
if ($(this).data('loop')) {
It needs to be changed to check for the value:
if ($(this).data('loop') == 'true') {
When you assign anything to be the value of an element attribute it becomes a string and, as such, requires a string comparison.
Event.preventDefault() is not being executed second time.
Link redirection happens when the method is completed.
So in your case redirection will happen when complete method of ajax call is completed.
lets say, we have event1 and event2 object in the code. event1 is the object in the ajax call method and event2 is the event object in recursive call (second call) method.
so when link is clicked second time , we still have complete method to be executed. as soon as it returns to the complete method of ajax call, it finds the event1 is having preventDefault property true and it does not redirect.
Try this ;)
$(document).ready(function(){
$('body').on('click', 'a', function(event){
event.preventDefault();
var caller = $(this);
var linkref = $(this).attr('href');
var linkpos = $(this).offset();
var screenwidth = $(window).width();
var json_data = JSON.stringify({
linkref: linkref,
linkpos: linkpos,
screenwidth: screenwidth
});
$.ajax({
url: "content/submitcontenthandler?handler=core/_dashboard&method=tracking_ping",
method: "POST",
/* To temprary block browser; */
async: false,
data: "json=" + json_data,
complete: function(jqXHR, status){
/* add class **ignore** to a element you don't want to redirect anywhere(tabs, modals, dropdowns, etc); */
if(!caller.hasClass('ignore')){
/* Redirect happens here */
window.location.href = linkref;
}
}
});
});
});
I have comment system using live ajax php, and also include for vote system on that comment
Logic: when i post new comment, system will call ajax function with method post, and display response in above of textarea for comment, that response is include vote system (a class="with_unique_id"), but when i click that vote, it wont calling ajax function (nothing happend in browser console), whereas in current comment that displaying in above of new comment, it working fine.
This is my ajax code for vote
jQuery(document).ready(function($){
$(".voteMe").click(function() {
var voteId = this.id;
var upOrDown = voteId.split('_');
$.ajax({
type: "post",
url: "<?php echo base_url('blog/likepost');?>/"+upOrDown[0],
cache: false,
data:'voteId='+upOrDown[0] + '&upOrDown=' +upOrDown[1],
success: function(response){
try{
if(response=='true'){
var newValue = parseInt($("#"+voteId+'_result').text()) + 1;
$("#"+voteId+'_result').html(newValue);
document.getElementById('likeStatus_'+upOrDown[0]).innerHTML = 'Success';
$("#likeStatus_"+upOrDown[0]).show();
setTimeout(function() { $("#likeStatus_"+upOrDown[0]).hide(); }, 5000);
}else{
$("#likeStatus_"+upOrDown[0]).show();
document.getElementById('likeStatus_'+upOrDown[0]).innerHTML = 'Liked';
setTimeout(function() { $("#likeStatus_"+upOrDown[0]).hide(); }, 5000);
}
}catch(err) {
alert(err.message);
}
},
error: function(){
alert('Error while request..');
}
});
});
});
It took me a while to read your code, but I guess this is the root cause:
if(response=='true'){
var newValue = parseInt($("#"+voteId+'_result').text()) + 1;
$("#"+voteId+'_result').html(newValue);
document.getElementById('likeStatus_'+upOrDown[0]).innerHTML = 'Success';
$("#likeStatus_"+upOrDown[0]).show();
setTimeout(function() { $("#likeStatus_"+upOrDown[0]).hide(); }, 5000);
}
This line here:
$("#"+voteId+'_result').html(newValue);
That become the link you want to click again. Right?
If that is so, then you need to re-assign the event handler.
By replacing the DOM element, you have also removed the assigned event handler
PS: You code is very hard to read. It will be nightmare for you to maintain it.
i have fixed my code with adding same ajax code function in response of current ajax with different id.
thankyou