CSV-import via jquery - variable locked in - javascript

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.

Related

AJAX return JSON filtered response with callback

I feel like im close, i need to return my filtered json object data and be able to use it in future functions. My main issue im having is its saying "callback is not a function". I used the second method in the top response here How do I return the response from an asynchronous call?
Thanks!
function randomFxn(callback){
var newObj = {};
$.ajax({
type: 'GET',
url: 'https://api.imgur.com/3/album/' + imgurID + '/images',
headers: {'Authorization': 'Client-ID '+ key},
success: function(jsonData){
var nameArr = ['mario', 'luigi', "...some other stuff"];
var counter = 0;
var inCounter = 0;
for(var i = 0; i < nameArr.length; i++){
for (var j = 0; j < 8; j++){
newObj[nameArr[counter]+j] = jsonData.data[inCounter].link;
}
counter++;
}
// $('body').html(`<pre>${JSON.stringify(newObj, null, '\t')}</pre>`);
console.log(newObj);
callback(newObj);
}
});
}
I guess, you have to call randomFxn like so:
randomFxn(function(result) {
console.log("got result", result);
});
The error is not in this function - it is how you are calling this function.
There are two ways to fix the problem, depending upon the logic of your application. You could change your function to this:
function randomFxn(){
var newObj = {};
$.ajax({
type: 'GET',
url: 'https://api.imgur.com/3/album/' + imgurID + '/images',
headers: {'Authorization': 'Client-ID '+ key},
success: function(jsonData){
var nameArr = ['mario', 'luigi', "...some other stuff"];
var counter = 0;
var inCounter = 0;
for(var i = 0; i < nameArr.length; i++){
for (var j = 0; j < 8; j++){
newObj[nameArr[counter]+j] = jsonData.data[inCounter].link;
}
counter++;
}
// $('body').html(`<pre>${JSON.stringify(newObj, null, '\t')}</pre>`);
console.log(newObj);
}
});
}
Or, wherever you call randomFxn, you need to pass another function as a parameter:
randomFxn(function() {
// do something here
});

Replace string in text area with the value of ajax response

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);
});
}
});

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;
}

Transfer data from php as json, then store it in global object

I have the following code:
PHP code:
$data = array();
$data[0]['name'] = "Kj";
$data[0]['age'] = 30;
$data[0]['country'] = "Italy";
$data[1]['name'] = "Dn";
$data[1]['age'] = 18;
$data[1]['country'] = "USA";
$data[2]['name'] = "Jo";
$data[2]['age'] = 22;
$data[2]['country'] = "Switzerland";
$data[3]['name'] = "Ro";
$data[3]['age'] = 34;
$data[3]['country'] = "UAE";
$data[4]['name'] = "Lc";
$data[4]['age'] = 13;
$data[4]['country'] = "UK";
echo json_encode($data);
Javascript code:
var jsonData = {};
$(document).ready(function () {
$.get('page.php', function (data) {
jsonData = jQuery.parseJSON(data);
});
});
for (var i = 0; i < jsonData.length; i++) {
$('ul').append("<li>" + jsonData[i].name + "</li>");
}
The problem is when put the for loop inside the $.get callback works fine like as the following.
$.get('page.php', function (data) {
jsonData = jQuery.parseJSON(data);
for (var i = 0; i < jsonData.length; i++) {
$('ul').append("<li>" + jsonData[i].name + "</li>");
}
});
But when put the for loop outside the $.get callback does not print out anything, but the data has been received successfully, but without print it.
Now, how can store the data that has been received in global variable to print it in anywhere ?
You should change your approach when you work with asynchronous operations (AJAX, timeouts). Something like this:
function GetData(callback) {
$.get('page.php', function (data) {
callback(jQuery.parseJSON(data));
});
}
GetData(function (data) {
for (var i = 0; i < data.length; i++) {
$('ul').append("<li>" + data[i].name + "</li>");
}
});
Your code already stores data in a global variable correctly.
Type jsonData into F12-javascript console and you will see it.
The question is rather about the control flow, what is the other event that will trigger usage of jsonData?

jquery problem in IE with dynamic dropdown selection

Hi jquery/javascript gurus,
I am trying to use jquery ajax function to populate the dropdown, it works fine with FF, but IE give the javascript error snow below in the scrnshot. howver IE does get the data and selects it.
Am i doing something wrong?
function getAjaxFunction(thisval, curval) {
$.ajax({
type: "POST",
url: "lookup.do?param="+thisval,
cache: false,
success: function(data) {
var values = data;
var vals = values.split(";");
$("#dropdown").find("option").remove().end();
for (var i = 0; i < vals.length; i++) {
var parts = vals[i].split(":");
$("#dropdown").append($('<option />').val(parts[0]).text(parts[1]));
}
$("#dropdown").val(curval);
}
});
}
You say val(curval) at the end of your function, but your function parameter is named currval with two Rs.
This worked!
function getAjaxFunction(thisval, curval) {
$.ajax({
type: "POST",
url: "lookup.do?param="+thisval,
cache: false,
success: function(data) {
var values = data;
var vals = values.split(";");
$("#dropdown").find("option").remove().end();
for (var i = 0; i < vals.length; i++) {
var parts = vals[i].split(":");
$("#dropdown").append($('<option />').val(parts[0]).text(parts[1]));
}
try {
$("#dropdown").val(curval);
} catch(ex) {
setTimeout("$('#dropdown').val('"+curval+"')",1);
}
}
});
}

Categories