i'm creating a link sharing that on bind() events of a specific textarea ( where i paste links ) it does an $.post
ajax callback with a preview (in case of youtube or vimeo link). Basically, i would remove link into textarea each times that link is detected and preview is gotten.
this is the function that does the callback :
$('#writer').bind('change keypress keyup keydown',function() {
var value_= $('#writer').val();
$('#thumb-temp').hide();
$.post( 'checklink.php?', { string : value_ },
function(response) {
$('.writer').prepend(response);
$('#thumb-temp').show();
}).fail(function() { alert( "error" ) })
});
and the page checklink.php that should remove the link
<?
$link = $_POST['string'];
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
preg_match($reg_exUrl, $link, $url);
$link = $url[0];
?>
<script>clearTextarea('<? echo $link ?>')</script>
and in the end the clearTextarea() function
function clearTextarea(url) {
var _textarea = $('#writer');
var _curVal = _textarea.val();
var _curUrl = url;
var _regex = new RegExp( _curUrl , 'g' );
var _newVal = _curVal.replace( _regex , '' );
_textarea.val( _newVal );
}
Now, apparentely, this should works but nothing happens, any ideas ? I do not understand where I'm wrong :(
I'm not sure if you can run javascript that way (echoing from PHP). I would call it from the $.post directly.
First of all, I will suggest you not to send the ajax so many times. Regex is basically what you can do in JS as well. So instead of sending ajax - check for links in your JS code. Second, if you want to change the value of textarea, you should use html()
instead of val()
.
The Order should be,
<script type="text/javascript">
function clearTextarea(url) {
var _textarea = $('#writer');
var _curVal = _textarea.val();
var _curUrl = url;
var _regex = new RegExp( _curUrl , 'g' );
var _newVal = _curVal.replace( _regex , '' );
_textarea.val( url );
}
</script>
Textarea in HTML:
<textarea id="writer"></textarea>
PHP code
<?php
$link = $_POST['string'];
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
preg_match($reg_exUrl, $link, $url);
$link = $url[0];
?>
Calling clearTextarea function();
<script>clearTextarea('<?php echo $link ?>');</script>
i solved in this way
function clearTextarea() {
var _textarea = $('#writer');
var _curVal = _textarea.val();
var _curUrl = _curVal.match(/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/gi);
var _newVal = _curVal.replace( _curUrl , '' );
_textarea.val(_newVal);
}
and call clearTextarea() on ajax complete. That's it ;D