Ajax return response, but I can't add it to my textarea

83 views Asked by At

I want to customize my text area by detecting an url and then transform it to urlshortner and put it in the text area. but the problem that this url cannot added to my textarea. my script work as follow:

1: I get the full text from the text area.

2: I test if a string is an url or not

3: I call ajax to get the urlshortner

4: I add the returned url to an array.

5: I put the new text to my textarea

but the problems always I see the initial text in my textarea.

text area before call ajax

this my code

function shortner(tex){
    var c="";
    var msgtext="";
    var urlRegex = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
    var MsgStr = $("#Pushtype_message").val();
    var Arr = tex.split(" ");
    //  $("#Pushtype_message").val("");
    var final=0;
    var pushs=[];
    var n=0;
    while (n < Arr.length) {
        txtStr = Arr[n];
        var urltest=urlRegex.test(txtStr);
        if(urltest)
        {
            var bit_url="";
            var url=txtStr;
            var username="o_1i42ajamkg"; // bit.ly username
            var key="R_359b9c59*************";
            $.ajax({
                url:"http://api.bit.ly/v3/shorten",
                data:{longUrl:url, apiKey:key, login:username},
                dataType:"jsonp",
                async: false,
                success:function(v)
                {
                    if(v.data.url != null){
                        bitly = v.data.url;
                        pushs.push(bitly);
                        n++;
                        console.log(pushs);
                    }
                }
            });
        }else{
            pushs.push(txtStr);
            n++;
            //var txt= $("#Pushtype_message").val();
        }
    }
    return pushs;
}

$("#urlr").change(function()
{
    var text=  $("#Pushtype_message").val();
    points=shortner(text);
    /// console.log(points);
    $("#Pushtype_message").val(points.join(' '));
});

when I execute my script I got the following result

Array [ "jkhfsdkfh", "https://www.google.Fr", "sdfhksdhfsdf", "http://bit.******" ]

as you see here, https://www.google.fr still in the text , but I want to replace it by the url returned by the bitly.

Thank You for help

0

There are 0 answers