I have a JavaScript function in a PhoneGap app that makes a successful call to the barcode scanner (using the Cordova plugin). I then form a JSON string and make a 'return' call in an attempt to pass the string back to the function call assignment. I successfully alert the JSON string in the scanning function but then get an undefined value for the variable that's been assigned the function result. I'm thinking that this might have to do with scope but declaring the variable outside of the function didn't make any difference.
var myscan = null;
var myclueJSON = null;
var myscan = getScan(); //call scanning function and assign result JSON to myscan variable
alert(myscan); //returns undefined
//call PhoneGap barcode scanner function
//and form JSON to return
function getScan()
{
var scanner = cordova.require("cordova/plugin/BarcodeScanner");
scanner.scan( function (result)
{
var myresult = result.text;
var obj= JSON.parse(myresult);
//fetch event id from barcode
var myeventid = obj.eventid;
//fetch clue sequence from barcode
var mycluesequence = obj.cluesequence;
//form JSON string
var myscanJSON = '{"eventid":"' + myeventid + '","cluesequence":"' + mycluesequence + '"}';
//return JSON string
return myscanJSON;
}, function (error)
{
console.log("Scanning failed: ", error);
});
It may be due to the fact you're trying to return myscanJSON within the callback function. You could try declaring an empty string outside the callback then append to it like so:
var myscan = null;
var myclueJSON = null;
var myscan = getScan(); //call scanning function and assign result JSON to myscan variable
alert(myscan); //returns undefined
//call PhoneGap barcode scanner function
//and form JSON to return
function getScan()
{
var scanner = cordova.require("cordova/plugin/BarcodeScanner"),
myscanJSON = '';
scanner.scan( function (result)
{
var myresult = result.text;
var obj= JSON.parse(myresult);
//fetch event id from barcode
var myeventid = obj.eventid;
//fetch clue sequence from barcode
var mycluesequence = obj.cluesequence;
//form JSON string
myscanJSON += '{"eventid":"' + myeventid + '","cluesequence":"' + mycluesequence + '"}';
}, function (error)
{
console.log("Scanning failed: ", error);
});
//return JSON string
return myscanJSON;
}
Or you could refactor your callback function:
var myscan = null;
var myclueJSON = null;
var myscan = scanner.scan(getScan(result), handleError(error)); //call scanning function and assign result JSON to myscan variable
alert(myscan); //returns undefined
//call PhoneGap barcode scanner function
//and form JSON to return
function getScan(result)
{
var myresult = result.text;
var obj= JSON.parse(myresult);
//fetch event id from barcode
var myeventid = obj.eventid;
//fetch clue sequence from barcode
var mycluesequence = obj.cluesequence;
//form JSON string
var myscanJSON = '{"eventid":"' + myeventid + '","cluesequence":"' + mycluesequence + '"}';
//return JSON string
return myscanJSON;
}
function handleError(error){
return error;
}
I refactored the code. It did have a bit of a challenge that I didn't mention. The barcode scanner call needed to be initiated after a successful geolocation call. Since these want to complete asynchronously, I had to nest the getScan function inside the geolocation success function, passing in a simple lat/lng JSON object to the scan function which eventually forms a longer JSON string and makes a jQuery AJAX call to write to a database.
//get current position function
function fetchGeolocation()
{
navigator.geolocation.getCurrentPosition(fetchCoords, handle_error);
}
//extract current coords
function fetchCoords(p)
{
mylocjson = '{"lat":"' + p.coords.latitude + '","lng":"' + p.coords.longitude + '"}';
//fire up scanner, passing in lat/lng JSON string
getScan(mylocjson);
}
//fire up PG scanner and form JSON result object
function getScan(incominglocjson)
{
//parse lat/lng
var clueobj = JSON.parse(incominglocjson);
var scanner = cordova.require("cordova/plugin/BarcodeScanner");
scanner.scan(function (result)
{
var myresult = result.text;
var obj= JSON.parse(myresult);
//fetch event id from barcode
var myclueJSON = '{"eventid":"' + obj.eventid + '","cluesequence":"' + obj.cluesequence + '","lat":"' + clueobj.lat + '","lng":"' + clueobj.lng + '"}';
}//end scanner.scan()
//make AJAX call to save data
$.ajax(
{
url: "http://myurlhere/myfilename.php",
type: 'post',
data:{data:myclueJSON},
success: function(returndata)
{
//process success returndata
},
fail: function(returndata){
//process fail returndata
}
});//end AJAX call to save data
}//end getScan()
//handle current position fetch error
function handle_error(error)
{
switch(error.code)
{
case error.PERMISSION_DENIED:
alert("User denied the request for geolocation. Please allow access to your GPS system when prompted.");
break;
case error.POSITION_UNAVAILABLE:
alert("Location information is unavailable. Check to see if geolocation is enabled on your device.");
break;
case error.TIMEOUT:
alert("The request to get user location timed out. Try moving to a slightly different location to better access the satellite network.");
break;
case error.UNKNOWN_ERROR:
alert("An unknown error occurred. Call tech support at (999) 999-9999.");
break;
}//end error code switch
}//end handle_error()
Related
Now, I have tried to get some data from crawling website.
The target website provides current status of bicycle stations using google map.
GDownloadUrl("/mapAction.do?process=statusMapView", function(data, responseCode) {
var jsonData = eval("(" + data + ")");
//alert(jsonData.centerLat);
var length = jsonData.markers.length;
//if (length > 100) length = 100;
for (var i = 0; i < length; i++) {
var point = new GLatLng(parseFloat(jsonData.markers[i].lat), parseFloat(jsonData.markers[i].lng));
var name = jsonData.markers[i].name;
var cntRackTotal = jsonData.markers[i].cntRackTotal;
var cntRentable = jsonData.markers[i].cntRentable;
var cntLockOff = jsonData.markers[i].cntLockOff;
var cntPrtRack = jsonData.markers[i].cntPrtRack;
var percent = jsonData.markers[i].percent;
var imgFile = jsonData.markers[i].imgFile;
var number = jsonData.markers[i].kiosk_no;
//map.addOverlay(createMarker(number, point, name, cntRackTotal, cntRentable, cntLockOff, cntPrtRack, percent, imgFile ));
}
});
This JS source code is used on target website. In GDownloadUrl callback function, the parameter "data" contains current status of bicycle stations. And I want to get data.
Now, I tried using python selenium and execute_script().
jsSourcecode = ("var strData;"+
"strData = GDownloadUrl('/mapAction.do?process=statusMapView',"+
" function(data, responseCode) {return data;}); return strData;")
data = driver.execute_script(jsSourcecode)
this source code is that I used to get data. I expected data on callback would be stored on var strData and the return value of execute_script() would be the data. but the return value is just "True".
I have little knowledge about js.. How can I get the data? Please help
The function you are calling is asynchronous and requires a callback function as argument.
Use execute_async_script and provide the callback present in the last argument:
data, status = driver.execute_async_script("""
var callback = arguments[0];
window.GDownloadUrl('/mapAction.do?process=statusMapView', function(data, status){
callback([data, status]);
});
""")
I have two functions I am using to pull JSON from my server side to then display it to HTML.
The first function that pulls the data from the route handler is successfully pulling the data and parsing it successfully with JSON.parse() and displaying the needed information to the console without issue. I am not having and ajax or route handling issue...
Here is how I am dealing with the JSON first in my function called "projectInfo()":
projInfo = JSON.stringify(data);
console.log("DEBUG DONE WITH CAPTURING project_info DATA: " );
// This console.log() prints the JSON string
// successfully pulled from route handler
// var projInfo is a local string var declared in the scope of
// this first function
console.log("var projInfo: " + projInfo);
// parse JSON data in projInfo and store in string var p
// string var p is a local var declared inside of the scope
// of this function
p = JSON.parse(projInfo);
console.log("Parsed Project JSON: " + p.Project);
// update "Global" pInfo with the value of the JSON data for
// "Project" as needed
pInfo = p;
console.log("What is inside of pInfo???: " + pInfo);
// This last console.log prints [object Object] to console
// How do I pul the value out of this Object?
The second function calls the first function in order to update a global variable with the parsed JSON data that I need to then display the global variable's data to the DOM element that I am trying to display.
Here is how I am trying to update my global var with a JSON Object in my function called "loginFun()":
// Call projectInfo() in order to update Global pInfo
// with the needed project info
projectInfo();
// This console.log() prints nothing...?
console.log("projectInfo var data should be aa2: " + pInfo);
document.getElementById("userBar").style.display = "";
// This is where I try to Display pInfo in the DOM but I only get Undefined...?
document.getElementById("signedinas").innerHTML = "<font face=\"verdana\" size =\"4\" color=\"white\">Logged in as: " + username + " Project: " + pInfo + " </font>";
When I JSON.parse() the data in the first function I run a console.log() statement and I get the needed data to print from a variable local to the function I am getting my JSON with using ajax and I verify that the function is in fact doing what I need so that part is good up until I get the [object Object] output.
I am having issues when I call this function from my second function to then try to use the global variable which should have the data stored.
when I try to use the global variable with the needed data I get an 'undefined'...
I have also tried returning the data that has been parsed in the first function to then storehttps://codepen.io/lopezdp/pen/owKGdJ the value returned into a local variable in the second function but I still get 'undefined'.
If you would like to see the complete code for both functions I have put them on a CodePen to make it easier at:
https://codepen.io/lopezdp/pen/owKGdJ
How can I get my Project Data to display in my DOM element?
EDIT: The JSON Data that I am using looks like this:
{"User":"aa2","Owner":"aa2_role","Status":"locked","Port":"5432","Description":"Transferred from CFS01 on Jun29","Project":"aa2","Server":"localhost"}
I rewrote your login function like this and it worked for me. I also eliminated the projectInfo() function!
var allMn = [];
var tags = [];
var pInfo = '';
function loginFun() {
var username = document.getElementById('username').value;
var password = document.getElementById('password').value;
if (username == "" || password == "") {
alert("Required fields cannot be left blank.");
} else {
$.ajaxSetup({
cache: false
});
$.ajax({
type: 'GET',
url: 'http://139.169.63.170:' + port + '/login/' + username + "zlz" + password,
cache: false,
success: function (data) {
// NEED SUB ROUTINE HERE FOR AJAX CALL DPL
// Make async call to ccdd tool database to get new data
// This collects allMn[] data!!!
getMnJson();
// END SUB ROUTINE HERE
// Checks to make sure user is logged in if not
// the condition redirects user to loginFun()
if (data.search("HTTP ERROR: ") != -1) {
alert("Login Failed.");
document.getElementById('username').value = "";
document.getElementById('password').value = "";
document.getElementById('searchResults').innerHTML = "Login Failed";
document.getElementById('searchRBar').style.display = "";
loginFun();
} else {
login = 1;
// Call projectInfo() in order to update pInfo with the needed project info
//projectInfo();
var projInfo = '';
var p = '';
// Get all Mn Data on startup tp display in DOM -DPL
$.ajax({
type: 'GET',
url: 'http://139.169.63.170:' + port + '/role',
dataType: 'json',
cache: true,
success: function (data) {
// projInfo = JSON.stringify(data);
console.log("DEBUG DONE WITH CAPTURING project_info DATA: " );
// console.log("var projInfo: " + projInfo);
// parse JSON data in projInfo
p = data['Project']; //JSON.parse(projInfo);
console.log("Parsed Project JSON: " + p);
// update "Global" pInfo with the value of the JSON data for "Project" as needed
pInfo = p;
console.log("What is inside of pInfo???: " + pInfo);
document.getElementById("signedinas").innerHTML = "<font face=\"verdana\" size =\"4\" color=\"white\">Logged in as: " + username + " Project: " + pInfo + " </font>";
}
}).fail(function () {
alert("Login Failed.");
document.getElementById('username').value = "";
document.getElementById('password').value = "";
console.log("Error. /role data access Error.");
});
console.log("projectInfo var data should be aa2: " + pInfo);
document.getElementById("userBar").style.display = "";
// Display pInfo in the DOM
// document.getElementById("signedinas").innerHTML = "<font face=\"verdana\" size =\"4\" color=\"white\">Logged in as: " + username + " Project: " + pInfo + " </font>";
$("div.create").children().remove();
//-------------------------------------------------------------------END OF GLOBAL VARIABLES
$.ajaxSetup({
cache: false
});
// get table data from proxy server on port 7071 DPL
// NEED SUB ROUTINE HERE FOR AJAX CALL
// Make call to server-side code to reload JSON data into table from port 7071
pushJsonData();
// END SUB ROUTINE HERE!!!
// getTblJson();
}
}
}).fail(function () {
alert("Login Failed.");
document.getElementById('username').value = "";
document.getElementById('password').value = "";
console.log("Error. Need user Credentials");
});
}
}
I am fairly new to js and node.js but I have managed to get the calls going to the API and getting the necessary information. However when I was attempting to continue to raise the batter id to get the next information available. I have successfully gotten the undefined error check to work as well. But I was unable to loop through because I was trying to perform something immediately on an async function. I am now trying to make the entire function async with a 2 second delay after each run, but it is returning the following error (i'm assuming because something is undefined)
**Note: When I just get the value for i=4 and p=1 the value does exist in the API data. However it gives this error when I attempt to start with those values using this code.
error:
Unexpected token u in JSON at position 0
this is my code:
request('API Info redacted',
setTimeout (function (err, response, body) {
//do stuff below
//to get the first play of the game, set i=1 and p=0
var i = 4;
var p = 1;
// ************
var boolIn = 1;
// parse the body as JSON
var parsedBody = JSON.parse(body);
var apiResults = parsedBody.apiResults;
if( typeof(apiResults[0].league.season.eventType[0].events[0].pbp[i].pbpDetails[p]) == 'undefined') {
//sets the variables to the first batter of the next inning
p=0;
i = i+1;
}
//below pulls the apiResults from the body of the API request
var sportId = apiResults.sportId;
var hitName = apiResults[0].league.season.eventType[0].events[0].pbp[i].pbpDetails[p].name;
var fname = apiResults[0].league.season.eventType[0].events[0].pbp[i].pbpDetails[p].batter.firstName;
var lname = apiResults[0].league.season.eventType[0].events[0].pbp[i].pbpDetails[p].batter.lastName;
var outsB = apiResults[0].league.season.eventType[0].events[0].pbp[i].pbpDetails[p].outs.before;
var outsA = apiResults[0].league.season.eventType[0].events[0].pbp[i].pbpDetails[p].outs.after;
var rbis = apiResults[0].league.season.eventType[0].events[0].pbp[i].pbpDetails[p].runsBattedIn;
var outDifference = (outsA - outsB);
var hitB = apiResults[0].league.season.eventType[0].events[0].pbp[i].pbpDetails[p].baseSituation.beforeId;
var hitA = apiResults[0].league.season.eventType[0].events[0].pbp[i].pbpDetails[p].baseSituation.afterId;
var baseDifference = (hitA - hitB);
//prints the details pulled above
res.json("First Name: " + fname + ", Last Name: " + lname + ", Hit name: " + hitName + ", Outs on the play: " + outDifference + ", Rbi's: " + rbis +
", Base Sit: " + baseDifference);
//increases the batter call
p = p+1;
//below ends the setTimeout
}, 2000));
//ended request
});
setTimeout will not pass arguments to the function it calls, so body is undefined. When you pass that to JSON.parse, it will be converted to the string "undefined", which isn't a valid JSON text.
Nowhere is your code do you show any JSON coming into your program (or embedded into it). You need to have some JSON to parse before you try to parse it.
I have been trying the code given in
How to use YQL to retrieve web results?
but it is not working.
Please suggest me something else or rectify that code.
I am just calling a function on page_load
<body onload = "load_content();">
In the load_content() method, I have to get the feed of other web site and display it on my HTML page.
Load_Content method
var query = "select * from html where url='http://www.imdb.com/title/tt0123865/'";
// Define your callback:
var callback = function(data) {
console.log("DATA : " + data);
};
// Instantiate with the query:
var firstFeedItem = new YQLQuery(query, callback);
// If you're ready then go:
console.log("FEED : " + firstFeedItem.fetch()); // Go!!
Function YQLQuery
function YQLQuery(query, callback)
{
this.query = query;
this.callback = callback || function(){};
this.fetch = function() {
if (!this.query || !this.callback) {
throw new Error('YQLQuery.fetch(): Parameters may be undefined');
}
var scriptEl = document.createElement('script'),
uid = 'yql' + +new Date(),
encodedQuery = encodeURIComponent(this.query.toLowerCase()),
instance = this;
YQLQuery[uid] = function(json) {
instance.callback(json);
delete YQLQuery[uid];
document.body.removeChild(scriptEl);
};
scriptEl.src = 'http://query.yahooapis.com/v1/public/yql?q='
+ encodedQuery + '&format=json&callback=YQLQuery.' + uid;
document.body.appendChild(scriptEl);
};
}
Nothing is coming in data variable
A simple get request is an answer to this.
$.get("http://www.imdb.com/title/tt1243957/",
function(data){
console.log(data);
}//end function(data)
);//end getJSON
I'm using the following code to make ajax call where the form data is passed as params.
//ajax call
function restServiceCall(origin,destination,tripType,dateDepart,dateReturn){
dataString = 'origin='+ origin + '&destination=' + destination + '&tripType='+tripType;
$.jsonp({
"url": flightURL,
callbackParameter:jsonpCallBack,
data: dataString,
beforeSend:function(){$('#loadingdiv').show()},
"success": function(data) {
if(data.error != null){
$('#errtitle').html('<h2 class="pgtitle">Error !! '+data.error+'</h2>').show();
$("#displaydiv,loadingdiv").hide();
}else{
renderData (data,dateDepart,dateReturn);
}
},
"error": function(xOptions, textStatus) {
$('#errtitle').html('<h2 class="pgtitle">Sorry the service you are looking for is currently unavailable</h2>').show();
$("#displaydiv,loadingdiv").hide();
}
});
}
Besides making the call from form I also use it in the following function wherein I just need to pass either the dateDepart/dateReturn as params.
//for pagination
$('.pagenation a').bind('click',function(){
var numDays = 7;
var self = $(this);
var dateTemp = self.parents(':eq(1)').attr('id')=="onewaytripdiv"? parseDate(dateDepart):parseDate(dateReturn);
if(self.hasClass('left')){
var tempDepDate = removeNumOfDays(dateTemp,numDays);
}else{
var tempDepDate = addNumOfDays(dateTemp,numDays);
}
var changedDate = tempDepDate.getDate()+' '+cx.monthNamesShort[tempDepDate.getMonth()]+' '+tempDepDate.getFullYear();
if(self.parents(':eq(1)').attr('id')=="onewaytripdiv"){
dateDepart = changedDate;
}else{
dateReturn = changedDate;
}
restServiceCall(origin,destination,tripType,dateDepart,dateReturn);
});
I would like to remove the params in the function call, as the params may vary. Please suggest an alternative to pass the params.
How about passing an array of parameters instead? And then pass another value, such as an integer to indicate to the function what to expect in it's parameter array.
e.g
restServiceCall(myParams, 0);