I can't copy the generated link directly (without ctrl+C)
I am usign document.execCommand('copy') but it seems it has no effect.
If code has no AJAX then its working pefectly.
Here's the
fiddle link with AJAX
fiddle link without AJAX
HTML:
<div class="permalink-control"> </div>
JQUERY:
$(".permalink-control")
.append(
'<div class="input-group">' +
' <span class="input-group-btn"><button type="button" class="btn btn-default" title="Get Permalink"><span class="glyphicon glyphicon-link"></span></button></span>' +
' <input type="text" class="form-control">' +
'</div>'
);
$(".permalink-control input")
.hide()
.focus(function () {
// Workaround for broken selection: https://stackoverflow.com/questions/5797539
var $this = $(this);
$this.select()
.mouseup(function () {
$this.unbind("mouseup");
return false;
});
});
$(".permalink-control button")
.click(function () {
var $this = $(this);
$.ajax({
url: "https://api-ssl.bitly.com/shorten",
dataType: "jsonp",
data: {
longUrl: window.location.href,
access_token: "your access token",
format: "json"
},
success: function (response) {
var longUrl = Object.keys(response.results)[0];
var shortUrl = response.results[longUrl].shortUrl;
if (shortUrl.indexOf(":") === 4) {
shortUrl = "https" + shortUrl.substring(4);
}
$this.parents(".permalink-control")
.find("input")
.show()
.val(shortUrl)
.focus();
},
async:false
});
});
UPDATE:
How do I copy to the clipboard in JavaScript?
is not answer to my question as My code also copies without using ctrl+C if AJAX is not there.
However when I am using AJAX document.execCommand('copy') is not working.
The reason for this is clearly stated in W3 specs:
Copy and cut commands triggered through a scripting API will only affect the contents of the real clipboard if the event is dispatched from an event that is trusted and triggered by the user, or if the implementation is configured to allow this.
But, having said that we can try to fool around the browser by copying text when a user does some interaction.
In this case since you are looking for a click event I assume you're user is interacting with mouse
So, what if I attach a $(window).blur() or $(document).click() event after the ajax call is resolved?
That's right, Since, the user has to blur at some point to use the copy selection, user will initiate a blur() or click() (depending on your need) and we can copy text to our clipboard.
Here's the HACKY DEMO
$(document).ready(function(){
var shortUrl;
$(".permalink-control")
.append(
'<div class="input-group">' +
' <span class="input-group-btn"><button type="button" class="btn btn-default" title="Get Permalink"><span class="glyphicon glyphicon-link"></span></button></span>' +
' <input type="text" class="form-control">' +
'</div>'
);
$(".permalink-control input")
.hide()
.focus(function () {
// Workaround for broken selection: http://stackoverflow.com/questions/5797539
var $this = $(this);
$this.select();
document.execCommand('copy');
$this.mouseup(function () {
$this.unbind("mouseup");
return false;
});
});
$(".permalink-control button")
.click(function () {
var shortUrl ="";
var $this = $(this);
$.ajax({
url: "https://api-ssl.bitly.com/shorten",
dataType: "jsonp",
data: {
longUrl: window.location.href,
access_token: "48ecf90304d70f30729abe82dfea1dd8a11c4584",
format: "json"
},
success: function (response) {
var longUrl = Object.keys(response.results)[0];
shortUrl = response.results[longUrl].shortUrl;
if (shortUrl.indexOf(":") === 4) {
shortUrl = "https" + shortUrl.substring(4);
}
$this.parents(".permalink-control")
.find("input")
.show()
.val(shortUrl)
.focus();
}
}).done(function(){
$(window).blur(function(){
document.execCommand('copy');
$(window).off('blur');// make sure we don't copy anything else from the document when window is foucussed out
});
})
});
})
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="permalink-control"></div>
<div class"log"></div>
P.S: This has been tested in chrome.
I had the same problem. I solved it rather primitively: inside the handler of a click event, you can run an interval that will check the variable where ajax will insert the value after the server responds. After the answer is received, we stop the interval and start the work with the clipboard. No problem, because the user himself starts the interval after the click, without any callbacks.
Simple jQuery example:
var ajaxResponse;
function copyText(copiedText){
$('<textarea class="copied-text">' + copiedText + '</textarea>').appendTo('body');
if ( navigator.userAgent.match(/ipad|iphone/i) ) {
var range = document.createRange(),
textArea = $('.copied-text')[0];
range.selectNodeContents(textArea);
var selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
textArea.setSelectionRange(0, 999999);
} else {
$('.copied-text').select();
}
document.execCommand('copy');
$('.copied-text').remove();
};
function myAjaxFunc(){
$.ajax({
type: 'POST',
url: yourUrl,
data: yourData,
success: function(data){
ajaxResponse = data;
}
});
};
$('.your-button').on('click', function(){
myAjaxFunc();
var ajaxCheckTimer = setInterval(function(){
if ( ajaxResponse ) {
copyText(ajaxResponse);
clearInterval(ajaxCheckTimer);
};
}, 100);
});
In this example, when clicking on a button, we send some data to the server and start the interval with checking the value of the ajaxResponse variable.
After the response from the server is received, the response of the server is written to this variable, after which the condition in the interval becomes true and the text copy function is called, and the server response variable is specified as the parameter: copyText(ajaxResponse);. The interval stops.
The copyText function creates an textarea on the page with the value of the ajaxResponse variable, copies this value from the field to the clipboard, and deletes the field from the page.
UPDATE 01.07.19
For correct copying to the clipboard on iOS, add the attribute contenteditable with the valuetrue to the text field:
$('<textarea class="copied-text" contenteditable="true">' + copiedText + '</textarea>').appendTo('body');
Related
Here is my code:
$('#form').on('change', 'input', function (e){
e.preventDefault();
var cb = $(this);
if(cb.is(':checked')){
send_data(this);
}
else{
this.value=0;
send_data(this);
}
//if(!(this.checked)){
//$(this).val(0);
//}
});
send_data function:
function send_data(obj) {
$.ajax({
type: 'POST',
url: 'some.php',
async: true,
data: $(this).serialize(),
success: function (msg) {
console.log(msg);
}
});
}
some function:
var inp_f =document.createElement('input');
inp_f.setAttribute('type', 'hidden');
inp_f.setAttribute('name', intrst);
inp_f.setAttribute('value', 0);
var inp = document.createElement('input');
inp.setAttribute('type', 'checkbox');
inp.setAttribute('id', intrst);
inp.setAttribute('name', intrst);
inp.setAttribute('value', 1);
I have looked over several questions, so before you flag me for duplicate post; none of them have solved my issue. I have created a function that dynamically creates inputs. When that input is checked a value of 1 is sent. When it is unchecked I am trying to then send a value of 0 through ajax call. I have created the invisible field for some reason it does recognize it. So I then attempted to changed the value of this.value=0 that does not set until after the script has ran. Then as long as the page is not reloaded the value remains 0.
EDIT: Reordered the input elements and the console is still showing $(this).val() = 0
Hi I'm working on an ajax function in jquery that saves the value of a checkbox. Here is my question, What if the user clicks in multiple times even the saving is not yet finished/success? How can i Prevent the user to tick the checkbox when the form is submitting? Thanks !
Heres my Code Snippet:
$(".chkOverride").click(function (e) {
var userId = $("#UserId").val();
var isChecked = $(this).is(":checked")
$.ajax({
url: "/Worker/Worker?Id=" + Id + "&isChecked=" + isChecked + "&UserId=" + UserId,
type: "post",
success: function (result) {
alert("Success!");
location.reload();
},
error: function () {
}
});
});
You can disable the checkbox before starting the ajax call. You may use the prop() method to do that. Set the disabled property value to true
$(".chkOverride").click(function (e) {
var _this=$(this);
_this.prop('disabled', true);
var userId = $("#UserId").val();
var isChecked = $(this).is(":checked")
$.ajax({
url: "/Worker/Worker?Id=" + Id + "&isChecked=" +
isChecked + "&UserId=" + UserId,
type: "post",
success: function (result) {
alert("Success!");
//No point in enabling as you are going to reload the page
_this.prop('disabled', false);
location.reload();
},
error: function () {
alert("Error :(");
_this.prop('disabled', false);
}
});
});
Have you come across this link:
Inhibit a checkbox from changing when clicking it
You can disable the checkbox using
$this.attr('disabled', 1);
Disable the button before making the Ajax call.
I work on a pagination system that wouldn't reload the whole page but just refresh the contents.
I retrieve the requested page with the value contained in a ID and want to send it to the server for the process.
The success is reached but my php script does not recognize the $_POST['page'] value.
Here is the JS:
$(document).ready(function()
{
$('#containerWrapper').on('click', '.holder a', function (event) {
var page = $(this).attr('id');
var url = "cart.php";
event.preventDefault();
// Launch of the Ajax query to refresh the current page
$.ajax({
url: "cart.php",
type: "POST",
data: {page: page},
success: function()
{
alert('Success, delivered page: ' + page);
$('#containerWrapper').load(url + " #containerWrapper");
}
});
});
});
Here the PHP, which i think isn't the real problem:
if (isset($_POST['page']) && ($_POST['page'])>0 && ($_POST['page'])<= $nbPages)
{
$cPage = htmlspecialchars($_POST['page']);
}
I've ready many topics but haven't found any relative problem for the now.
You really have too much code, it is not necessary for your purposes to bury a load() statement in an AJAX call. You could simply do this -
$(document).ready(function(){
$('#containerWrapper').on('click', '.holder a', function (event) {
event.preventDefault();
var url = "cart.php";
var page = $(this).attr('id');
$('#containerWrapper').load(url + " #containerWrapper", {page: page});
});
});
load() does allow you to send data to the requested page via a second arguement.
I want to do is when a user type an email to the inputbox ajax will pass the value automatically to php.
My problem is the result only show if I try to refresh the page
html:
<input type="text" id="email" name="email" />
script:
$(document).ready(function(){
var countTimerEmailName = setInterval(
function ()
{
emailName();
}, 500);
var data = {};
data.email = $('#email').val();
function emailName(){
$.ajax({
type: "POST",
url:"Oppa/view/emailName.php",
data: data,
cache: false,
dataType:"JSON",
success: function (result) {
$("#imageLink").val(result.user_image);
$("#profileImage").attr('src', result.user_image);
$("#emailNameResult").html(result.user_lname);
$("#emailCodeResult").val(result.user_code);
}
});
};
});
You can try with:
Because you dont need declare function in ready() and you need yo get the email value after any change. Now you only get the value when the page is ready.
function emailName( email ){
$.ajax({
type: "POST",
url:"Oppa/view/emailName.php",
data: 'email=,+email,
cache: false,
dataType:"JSON",
success: function (result) {
$("#imageLink").val(result.user_image);
$("#profileImage").attr('src', result.user_image);
$("#emailNameResult").html(result.user_lname);
$("#emailCodeResult").val(result.user_code);
}
});
};
$(document).ready(function(){
$('#email').change(function(e) {
emailName( this.val());
});
});
You're handling it wrong. jQuery has particular events to do these things.
Take this for example:
$(document).ready(function(){
$(document).on('keyup', '#email', function(e) {
e.preventDefault();
val = $(this).val();
console.log("Value: " + val);
});
});
It will look what is in the below input field as the user types. (which is what I presume you're trying to do?)
<input type="text" id="email" name="email" />
Example
You could simply remove that console.log() and replace it with your ajax request. (The above example will run as the user types.)
Alternatively you could use change() like this:
$(document).ready(function(){
$(document).on('change', '#email', function(e) {
e.preventDefault();
val = $(this).val();
console.log("Value: " + val);
});
});
Which will run after the value of the text box has changed. (When the user clicks out of the text box or moves somewhere else on the page.)
Example
I have a few forms on my single page and I'm submitting them by this method:
$(function() {
$(".button").click(function() {
var upform = $(this).closest('.upform');
var txt = $(this).prev(".tekst").val();
var dataString = 'tekst='+ txtr;
$.ajax({
type: "POST",
url: "http://url-to-submit.com/upload/baza",
data: dataString,
success: function() {
upform.html("<div class='message'></div>");
$('.message').html("<h2>FORM SUBMITTED</h2>")
.append("<p>THANKS!!</p>")
.hide()
.fadeIn(1500, function() {
$('.message').append("<img src='http://my-images.com/i/check.png' />");
});
}
});
return false;
});
});
As you can see, after submit a form, message div appears instead of submitted form.
It works perfectly, when I submit only one form - then it changes to my message div, but when I submit second, and next and next - every time ALL of my already submitted form's messages refreshing.
It looks bad. I want to operate only on actually submitting form. How to fix it?
Well you're setting the message of every .message div by using $('.message').html(). Try this:
upform.find('.message').html(...)
Hard to tell without seeing how your HTML looks but i'm guessing it's this bit,
$('.message')
Should be something like,
$('.message', upForm).
First you have to find out the message div (upform.find('.message')) and than add any html to it. i think your code should be
$(function() {
$(".button").click(function() {
var upform = $(this).closest('.upform');
var txt = $(this).prev(".tekst").val();
var dataString = 'tekst='+ txtr;
$.ajax({
type: "POST",
url: "http://url-to-submit.com/upload/baza",
data: dataString,
success: function() {
upform.html("<div class='message'></div>");
upform.find('.message').html("<h2>FORM SUBMITTED</h2>")
.append("<p>THANKS!!</p>")
.hide()
.fadeIn(1500, function() {
upform.find('.message').append("<img src='http://my-images.com/i/check.png' />");
});
}
});
return false;
});
});
Another way without editing more in your current code just add few lines.
var msgbox = $("<div class='message'></div>");
upform.html(msgbox);
msgbox.html("<h2>FORM SUBMITTED</h2>")
.append("<p>THANKS!!</p>")
.hide()
.fadeIn(1500, function() {
$(this).append("<img src='http://my-images.com/i/check.png' />");
});