pass variable by jquery mobile from page to page - javascript

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

Related

Fetching new JSON data each time Javascript function is called

I have a Java REST API, with some JSOn data, that I'm working with, in javascript.
I have two methods one to show data, and when to add new data:
so I have added an EventListener to my first bata to submit data:
btn.addEventListener("click", function() {
var request = new XMLHttpRequest();
request.open('GET', 'http://localhost:8084/RestandJson/api/Person');
request.onload = function(){
var data = JSON.parse(request.responseText);
addPerson(data);
};
request.send();
});
with the addPerson method like this:
const addPerson = (data) => {
var fName = document.getElementById("fname").value;
var lName = document.getElementById("lname").value;
var age = document.getElementById("age").value;
var id = data[data.length-1].id +1;
const person = {fName, lName, age, id};
data.push(person);
console.log(person);
for(i = 0; i< data.length; i++){
console.log(data[i]);
}
}
the problem is, that new data is generated for each GET request, so I only want to fetch the data once, and save that in an array, and then add new persons from there on.
I have a method to show the JSON data as well after converting it into objects:
I added an event listener to another button like before where I'm calling this method:
render HTML = (data) => {
let htmlString = "";
for(i = 0; i < data.length; i++){
htmlString += "<p> " + data[i].fName +" " + " " + data[i].lName + " " + data[i].age + " " + data[i].id + "</p>"
}
root.insertAdjacentHTML('beforeend', htmlString);
}
//bind click event on button to add person info
addPersonbtn.addEventListener('click', function() {
addPerson();
});
// fetch all person data from api (call this function when app load)
function getPersonList() {
var request = new XMLHttpRequest();
request.open('GET', 'http://localhost:8084/RestandJson/api/Person');
request.onload = function(){
var data = JSON.parse(request.responseText);
renderHTML(data);
};
request.send();
}
function postPersonData(personInfo) {
// your api to add single persion info
// on success call getPersonList(), it will update the list
}
const addPerson = () => {
var fName = document.getElementById("fname").value;
var lName = document.getElementById("lname").value;
var age = document.getElementById("age").value;
//var id = data[data.length-1].id +1; // handle it on db side, Primary key, auto generation
const person = {fName, lName, age};
postPersonData(person);
}
renderHTML = (data) => {
let htmlString = "";
for(i = 0; i < data.length; i++){
htmlString += "<p> " + data[i].fName +" " + " " + data[i].lName + " " + data[i].age + " " + data[i].id + "</p>"
}
root.insertAdjacentHTML('beforeend', htmlString);
}
i have made pseudo code for you , hope it will helps you a little bit

Multiple JSON files in one request from Javascript

I have two different codes for two different URL to fetch data. Code is as below :
Code 1 :
<script language="javascript" type="text/javascript">
var xmlHttp;
function parseBoolean(value) {
return (typeof value === "undefined") ? false : value.replace(/^\s+|\s+$/g, "").toLowerCase() === "true";
}
function createXMLHttpRequest(){
if(window.ActiveXObject){
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if(window.XMLHttpRequest){
xmlHttp = new XMLHttpRequest();
}
}
function call_post(){
createXMLHttpRequest();
var vosRequest = new Object();
vosRequest.accounts = new Array(1);
vosRequest.accounts[0] = new Object();
vosRequest.accounts[0] = document.getElementById("accounts").value;
xmlHttp.open("POST", "http://..../GetCustomer", true);
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
xmlHttp.onreadystatechange = showResult;
xmlHttp.send(JSON.stringify(vosRequest));
document.getElementById("postText").innerHTML = "<br>Request Format: " + JSON.stringify(vosRequest) + "</br>";
document.getElementById("responseText").innerHTML = "";
}
function showResult(){
if(xmlHttp.readyState == 4){
if(xmlHttp.status == 200){
document.getElementById("responseText").innerHTML = "<br>Response Format: " + xmlHttp.responseText + "</br>";
document.body.scrollTop=document.body.scrollHeight;
var json = JSON.parse(xmlHttp.responseText);
document.getElementById('id01').innerHTML = json.infoCustomers[0].infoCustomerAdditional.linkMan;
document.getElementById('id02').innerHTML = json.infoCustomers[0].account;
document.getElementById('id03').innerHTML = json.infoCustomers[0].name;
var num = json.infoCustomers[0].money;
var n = num.toFixed(3);
document.getElementById('id04').innerHTML = n;
var d = new Date(json.infoCustomers[0].validTime);
d = d.toGMTString();
document.getElementById('id05').innerHTML = d;
}
}
}
</script>
Code 2:
<script language="javascript" type="text/javascript">
var xmlHttp;
function parseBoolean(value) {
return (typeof value === "undefined") ? false : value.replace(/^\s+|\s+$/g, "").toLowerCase() === "true";
}
function createXMLHttpRequest(){
if(window.ActiveXObject){
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if(window.XMLHttpRequest){
xmlHttp = new XMLHttpRequest();
}
}
function call_post(){
createXMLHttpRequest();
var vosRequest = new Object();
if(document.getElementById("checkbox_account").checked){
vosRequest.account = document.getElementById("account").value;
}
if(document.getElementById("checkbox_areaCode").checked){
vosRequest.areaCode = document.getElementById("areaCode").value;
}
if(document.getElementById("checkbox_period").checked){
vosRequest.period = parseFloat(document.getElementById("period").value);
}
if(document.getElementById("checkbox_beginTime").checked){
vosRequest.beginTime = document.getElementById("beginTime").value;
}
if(document.getElementById("checkbox_endTime").checked){
vosRequest.endTime = document.getElementById("endTime").value;
}
xmlHttp.open("POST", "http://.../GetReportCustomerLocationFee", true);
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
xmlHttp.onreadystatechange = showResult;
xmlHttp.send(JSON.stringify(vosRequest));
document.getElementById("postText").innerHTML = "<br>Request Format: " + JSON.stringify(vosRequest) + "</br>";
document.getElementById("responseText").innerHTML = "";
}
function showResult(){
if(xmlHttp.readyState == 4){
if(xmlHttp.status == 200){
document.getElementById("responseText").innerHTML = "<br>Response Format: " + xmlHttp.responseText + "</br>";
document.body.scrollTop=document.body.scrollHeight;
var obj, dbParam, xmlhttp, myObj, x, txt = "";
var json = JSON.parse(xmlHttp.responseText);
//txt += ""
for (x=0;x<json.infoReportCustomerLocationFees.length;x++) {
txt += "<tr><td>" + json.infoReportCustomerLocationFees[x].areaCode + "</td>";
txt += "<td>" + json.infoReportCustomerLocationFees[x].areaName + "</td>";
json.infoReportCustomerLocationFees[x].totalFee = json.infoReportCustomerLocationFees[x].totalFee.toFixed(3);
txt += "<td>" + json.infoReportCustomerLocationFees[x].totalFee + "</td>";
txt += "<td>" + json.infoReportCustomerLocationFees[x].totalTime + "</td>";
txt += "<td>" + json.infoReportCustomerLocationFees[x].totalSuiteFee + "</td>";
txt += "<td>" + json.infoReportCustomerLocationFees[x].totalSuiteFeeTime + "</tr></td>";
}
// txt += "</table>"
document.getElementById("demo1").innerHTML = txt;
}
}
}
function load(){
document.getElementById("account").value = "ABC";
document.getElementById("areaCode").value = "1";
document.getElementById("period").value = "7";
document.getElementById("beginTime").value = "20170828";
document.getElementById("endTime").value = "20170903";
}
</script>
Both the codes are in two different html files and as an individual, both runs fine and fetches data.
I want to fetch the data of both the url in one html, i.e. I want to merge both the files and retreive data of both the request in single HTML file.
Can u suggest how can i do it? I have searched on stackoverflow but not able to find the right solution.
Thanks in advance.

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:

Angularjs [Ionic] error open file from copy to device

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.

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