Replace string in text area with the value of ajax response - javascript

I have an ajax function that returns a shorturl of an url from a textarea.
When I want to replace the shorturl by the actual url in the text area by using replace, the code not work. this is my implementation
Ajax function:
function checkUrl(text) {
var bit_url = "";
var url = text;
var username = "o_1i42ajamkg"; // bit.ly username
var key = "R_359b9c5990a7488ba5e2b0ed541db820";
return $.ajax({
url: "http://api.bit.ly/v3/shorten",
data: {
longUrl: url,
apiKey: key,
login: username
},
dataType: "jsonp",
async: false,
success: function(v) {
bit_url = v.data.url;
}
});
}
and a function that call the checkurl function is implemented as follow
$("#urlr").change(function() {
var text = $("#Pushtype_message").val();
var c = "";
var msgtext = "";
var urlRegex = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/ig;
var MsgStr = $("#Pushtype_message").val();
var Arr = text.split(" ");
urllist = new Array();
urluri = new Array();
i = 0;
for (var n = 0; n < Arr.length; n++) {
txtStr = Arr[n];
var urltest = urlRegex.test(txtStr);
if (urltest) {
urllist[i] = txtStr;
}
}
for (var i = 0; i < urllist.length; i++) {
// console.log(urllist[i].toString());
checkUrl(urllist[i]).done(function(result) {
var response = (result.data.url);
console.log(response);
MsgStr.replace(urllist[i], response);
console.log(MsgStr);
$("#Pushtype_message").val(MsgStr);
});
}
});
In my text area I put this text:
test utl function https://www.google.Fr test success
and I get in my console the following result
main.js http://bit.****
main.js test utl function https://www.google.Fr test success
As you see, the function return an urlshortner but the initial text still the same. My expected result is: test utl function http://bit.l**** test success, but this don't work.

When working with textarea you can simply replace their text.
$("#Pushtype_message").text(MsgStr);

You need the assign the new value to MsgStr
for(var i=0; i<urllist.length; i++){
// console.log(urllist[i].toString());
checkUrl(urllist[i]).done(function(result){
var response=(result.data.url);
console.log(response);
MsgStr = MsgStr.replace(urllist[i],response);
console.log(MsgStr);
$("#Pushtype_message").val(MsgStr);
});
}
i is defined outside your for loop and used inside it urllist[i]=txtStr; but its value is never assigned, it's alaways = 0:
i=0;
for (var n = 0; n < Arr.length; n++) {
txtStr = Arr[n];
var urltest=urlRegex.test(txtStr);
if(urltest)
{
urllist[i]=txtStr;
}
}

I found the solution about my problem,
I affect urllist[j] to a new variable text, because in the checklist function urllist[j] return an undefined value.
var j=0;
for(j; j<urllist.length; j++){
var text=urllist[j];
checkUrl(urllist[j]).done(function(result){
var response=result.data.url;
console.log(urllist[j]);
MsgStr1 = MsgStr.replace(text,response);
console.log(MsgStr1);
$("#Pushtype_message").val(MsgStr1);
});
}
});

Related

jQuery - how to receive result from an inner ajax call?

I am developing an web app in which the user will be able to identify the location from map by clicking on the map (I use jquery 3.1). The problem is that I have to make some ajax calls, one depend on other, and on the last call the result it's not returned as a whole (full array) and I received only a part of array.
The problem survives from var a4.
How I can make that a4 result to be send as a full array because I tried with deferred but with no expecting result?
var getLocDetails = function () {
// Parse a web api based on user lat & lon
var a1 = $.ajax({
method: 'GET',
url: 'http://nominatim.openstreetmap.org/reverse?lat=44.43588&lon=26.04745&accept-language=ro&format=json'
});
// Get osm_type & osm_id and parse another web service to get a XML document (Ex.: https://www.openstreetmap.org/api/0.6/way/28240583)
var a2 = a1.then(function (data) {
return $.ajax({
method: 'GET',
url: 'https://www.openstreetmap.org/api/0.6/' + data.osm_type + '/' + data.osm_id
})
});
// Get all 'ref' attribute from every 'nd' node from XML and make an array with this values
var a3 = a2.then(function (data) {
var osmChildren = data.documentElement.childNodes;
var out = [];
for (var i = 0; i < osmChildren.length; i++) {
if (osmChildren[i].nodeName == 'way') {
var wayChildren = osmChildren[i].childNodes;
for (var j = 0; j < wayChildren.length; j++) {
if (wayChildren[j].nodeName == 'nd') {
var ndRef = Number.parseInt(wayChildren[j].getAttribute('ref'));
out.push(ndRef);
}
}
}
}
return out;
});
// HERE IS THE PROBLEM
// Based on array returned from a3, I am parsing every link like 'https://www.openstreetmap.org/api/0.6/node/ + nodeRef' to extract every lat and lon values for extreme points
var a4 = a3.then(function (data) {
var defer = $.Deferred();
var out = [];
for (var i = 0; i < data.length; i++) {
var nodeRef = data[i];
var nodeUrl = 'https://www.openstreetmap.org/api/0.6/node/' + nodeRef;
$.ajax({
method: 'GET',
url: nodeUrl
}).done(function (response) {
var node = response.documentElement.firstElementChild;
var lat = Number.parseFloat(node.getAttribute('lat'));
var lng = Number.parseFloat(node.getAttribute('lon'));
out.push([lat, lng]);
defer.resolve(out);
});
}
return defer.promise();
});
// When a4 is done, based his result, I have to have an array of lat & lon coordonates, but I recived only 1-2 coordonates even I have 10.
a4.done(function (data) {
console.log(data);
// Here I have to draw a polygon
});
}
you need to handle the requests in an array, as what you are doing tends to resolve the callback for a4 before all are complete.
To do this we can use $.when function
var req = [];
// Based on array returned from a3, I am parsing every link like 'https://www.openstreetmap.org/api/0.6/node/ + nodeRef' to extract every lat and lon values for extreme points
var a4 = a3.then(function (data) {
var defer = $.Deferred();
var out = [];
for (var i = 0; i < data.length; i++) {
var nodeRef = data[i];
var nodeUrl = 'https://www.openstreetmap.org/api/0.6/node/' + nodeRef;
req.push(
$.ajax({
method: 'GET',
url: nodeUrl
}).done(function (response) {
var node = response.documentElement.firstElementChild;
var lat = Number.parseFloat(node.getAttribute('lat'));
var lng = Number.parseFloat(node.getAttribute('lon'));
out.push([lat, lng]);
})
);
}
$.when.apply($, req).done(function(){
return defer.resolve(out);
});
return defer.promise();
});

How to make a javascript function with elementid like argument?

I have an DevExpress Mvc token extension, where the user will insert several items.
Using javascript I send the items to the controller, which is working fine.
My function look like this:
$(function() {
$("#btnSave").click(function () {
var name = window.ComboBox.GetValue();
var i;
var team = new Array();
var tokens = window.tokenBox.GetTokenCollection();
for (i = 0; i < tokens.length; i++) {
team.push(tokens[i]);
}
var s = new Array();
var ss = window.tokenBox2.GetTokenCollection();
for (i = 0; i < ss.length; i++) {
s.push(ss[i]);
}
var w = new Array();
var ww = window.tokenBox3.GetTokenCollection();
for (i = 0; i < ww.length; i++) {
w.push(ww[i]);
}
var o = new Array();
var oo = window.tokenBox4.GetTokenCollection();
for (i = 0; i < oo.length; i++) {
o.push(oo[i]);
}
var t = new Array();
var tt = window.tokenBox5.GetTokenCollection();
for (i = 0; i < tt.length; i++) {
t.push(tt[i]);
}
$.ajax({
type: "post",
url: '#Url.Action("Action","Controller")',
data: { name:name, team:team, s:s, o:o, w:w, t:t },
beforeSend: function () {
window.loadingPanel.Show();
},
success: function (response) {
$("#mainAjax").html(response);
window.loadingPanel.Hide();
}
});
});
});
I want to use a function, to get the items from token and put them in an array (not repetitive code like above), something like this:
function GetTokenItems(token) {
var list = new Array();
var el = document.getElementsById(token);
var tokens = el.GetTokenCollection();
for (var i = 0; i < tokens.length; i++) {
list.push(tokens[i]);
}
return list;
};
This function is not working, error says:
Uncaught TypeError: document.getElementsById is not a function
How can I pass the Id of the tokenBok like argument in a function, or/and what is wrong with my function?
**Edit:**
I made the correction document.getElementById and now I get the error:
Uncaught TypeError: el.GetTokenCollection is not a function
Should be document.getElementById(id):
Returns a reference to the element by its ID; the ID is a string which can be used to identify the element; it can be established using the id attribute in HTML, or from script.
document.getElementById(...)
// ^ without s
I found the answer of my issue, maybe will be helpfull for others!
For Devexpress mvc extensions is enough to use the name of the extension like argument, no need to look for him with document.getElementById, so my function is working like this:
function GetTokenItems(token) {
var list = new Array();
var tokens = token.GetTokenCollection();
for (var i = 0; i < tokens.length; i++) {
list.push(tokens[i]);
}
return list;
};
now I can call this function like this:
var team=GetTokenItems(tokenBox); and is working!!!

Uncaught TypeError: Cannot read property 'HotelInfo' of undefined

//an ajax call to the api
jQuery(document).ready(function() {
jQuery.ajax({
url:"http://localhost:8080/activitiesWithRealData?location=%22SEA%22&startDate=%2205-14-16%22&endDate=%2205-16-16%22&theme=%22food%22",
dataType: 'JSON', type: 'GET',
success: function (data)
var viewModel;
if(data) {
viewModel = new dealsPageModel(data);
var idList = "";
for (var i = 0; i< data.packageDeal.length; i++)
{
if (i == data.packageDeal.length -1)
{ idList += data.packageDeal[i].hotelId;
}
else
{idList += data.packageDeal[i].hotelId + ',';
}
}
var searchUrl = "http://terminal2.expedia.com/x/hotels?hotelids=" + idList + "&apikey=6weV4ksGIJ5eQhd58o2XTDwVo35lZf2S";
//another call to another api to return hotel specific info
jQuery.get(searchUrl, function ( )
{
for(var i=0; i<viewModel.dealList.length; i++)
{
var hotelId = viewModel.dealList[i].hotelId;
for(var i=0; i<data.HotelInfoList.HotelInfo.length; i++)
{
var url = HotelInfoList.HotelInfo[i].ThumbnailUrl;
var name = HotelInfoList.HotelInfo[i].Name;
}
// Get the hotelid from the current deal
// Loop through the hotelinfolist.hotelInfo and find out the url for the hotel idList
//Loop through the hotelinfolist.hotelInfo and find out the name for the hotel
viewModel.dealList.push(new deal(data.packageDeal[i], url, name));
}
ko.applyBindings(viewModel);
});
}
}
})
});
You loop through data.HotelInfoList.HotelInfo but operate on HotelInfoList.HotelInfo[i].ThumbnailUrl. The data. at the beginning is missing.
Also, place data in the callback function in jQuery.get:
jQuery.get(searchUrl, function(data){
// …
your data is in data.HotelInfoList not in HotelInfoList
your loop should be like this
for(var i=0; i<data.HotelInfoList.HotelInfo.length; i++)
{
var url = data.HotelInfoList.HotelInfo[i].ThumbnailUrl;
var name = data.HotelInfoList.HotelInfo[i].Name;
}

Get anchor tag values in jQuery

I have a html tag like this.
<a class="employee_details" target="_blank" href="index1.php?name=user1&id=123">User</a>
I need to get the two parameter values in jquery
<script type="text/javascript">
$(function () {
$('.employee_details').click(function () {
var status_id = $(this).attr('href').split('name');
alert(status_id[0]);
});
});
</script>
Any help in getting both the parameter values in two variables in javascript.
I want to get user1 and 123 in two variables using jQuery
Thanks
Kimz
You can use URLSearchParams as a most up-to-date and modern solution:
let href = $(this).attr('href');
let pars = new URLSearchParams(href.split("?")[1]);
console.log(pars.get('name'));
Supported in all modern browsers and no jQuery needed!
Original answer:
Try this logic:
var href = $(this).attr('href');
var result = {};
var pars = href.split("?")[1].split("&");
for (var i = 0; i < pars.length; i++)
{
var tmp = pars[i].split("=");
result[tmp[0]] = tmp[1];
}
console.log(result);
So you'll get the parameters as properties on result object, like:
var name = result.name;
var id = result.id;
Fiddle.
An implemented version:
var getParams = function(href)
{
var result = {};
var pars = href.split("?")[1].split("&");
for (var i = 0; i < pars.length; i++)
{
var tmp = pars[i].split("=");
result[tmp[0]] = tmp[1];
}
return result;
};
$('.employee_details').on('click', function (e) {
var params = getParams($(this).attr("href"));
console.log(params);
e.preventDefault();
return false;
});
Fiddle.
$(function() {
$('.employee_details').on("click",function(e) {
e.preventDefault(); // prevents default action
var status_id = $(this).attr('href');
var reg = /name=(\w+).id=(\w+)/g;
console.log(reg.exec(status_id)); // returns ["name=user1&id=123", "user1", "123"]
});
});
// [0] returns `name=user1&id=123`
// [1] returns `user1`
// [2] returns `123`
JSFiddle
NOTE: Better to use ON method instead of click
Not the most cross browser solution, but probably one of the shortest:
$('.employee_details').click(function() {
var params = this.href.split('?').pop().split(/\?|&/).reduce(function(prev, curr) {
var p = curr.split('=');
prev[p[0]] = p[1];
return prev;
}, {});
console.log(params);
});
Output:
Object {name: "user1", id: "123"}
If you need IE7-8 support this solution will not work, as there is not Array.reduce.
$(function () {
$('.employee_details').click(function () {
var query = $(this).attr('href').split('?')[1];
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
var varName = decodeURIComponent(pair[0]);
var varValue = decodeURIComponent(pair[1]);
if (varName == "name") {
alert("name = " + varValue);
} else if (varName == "id") {
alert("id = " + varValue);
}
}
});
});
It's not very elegant, but here it is!
var results = new Array();
var ref_array = $(".employee_details").attr("href").split('?');
if(ref_array && ref_array.length > 1) {
var query_array = ref_array[1].split('&');
if(query_array && query_array.length > 0) {
for(var i = 0;i < query_array.length; i++) {
results.push(query_array[i].split('=')[1]);
}
}
}
In results has the values. This should work for other kinds of url querys.
It's so simple
// function to parse url string
function getParam(url) {
var vars = [],hash;
var hashes = url.slice(url.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
// your code
$(function () {
$('.employee_details').click(function (e) {
e.preventDefault();
var qs = getParam($(this).attr('href'));
alert(qs["name"]);// user1
var status_id = $(this).attr('href').split('name');
});
});

CSV-import via jquery - variable locked in

i use a nice code to import csv data.
However, my variable seems to be somehow caught within the function so i cannot access it from other places in my .js ...
see my two alert functions in the code below.
Code copied from post(How to read data From *.CSV file using javascript?)
$(document).ready(function () {
$.ajax({
type: "GET",
url: "../recipes.csv",
dataType: "text",
success: function (data) {
processData(data);
}
});
});
function processData(allText) {
var allTextLines = allText.split(/\r\n|\n/);
var headers = allTextLines[0].split(',');
var lines = [];
for (var i = 0; i < allTextLines.length; i++) {
var data = allTextLines[i].split(',');
if (data.length == headers.length) {
var tarr = [];
for (var j = 0; j < headers.length; j++) {
tarr.push(data[j]);
}
lines.push(tarr);
}
}
dataArray = (lines + "").split(';');
alert(dataArray[1]); // here it works
}
alert(dataArray[1]); // here it doesn't work: "ReferenceError: dataArray is not defined"
The dataArray variable that the function processData(...) uses exists only inside the function.
In order to use it outside the function you need to declare it. For example:
var dataArray = {};
function processData(allText) {
var allTextLines = allText.split(/\r\n|\n/);
var headers = allTextLines[0].split(',');
var lines = [];
for (var i=0; i<allTextLines.length; i++) {
var data = allTextLines[i].split(',');
if (data.length == headers.length) {
var tarr = [];
for (var j=0; j<headers.length; j++) {
tarr.push(data[j]);
}
lines.push(tarr);
}
}
dataArray = (lines + "").split(';');
alert(dataArray[1]);
}
$(document).ready(function () {
$.ajax({
type: "GET",
url: "../recipes.csv",
dataType: "text",
success: function (data) {
processData(data);
alert(dataArray[1]); // here it will return the data from processData(...)
}
});
});
What is the scope of variables in JavaScript?. Here is an interesting thread for variable scope in JavaScript.

Categories