Angularjs [Ionic] error open file from copy to device - javascript

I am creating an application for my internship, and I have a problem, I need to go to a server, and copy the data from a file to the local database (so the user can have access to the offline application). In PhoneGap, was working perfectly, but as the layout was changed to ionic, the code stopped working can anyone help?
It is my code:
.controller('MapCtrl', function($scope) {
var conect;
if(navigator && navigator.connection && navigator.connection.type === 'none')
{
conect=0;
}
else
{
conect=1;
}
var db = window.openDatabase("Database", "1.0", "Cordova Demo", 200000);
db.transaction(populateDB, errorCB);
function populateDB(tx) {
tx.executeSql('DROP TABLE IF EXISTS DEMO');
tx.executeSql('CREATE TABLE IF NOT EXISTS DEMO (id INTEGER, NEVENTO, DATA, HORA, LOCAL, FREGUESIA, CATEGORIAS, DESC_BRE, DESC, LAT, LON)');
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
var xmlhttp = new XMLHttpRequest();
}
else
{// code for IE6, IE5
var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", "https://dl.dropboxusercontent.com/u/2906080/event_catalog.xml", false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
var x = xmlDoc.getElementsByTagName("EVENT");
for (i = 0; i < x.length; i++)
{
var xName = x[i].getElementsByTagName("NEVENTO")[0].childNodes[0].nodeValue;
var xData = x[i].getElementsByTagName("DATA")[0].childNodes[0].nodeValue;
var xHora = x[i].getElementsByTagName("HORA")[0].childNodes[0].nodeValue;
var xLocal = x[i].getElementsByTagName("LOCAL")[0].childNodes[0].nodeValue;
var xFregsia = x[i].getElementsByTagName("FREGUESIA")[0].childNodes[0].nodeValue;
var xCategoria = x[i].getElementsByTagName("CATEGORIAS")[0].childNodes[0].nodeValue;
var xDescbre = x[i].getElementsByTagName("BRE")[0].childNodes[0].nodeValue;
var xDesc = x[i].getElementsByTagName("DESC")[0].childNodes[0].nodeValue;
var xLat = x[i].getElementsByTagName("LAT")[0].childNodes[0].nodeValue;
var xLon = x[i].getElementsByTagName("LON")[0].childNodes[0].nodeValue;
tx.executeSql('INSERT INTO DEMO (id, NEVENTO, DATA, HORA, LOCAL, FREGUESIA, CATEGORIAS, DESC_BRE, DESC, LAT, LON) VALUES ("' + i + '", "' + xName + '", "' + xData + '", "' + xHora + '","' + xLocal + '", "' + xFregsia + '","' + xCategoria + '", "' + xDescbre + '","' + xDesc + '","' + xLat + '","' + xLon + '")');
}
alert("Base de dados actualizada!!");
}
})
I put alerts in code, code missed after xmlhttp.send(); I think is problem in CROSS DOMAIN some could confirm and could help was very good.

Related

Sheet JS using spaces in excel file headers

I'm using SheetJS to parse out an externally linked excel spreadsheet and create some HTML elements.
Overall, the way that I have it set up is fine, but I noticed that if the excel sheet that I'm referencing has spaces in the header (e.g. - First Name, Last Name, etc.) it won't recognize that and errors out. And I'm not sure how to go about accommodating the spaces in the headers.
Here's what I have:
Excel File Data:
JS:
var url = "https://assets.codepen.io/8689/test2.xlsx";
/* set up XMLHttpRequest */
var oReq = new XMLHttpRequest();
oReq.open("GET", url, true);
oReq.responseType = "arraybuffer";
oReq.onload = function (e) {
var arraybuffer = oReq.response;
/* convert data to binary string */
var data = new Uint8Array(arraybuffer);
var arr = new Array();
for (var i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]);
var bstr = arr.join("");
/* Call XLSX */
var workbook = XLSX.read(bstr, { type: "binary" });
/* DO SOMETHING WITH workbook HERE */
var first_sheet_name = workbook.SheetNames[0];
/* Get worksheet */
var worksheet = workbook.Sheets[first_sheet_name];
var jData = XLSX.utils.sheet_to_json(worksheet, { raw: false });
$.each(jData, function (i, f) {
var el =
"<div class='thing'>" +
"<h2>" +
f.First Name +
" " +
f.Last Name +
"</h2>" +
"<h3>" +
f.Title +
"</h3>" +
"<p>" +
f.Comment +
"</p>" +
"</div>";
$(el).appendTo("#wrapper");
});
console.log(jData);
};
oReq.send();
I know that f.First Name and f.Last Name will error out, and I'm not sure what I can do to try and get it to accommodate the space. I tried an underscore, but that obviously doesn't work either (I kind of figured, but I wanted to test to be sure).
Ok, I did some more digging and I realized that since this is JSON data that is being parsed, I can use bracket notation to help parse that out:
$.each(jData, function (i, f) {
var el =
"<div class='thing'>" +
"<h2>" +
f["First Name"] +
" " +
f["Last Name"] +
"</h2>" +
"<h3>" +
f.Title +
"</h3>" +
"<p>" +
f.Comment +
"</p>" +
"</div>";
});

Http Post image fails in browser/Ripple emulator

I am writing a small Cordova (PhoneGap) app. that is sending an image from a file input - using a post method. It works fine in my Android device, but fails in both broswer and Ripple emulator. Here is the code:
function queryImageByData(dataURL) {
var imgType = dataURL.substring(5, dataURL.indexOf(";"));
var imgExt = imgType.split("/")[1];
var imgData = atob(dataURL.substring(dataURL.indexOf(",") + 1));
var filenameTimestamp = (new Date().getTime());
var separator = "----------12345-multipart-boundary-" + filenameTimestamp;
var formData = "--" + separator + "\r\n" +
"Content-Disposition: file; name=\"file\"; filename=\"snapshot_" + filenameTimestamp + "." + imgExt + "\"\r\n" +
"Content-Type: " + imgType + "\r\nContent-Transfer-Encoding: base64" + "\r\n\r\n" + imgData + "\r\n--" + separator + "\r\n";
var xhr = new XMLHttpRequest();
xhr.sendAsBinary = function (data) {
var arrb = new ArrayBuffer(data.length);
var ui8a = new Uint8Array(arrb, 0);
for (var i = 0; i < data.length; i++) {
ui8a[i] = (data.charCodeAt(i) & 0xff);
}
var blob = new Blob([arrb]);
this.send(blob);
};
xhr.open("POST", "https:/my_endpoint_here", true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
parseResult(xhr.responseText);
}
else {
onFailedResponse(xhr.responseText);
}
}
};
xhr.setRequestHeader("Content-type", "multipart/form-data; boundary=" + separator);
xhr.sendAsBinary(formData);
}
The error I get is:
Error: MultipartParser.end(): stream ended unexpectedly: state = HEADER_FIELD_START
at MultipartParser.end
EDIT:
I have a problem also with a get method. It fails on Ripple/Browser but runs OK on the device. here is some sample code:
var url = document.getElementById("urlInput").value;
var query = "my_url_here";
var jqxhr = $.ajax(query)
.done(function (data) {
alert("success" + data);
})
.fail(function (data) {
alert("error" + data);
})
Well I found the core issue, which cross domain calls.
The browsers do not allow it, and apperently so does Ripple emulator,
but mobile devices do allow it.
Now I just need to figure out how to make it work using CORS.

How do I tell what referral url my httprequest says it's coming from?

I'm sending an xmlhttprequest to youtube to get some videos. I have gone to the google developer's console and set up an api key with WORK URL I'm requesting from connected to it. When I try to run the script from WORK URL, I get an 'ipreferrer not allowed' error, even though I specified that url on my api key.
But when I connect the api key to MY OWN PERSONAL URL and run the same script from that url, it works fine. So when it's run from WORK URL it must be sending the wrong referral url to youtube.
The question is, how can I tell what referral url my xmlhttprequest is telling youtube it is coming from?
My code is below:
function createCORSRequest(myurl, cb)
{
var xmlhttp;
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();}
else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
if( typeof cb === 'function' )
cb(xmlhttp.responseText);
}
}
xmlhttp.open("GET",myurl,true);
xmlhttp.send();
}
function buildVideoMenu()
{
openDiv = true;
mainVideoTarget = 'main_video';
playlistID = 'PLAg45-Ox3WR4gODmcAmIYHVvCpngXcCTZ';
menuDiv = 'video_menu_images';
thumbnailDiv = 'thumb';
APIKey = 'AIzaSy...';
url = 'https://www.googleapis.com/youtube/v3/playlistItems?' +
'&part=snippet' +
'&maxResults=25' +
'&playlistId=' + playlistID +
'&key=' + APIKey;
//alert(url);
createCORSRequest(url, function(srchJSON) //Get JSON for search
{
myDivHTML = '';
myDiv = document.getElementById("video_menu_images"); //get div in variable
console.log("YouTube returned the json code: " + srchJSON);
srchObj = JSON.parse(srchJSON); //parse JSON for playlistItems
for(i=0;i<srchObj.items.length;i++) //For items in srchObj.items:
{
console.log("item number " + i);
if(srchObj.items[i].snippet.thumbnails!=undefined)
{
if(openDiv)
{
myDivHTML += '<div id = "tnvertblock">';
}
myDivHTML += ' <div class = "' + thumbnailDiv + '">';
//console.log(srchObj.items[i].snippet.title);
vidFrameURL = 'https://www.youtube.com/embed/' + srchObj.items[i].snippet.resourceId.videoId;
//console.log("url = " + vidFrameURL);
imgUrl = srchObj.items[i].snippet.thumbnails.default.url; //get thumbnail image url
myDivHTML += ' <a href = "' + vidFrameURL + '" target = "' + mainVideoTarget +'">';
myDivHTML += ' <img width = "120" height = "90" class = "thumbnail" src = "' + imgUrl + '" />';
myDivHTML += ' </a>';// Put in the item.snippet.thumbnails.default.url (its own div)
myDivHTML += ' </div>'; //close thumbnail div
if(!openDiv)
{
myDivHTML += '</div>';
}
openDiv = !openDiv;
}
}
//alert(myDivHTML);
myDiv.innerHTML = myDivHTML;
});
}
buildVideoMenu();
UPDATE: To clarify my question, here's a screenshot of the console developer's page with an explanation:

pass variable by jquery mobile from page to page

i have this code that fill ListView by xml file.
when i press on one item in the ListView i go to page2.
how to pass the Fname, Lname , Phone ..... variables for the person that i pick in the ListView to page2 ?
<script>
var ALL;
var ID, Fname, Lname, Phone, Car;
function XX() {
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", "DD.xml", false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
$("#ZIBI").empty();
var x = xmlDoc.getElementsByTagName("men");
for (i = 0; i < x.length; i++) {
try{ID = x[i].getElementsByTagName("ID")[0].childNodes[0].nodeValue;}
catch (err) { ID = "0";}
try{Fname = x[i].getElementsByTagName("Fname")[0].childNodes[0].nodeValue;}
catch (err) { Fname = "0"; }
try{Lname = x[i].getElementsByTagName("Lname")[0].childNodes[0].nodeValue;}
catch (err) { Lname = "0"; }
try{Phone = x[i].getElementsByTagName("S_phone")[0].childNodes[0].nodeValue;}
catch (err) { Phone = "0"; }
try { Car = x[i].getElementsByTagName("car")[0].childNodes[0].nodeValue; }
catch (err) { Car = "0"; }
ALL =
'<li>' +
'<a href="page2.html" data-transition="slidedown">' +
//'<a href="tel:' + Phone + ' data-icon="location">' +
'<img src="PIC/' + ID + '.jpeg">' +
'<p class="nam">' + Fname + " " + Lname + '</p>' +
'<p class="phn">' + Phone + '</p>' +
'<p class="crr">' + Car + '</p>' +
'</a>' +
'<a href="tel:' + Phone + ' data-icon="location" ></a>' +
'</li>'
$("#ZIBI").append(ALL);
$("#ZIBI").listview("refresh");
}
}
</script>
In the new page you can use the following:
var fullname = $(this).find('p.nam').text();
var phone = $(this).find('p.phn').text();
var car = $(this).find('p.crr').text();
within the click handler for the link clicked.
However, if you have turned off ajax navigation, the above would not work.
$(document).on('click', 'li a', function() {
//catch them here
});

new XMLHttpRequest cannot run on Firefox

The script below work perfectly in IE for the XML respond. But seems i cant figured out how to run on Firefox or Chorme. Try few modification but still not able to run it. Kindly need assistant.
<script type="text/javascript" language="javascript">
var xmlhttp;
var timeStamp;
var currentTime = new Date()
var month = currentTime.getMonth() + 1
var day = currentTime.getDate() //remove the + 1 afterwards
var year = currentTime.getFullYear()
var hour = currentTime.getHours()
var minutes = currentTime.getMinutes()
var second = currentTime.getSeconds() + 1
timeStamp = day + "/" + month + "/" + year + " " + hour + ":" + minutes + ":" + second;
function on_click()
{
var xmlToSend = "<?xml version='1.0' encoding='utf-8'?>";
xmlToSend += "<soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' ";
xmlToSend += "xmlns:xsd='http://www.w3.org/2001/XMLSchema' ";
xmlToSend += "xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>";
xmlToSend += "<soap:Body><Welcomescreen Sender='SENDERDDRESS' TimeStamp='28/10/2009 16:49:31' Type='1' Workshop='SG' RequireAppointmentDate='2010/01/04' xmlns='http://www.SENDERDDRESS.com/integration'/>";
xmlToSend += "</soap:Body></soap:Envelope>";
/
var xmldoc = new ActiveXObject("Microsoft.XMLDOM");
xmldoc.loadXML(xmlToSend);
if (window.XMLHttpRequest)
{/ / code
for IE7 + , Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = state_Change;
xmlhttp.open("POST", "http://SENDERDDRESS:4509/resd", false);
xmlhttp.setRequestHeader("SOAPAction", "http://www.mhe.com/SRP/requestVinRequest");
xmlhttp.setRequestHeader("Content-Type", "text/xml");
xmlhttp.setRequestHeader("User-Agent", "Jakarta Commons-HttpClient/3.0.1");
xmlhttp.setRequestHeader("Host", "SENDERDDRESS:4509");
xmlhttp.setRequestHeader("Content-Length", "391");
xmlhttp.send(xmldoc);
var objResponse = document.getElementsByTagName("Appointment");
objResponse.innerText = xmlhttp.responseXML.xml;
}
function state_Change()
{
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
txt = "<table align='right' border='1' width='400'><tr><th><font color='#d9d7d7' size='4' face='verdana'>Time</font></th><th><font color='#d9d7d7' size='4' face='verdana'>Plate No.</font></th><th><font color='#d9d7d7' size='4' face='verdana'>Status</font></th></tr>";
x = xmlhttp.responseXML.documentElement.getElementsByTagName("Appointment");
for (i = 0; i < x.length; i++) {
xx = x[i].getElementsByTagName("AppointmentTime"); {
try {
txt = txt + "<td><font size = 5>" + xx[0].firstChild.nodeValue + "</font></td>";
} catch (er) {
txt = txt + "<td> </td>";
}
}
xx = x[i].getElementsByTagName("NumberPlate"); {
try {
txt = txt + "<td><font size = 5>" + xx[0].firstChild.nodeValue + "</font></td>";
} catch (er) {
txt = txt + "<td> </td>";
}
}
xx = x[i].getElementsByTagName("statusCode"); {
try {
txt = txt + "<td><font size = 5>" + xx[0].firstChild.nodeValue + "</font></td>";
} catch (er) {
txt = txt + "<td> </td>";
}
}
txt = txt + "</tr>";
}
txt = txt + "</table>";
document.getElementById('txtCDInfo').innerHTML = txt;
} else
{
}
}
}
</script>
I see two issues. One is that you have a stray / just after the series of xmlToSend += lines, which is a syntax error, and then there's this:
var xmldoc = new ActiveXObject("Microsoft.XMLDOM");
ActiveXObject is not standard, it's an IE-specific thing. Unlike the other place you're using it, that line is not conditional.
You can just pass the xmlToSend string directly into XMLHttpRequest#send (link), you don't need to make an XML document out of it first. It'll just have to get turned back into a string again to be sent.
If you really want to actually create an XML document object, you can use DOMImplementation#createDocument (e.g., document.implementation.createDocument) on compliant browsers.
Off-topic: JavaScript libraries can make your life a bit easier in the Ajax area (and many others). Something like jQuery, Closure, Prototype, YUI, or any of several others may save you some time.

Categories

Resources