Papa parse working on chrome, not mobile - java

I have a script thats using papa parse to check for an entry in a CSV file, then redirecting based on if its there or not. It works perfectly fine in chrome on my desktop, has a few issues on firefox on my desktop, and completly doesnt work on my chrome browser on my android.
<body>
<form id="usrform">
<td><label>Unique ID</label></td>
<tr>
<td colspan="2"><input class="textBox" id="uniqueID" type="text" maxlength="30" required/></td>
</tr>
</form>
<button onclick="processClick()">Proceed</button>
</body>
<!-- Jquery import -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<!-- Papa Parse CSV -->
<script src="http://localhost/client/js/papaparse.min.js"></script>
<div id="loading" style="background:url(/images/loading.gif) no-repeat center center;width:20px;height:20px; visibility:hidden">
<img src="/images/loading.gif">
</div>
<script>
// hide loading icon
document.getElementById("loading").style.visibility = "hidden";
function processClick()
{
document.getElementById("loading").style.visibility = "visible";
if (document.getElementById("uniqueID").value == '' )
{
alert("Please fill in the uniqueID field");
document.getElementById("loading").style.visibility = "hidden";
}
else
{
parseData(**client site**/csv/csv.csv", searchArray);
}
}
function parseData(url, callBack) {
Papa.parse(url, {
download: true,
dynamicTyping: true,
complete: function(results) {
alert("parsed ready to callback");
//callBack(results.data);
}
});
}
function searchArray(data) {
//Data is usable here
console.log(" searching array");
for (a = 0; a < data.length; a++)
{
if (data[a][1] == document.getElementById('uniqueID').value)
{
// redirect
var target = "**clientsite**" + document.getElementById('uniqueID').value + ".html";
window.location.assign(target);
break;
}
else
{
console.log(" redirecting on fail");
// redirect to failure page
}
}
}
</script>
I used alerts to see where it stopped working on mobile, and it appears that the function parseData(url, callBack) { is not returning a value(whether its processing or not i cannot tell).
This works perfectly on chrome/desktop, which is the confusing part!
I imagine im missing something stupid here.

There was my error i didnt catch when uploading from testing on my local server. It was working as it could see my localhost file, but it wouldnt for anyone else!

Related

HtmlUnit: login HtmlElement when click not responding

Hi It's my first time using HtmlUnit [version 2.31], I'm trying to login to a webpage. Here is the HTML:
<body>
<div id="login">
<div id="header">
User Log In
</div>
<div id="error">Enter your credentials to login</div>
<table>
<tr>
<th>Username</th>
<td><input type="text" id="username" /></td>
</tr>
<tr>
<th>Password</th>
<td><input type="password" id="password" /></td>
</tr>
</table>
<div id="buttons">
<input type="button" value="Login" id="button" onclick="login();" />
</div>
</div>
</body>
Here is my code:
WebClient webClient = new WebClient(BrowserVersion.FIREFOX_52);
webClient.getOptions().setJavaScriptEnabled(false);
webClient.getOptions().setUseInsecureSSL(true);
try{
HtmlPage page = webClient.getPage(url);
String pageContent = page.asText();
System.out.println(pageContent);
HtmlButtonInput button = page.getFirstByXPath("//input[#type = 'button']");
//I'm new to XPath, but I think this works okay
HtmlTextInput name = (HtmlTextInput) page.getElementById("username");
HtmlPasswordInput pwd = (HtmlPasswordInput) page.getElementById("password");
System.out.println(name.getSelectedText());
name.setValueAttribute(username);
pwd.setValueAttribute(password);
System.out.println(name.getSelectedText());
HtmlPage loggedInPage = button.click();
String pageContent2 = loggedInPage.asText();
System.out.println("after logged in");
System.out.println(pageContent2);
}
Both pages (before and after login) as printed out the same. So I must did something wrong here. Any help will be appreciated.
Edit 1:
I already try Thread.sleep(2000) after feeding in username and password and before the click line
Edit 2:
js for login:
document.onkeypress = processKey;
function processKey(e) {
if (null == e)
e = window.event ;
if (e.keyCode != 13)
return;
$('button').click();
return false;
}
function parseXMLTag(tag) {
var value = '';
if (tag && tag.firstChild != undefined) {
value = tag.firstChild.nodeValue;
}
return value;
}
function login() {
new Ajax.Request('/cti/api/admin/login.xml', {
method: 'post',
parameters: {username: $('username').value, password: $('password').value},
onSuccess: function(transport) {
var response = transport.responseXML;
var success = parseXMLTag(response.firstChild.getElementsByTagName('success')[0]);
var error = parseXMLTag(response.firstChild.getElementsByTagName('error')[0]);
if (success == 1)
document.location = 'main.html';
else
$('error').innerHTML = error;
}
});
}
Because you have not posted the url you are calling, i can only provide some hints.
Even if HtmlUnit does a lot of magic behind the scenes you need a basic understanding of all the web technologies
From the code it looks like the login is done based on Ajax; this has some implications:
Ajax requires javascript enabled (HtmlUnit default)
Ajax is async - all the actions (e.g. click) in HtmlUnit are sync, this means you have to wait for the ajax call to finish
in your special case the ajax call changes the content of the page on success by reloading the page using a different url (document.location = 'main.html'). As a consequence you have to refresh your page variable
Or in code:
try (WebClient webClient = new WebClient(BrowserVersion.FIREFOX_52))
{
webClient.getOptions().setUseInsecureSSL(true);
HtmlPage page = webClient.getPage(url);
String pageContent = page.asText();
System.out.println(pageContent);
HtmlButtonInput button = page.getFirstByXPath("//input[#type = 'button']");
// to make sure you got the right element
System.out.println(button.asXml());
HtmlTextInput name = (HtmlTextInput) page.getElementById("username");
HtmlPasswordInput pwd = (HtmlPasswordInput) page.getElementById("password");
// use type() to simulate typing
name.type(username);
pwd.type(password);
// no need to get the page here because this is still the one the
// button is placed on
button.click();
// wait for ajax to do the job
webClient.waitForBackgroundJavaScript(10000);
// ok hopefully the job is done and the login was successfull
// lets get the current page out of the current window
HtmlPage loggedInPage = (HtmlPage) page.getEnclosingWindow().getTopWindow().getEnclosedPage();
...
// check the result
// you can also write this to a file and open it in a real browser
// maybe the login was failing and there is an error message
// rendered on this page
System.out.println(loggedInPage.asXml());
}
Hope that helps.
I would suggest you try setting:
webClient.getOptions().setJavaScriptEnabled(true);
webClient.getOptions().setRedirectEnabled(true);

steps for share on LinkedIn using API

I am having difficulty getting a share on LinkedIn. I am trying to post a LinkedIn share update via its Share on LinkedIn API. Does anyone can tell me how to post on linked share update and give me steps to manage it.
First you have to sign into LinkedIn Developers and create an app to get the API code specific to your application: Login Here
Then, the quickest way for you to learn is to look at some examples. Here is a working version of what you are trying to code: http://datopstech.com/linkedin-share-tool/
The only thing you NEED to change to get this code running for yourself is the API_Key found in the HTML snippet.
The source for this can be found here or, I copied and pasted relevant pieces below for reference:
$(document).ready(function(){
$("#submit_button").click(function organizeinput(){
if (IN.User.isAuthorized() == true){
var values = new Array();
//comment, title, description, image-content, image-url
// Get the parameters as an array
values = $(":input").serializeArray();
// Find and replace `content` if there
var countinput=0;
for (index = 0; index < values.length; ++index)
{
if (values[index].name == "comment" && values[index].value != "")
{
var comment;
comment = values[index].value;
countinput=countinput+1;
}
if (values[index].name == "title" && values[index].value != "")
{
var title;
title = values[index].value;
countinput=countinput+1;
}
if (values[index].name == "description" && values[index].value != "")
{
var description;
description = values[index].value;
countinput=countinput+1;
}
if (values[index].name == "image-content" && values[index].value != "")
{
var imagecontent;
imagecontent = values[index].value;
countinput=countinput+1;
}
if (values[index].name == "image-url" && values[index].value != "")
{
var imageurl;
imageurl = values[index].value;
countinput=countinput+1;
}
}
if (countinput == 5){
var postcontent = new Array();
postcontent = {"comment": comment, "content": {"title": title,"description": description,"submitted-url": imagecontent,"submitted-image-url": imageurl},"visibility": {"code": "anyone"} };
postcontent = JSON.stringify(postcontent);
shareContent(postcontent);
}
else alert("All the fields are required.");
}
else alert("You have to login to linkedin before you can post content.");
});
function onLinkedInLoad() {
IN.Event.on(IN, "auth", organizeinput);
}
// Handle the successful return from the API call
function onSuccess(data) {
console.log(data);
alert("Post Successful!");
}
// Handle an error response from the API call
function onError(error) {
console.log(error);
alert("Oh no, something went wrong. Check the console for an error log.");
}
// Use the API call wrapper to share content on LinkedIn
function shareContent(pcontent) {
IN.API.Raw("/people/~/shares?format=json")
.method("POST")
.body(pcontent)
.result(onSuccess)
.error(onError);
}
//function executepost (pcontent)
//{
//$.post("https://api.linkedin.com/v1/people/~/shares?format=json", postcontent, function() {return null;});
// Setup an event listener to make an API call once auth is complete
//}
});
/*
$.ajax({
url: "https://api.linkedin.com/v1/people/~/shares?format=json",
type: 'post',
data: postcontent,
headers: {
'Content-Type': 'application/json',
'x-li-format': 'json'
},
dataType: 'json',
success: function (data) {
console.info(data);
}
});*/
// Convert to URL-encoded string
//values = jQuery.param(values);
/*
if (crflag ==1)
{
$.post("index.php", values, function(response) {processdata(response); return response;});
}
else
{
alert("Sorry, looks like we are missing some input");
}
//$.post("db_insert.php", $(":input").serializeArray(), function(tabledata){$("#result").html(tabledata);});
*/
Status API Training Shop Blog About Pricing
© 2016 GitHub, Inc. Terms Privacy Security Contact Help
<DOCTYPE html>
<html lang="en">
<head>
<title>Linkedin Share Link With Image, Choose Picture for Hyperlink Thumbnail, JSON Post Developer, Web Tool, Without Meta Property og: tag Online</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- add jQuery -->
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<!-- add bootstrap -->
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<!-- user typed js for form -->
<script src="postscript.js"></script>
<!-- initialize LinkedIn JS SDK -->
<script type="text/javascript" src="//platform.linkedin.com/in.js">
api_key: //YOUR API KEY HERE
authorize: true
//onLoad: onLinkedInLoad
</script>
</head>
<body>
<div class="wrap">
<h1 align="center">Create An Advanced LinkedIn Post</h1>
<p align="center">Configure a share post for Linkedin. First, authorize through LinkedIn by logging in.</br> Then, fill out all of the fields below and click submit to share the content.</br></br><script type="in/Login"></script></p> <br><br>
<div class="col-md-4"><!--quick spacer :)--></div>
<div class="col-md-5">
<form name="post_content" action="" method="post">
<label for="comment">Comment: </label>
<input type="text" class="form-control" name="comment" placeholder="Comment" required></input><br>
<label for="title">Title: </label>
<input type="text" class="form-control" name="title" placeholder="Title" required></input><br>
<label for="description">Description: </label>
<input type="text" class="form-control" name="description" placeholder="Description" required></input><br>
<label for="image-content">Link to Content: </label>
<input type="text" class="form-control" name="image-content" placeholder="http://example.com/content" required></input><br>
<label for="image-location">Image Location: </label>
<input type="text" class="form-control" name="image-url" placeholder="http://example.com/images/example.jpg" required></input><br><br>
<input type="button" id="submit_button" value="Submit" class="btn btn-default"></input>
</form>
</div>
</div>
</div>
<div id="VINoutput"></div>
</body>
</html>
Just use a URL like this...
https://www.linkedin.com/sharing/share-offsite/?url={url}
Source: Microsoft LinkedIn Share URL Documentation.
For example, this works for me:
https://www.linkedin.com/sharing/share-offsite/?url=http://www.wikipedia.org/
Demonstration:

AJAX with image button

I have tried different combinations of input type but how am I able to input a message without messing up the image? The purpose was to update the table without refreshing the page. To be more specific, when I clicked the image it should update the table on the side of the page. For many of the tutorial out there I saw people only use for onclick to call the ajax functions. Is there a good example for what I can do for the image button instead of the plain button?
For example:
<form name="bakery" action="TestMartController" method="post" >
<input type="hidden" name="action" value="dairy">
<input type="image" src="<%=request.getContextPath()%>/css/categories/dairy.jpg" onclick="loadXMLDoc">
The table I want to update is
<div id="refresh">
<table class="rightTable" border="1" width="70%">
<tr>
<th>Photo</th>
<th>Product and Description</th>
<th>Price</th>
<th>Orders</th>
<th>Quantity</th>
<th>Edit Quantity</th>
<th>Add Item </th>
</tr>
<c:forEach var="b" items="${bakery}">
...
</c:forEach>
</table>
</div>
Javascript file
function loadXMLDoc()
{
var xmlhttp;
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 = function() {
if (xmlhttp.readyState == 4 ) {
if(xmlhttp.status == 200){
document.getElementById("refresh").innerHTML = xmlhttp.responseText;
}
else if(xmlhttp.status == 400) {
alert('There was an error 400');
}
else {
alert('something else other than 200 was returned');
}
}
};
xmlhttp.open("POST", "bakery.jsp", true);
xmlhttp.send();
}
First of all you want a ajax call which makes post to a service and get datas and update your table.
I suggest to you learn how to use jquery and ajax call.
1- In your html define call method. Don't use form!
<img src="yourImage.jpg" onclick="getSomeData()">
2- Make post or get call to your service with jquery. And get Data.
function getSomeData(){
var url = "http://url";
$.post(url,{data:data})
.done(function(data){
//this data is your call result.
//do something
updateTable(data);
})
.fail(function(){
console.log('fail');
});
}
3- Create your gui function to change table.
function updateTable(){
//update your htmls
}

UI Bootstrap (AngularJS) modal is not working

I have this practice project that I am working on, but I cant get my UI Boostratp modal working. Using example from the site https://github.com/angular-ui/bootstrap/tree/master/src/modal I have been trying to implement this feature but without success.
I believe that this is because of that I do not have the knowledge to integrate demo code to my MVC style project (I have separate app.js, controller, and service files), and this one file example is rather confusing to me.
My folder/file structure:
Now, I have tried various things, including making a separate controller, and separate view for modal content (that's why I have bookDetailes.html and bookDetailesConreoller.js files but they are currently out of order - not connected in app.js's stat provider and their code is under comment). This is where I am:
A have a list of basic book details retrieved from data base and printed out in book.html view via data-ng-repeat. In every repeat I have an Action button that is supposed to open modal for editing or deleting that entry.
Here is my book.html file where I have nested the demo markup code from UI Bootsratp site:
<h4 class="text-center"><strong>Book Collection</strong></h4>
<br>
<table class="table table-hover">
<thead>
<tr>
<th>ID</th>
<th>Image</th>
<th>Title</th>
<th>Author</th>
<th>Year</th>
<th>Publisher</th>
<th>City of Publishing</th>
<th>Genre</th>
<th>Action
<th>
</tr>
</thead>
<tbody data-ng-init="init()">
<tr data-ng-repeat="book in books">
<td>{{book.id}}</td>
<td>{{book.image}}</td>
<td>{{book.title}}</td>
<td>{{book.author}}</td>
<td>{{book.yearOfPublishing}}</td>
<td>{{book.publisher}}</td>
<td>{{book.cityOfPublishing}}</td>
<td>{{book.genre}}</td>
<td><a class="btn btn-default" data-toggle="modal" data-ng-click="open()">Action</a></td>
</tr>
</tbody>
</table>
<div>
<script type="text/ng-template" id="myModalContent.html">
<div class="modal-header">
<h3 class="modal-title">I'm a modal!</h3>
</div>
<div class="modal-body">
<ul>
<li ng-repeat="item in items">
<a ng-click="selected.item = item">{{ item }}</a>
</li>
</ul>
Selected: <b>{{ selected.item }}</b>
</div>
<div class="modal-footer">
<button class="btn btn-primary" ng-click="ok()">OK</button>
<button class="btn btn-warning" ng-click="cancel()">Cancel</button>
</div>
</script>
</div>
As you can see, this last part after table tag is supposed to be modal markup taht is called when Action button is pressed and command "open()" i passed to bookController.js via data-ng-click.
My bookControler.js:
collectionsApp.controller('bookController', function($scope, bookService,
$state) {
var books = [];
$scope.save = function() {
bookService.save($scope.book, onSaveDelete);
}
$scope._delete = function(id) {
for (book in books) {
if (book.id === id) {
bookService._delete(book, onSaveDelete);
}
}
}
$scope.edit = function(id) {
for (book in books) {
if (book.id === id) {
$scope.book;
}
}
}
$scope.init = function() {
bookService.list(onInit);
}
// <-- Beginning of the modal controller code I inserted (and adopted) from the example:
$scope.items = [ 'item1', 'item2', 'item3' ];
$scope.open = function(size) {
modalInstance = $modal.open({
templateUrl : 'myModalContent.html',
controller : ModalInstanceCtrl,
size : size,
resolve : {
items : function() {
return $scope.items;
}
}
});
modalInstance.result.then(function(selectedItem) {
$scope.selected = selectedItem;
}, function() {
$log.info('Modal dismissed at: ' + new Date());
});
};
var ModalInstanceCtrl = function($scope, $modalInstance, items) {
$scope.items = items;
$scope.selected = {
item : $scope.items[0]
};
$scope.ok = function() {
$modalInstance.close($scope.selected.item);
};
$scope.cancel = function() {
$modalInstance.dismiss('cancel');
};
};
// <-- Ending of the modal code I have inserted from the example.
onSaveDelete = function(response) {
if (response.data.status === 'success') {
$scope.init();
} else {
alert("DEBUG ALERT: SAVE/DELETE FAIL");
}
};
onInit = function(response) {
$scope.books = response.data;
books = response.data;
};
});
Now, like this, code is working in the seance that data-ng-repeat is working and I get list of database entries on page load. But when I click on the Action button i get this error message in the console:
But when I add $modal to may code like this:
collectionsApp.controller('bookController', function($scope, bookService,
$state, $modal) {
var books = [];
...
I get this error on page load:
Can someone help me understand and implement modals to my project? Thanks in advance... ;)
Add this,
angular.module('Urapp', ['ui.bootstrap']);

Protocol Not Supported (Android)

I am trying to develop application in phone gap.It monitors server jobs. Currently server is not available so I made my system as server. I put project files in the same directory where my server is installed. I am trying to access my files in main activity. But it is showing error on my emulator. Error heading is Protocol not Supported. I am sharing main activity file and html file below. Please look at these files.
Main Activity File:
package com.example.productionmonitor;
import org.apache.cordova.DroidGap;
import android.os.Bundle;
import android.view.Menu;
public class MainActivity extends DroidGap{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
System.out.println("Here");
super.setIntegerProperty("loadUrlTimeoutValue",120000);
super.loadUrl("file////C:/Program Files/Elixir Technologies/Tango/tomcat/webapps/productionmanagerserver/Monitor app/productionMonitor.htm");
//super.loadUrl("file:///android_asset/www/productionMonitor.htm");
//super.loadUrl("C:///|\Program Files\/Elixir Technologies\/Tango\tomcat\webapps\productionmanagerserver\Monitor app\productionMonitor.htm");
//super.loadUrl("http:///localhost:8080/productionmanagerserver/productionMonitor.htm");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
This is that html file which I saved in location(C:\Program Files\Elixir Technologies\Tango\tomcat\webapps\productionmanagerserver\Monitor app\login.html) and I want to access this file.
<!doctype html>
<html lang="en-US">
<head>
<meta charset="utf-8">
<title>Login</title>
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Varela+Round">
<link rel="stylesheet" href="./files/login.css">
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<script>
var strFile ;
function userLogin()
{
window.location.href = "productionMonitor.htm";
}
function init()
{
var xmlhttp = null ;
try {
xmlhttp = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
xmlhttp = new ActiveXObject("MsXML2.XMLHTTP");
} catch (othermicrosoft) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
xmlhttp = null;
}
}
}
if (xmlhttp == null)
alert("Error creating request object!");
if ("withCredentials" in xmlhttp) {
// Check if the XMLHttpRequest object has a "withCredentials" property.
// "withCredentials" only exists on XMLHTTPRequest2 objects.
//xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// Otherwise, check if XDomainRequest.
// XDomainRequest only exists in IE, and is IE's way of making CORS requests.
xmlhttp = new XDomainRequest();
}
return xmlhttp ;
}
function CallWebservice()
{
var req = init() ;
var url ="http://localhost:8080/identityserver/domains/allData";
req.open('GET',url,true);
req.send(null);
req.onreadystatechange = function() {
if (req.readyState != 4) return; // Not there yet
if (req.status != 200) {
// Handle request failure here...
alert("Call failed");
return;
}
// Request successful, read the response
strFile = req.responseText ;
parseDomainList(strFile);
}
}
function parseDomainList(dlist)
{
var xmlDoc = new DOMParser().parseFromString(strFile,'text/xml');
var domain = xmlDoc.getElementsByTagName("domain");
for (i=0;i<domain.length;i++)
{
var dname =domain[i].getElementsByTagName("domain_name");
var domainid = document.getElementById("domain") ;
var option=document.createElement("option");
domainid.appendChild(option);
}
alert(strFile) ;
userLogin() ;
}
</script>
</head>
<body>
<div id="login">
<h2><span class="fontawesome-lock"></span>Sign In</h2>
<form action="javascript:void(0);" method="POST">
<fieldset>
<p><label for="email">User Name</label></p>
<p><input type="email" id="email" value="admin" onBlur="if(this.value=='')this.value='admin'" onFocus="if(admin')this.value=''"></p>
<p><label for="password">Password</label></p>
<p><input type="password" id="password" value="admin" onBlur="if(this.value=='')this.value='admin'" onFocus="if(this.value=='admin')this.value=''"></p>
<p><label for="domain">Domain List</label></p>
<p><select type="domain" id="domain"> </select> </p>
<p><input type="submit" value="Sign In" onclick="CallWebservice()"></p>
</fieldset>
</form>
</div> <!-- end login -->
</body>
</html>
It really doesn't matter where you put the files on your windows machine. Neither your android device, nor the Emulator can never access them. That'd be scary, if you think about it.
You'll need to turn your development machine into a proper server and then access it with the special ip address 10.0.2.2 from the emulator, which is the development machine's loopback. If you're testing on a device, you'll need to access the development machine's local IP address, presuming you're on the same LAN.

Categories