I am trying to get the dates when available on this datepicker
When availables , the dates are saved in the variable available_dates inside a js script which fills the html input.
HTML of the input :
<input type="text" readonly="" class="form-control-input app_date validate" style="width: 260px;" id="app_date" name="app_date" placeholder="YYYY-MM-DD" onchange="this.form.submit();showLoader();" value="" autocomplete="off">
How can i retrieve the values from available_dates when the dates are availables, get them to my python script to select one of them.
The following python script didn't work :
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
driver.find_element(By.XPATH, "//*[#id='app_date']").click()
time.sleep(3)
try:
print([date.get_attribute("innerHTML") for date in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//div[#class='datepicker-days']/table[#class=' table-condensed']//tr//td[#class='day activeClass' and #title='Book']")))])
except TimeoutException:
print("No booking dates available for the current month")
driver.refresh()
JS script :
<script type="text/javascript" xpath="1">
var today = new Date();
var dd = today.getDate()+1;
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10){
dd='0'+dd
}
if(mm<10){
mm='0'+mm
}
var today = yyyy+'-'+mm+'-'+dd;
function formatDate(rawDate) {
var day = ("0" + rawDate.getDate()).slice(-2);
var month = ("0" + (rawDate.getMonth() + 1)).slice(-2);
return (day)+ "-" + (month)+ "-" +rawDate.getFullYear() ;
}
$(document).ready(function() {
var dt1 = '2023-02-14';
var checkService = 'Normal';
$('.date_of_birth').datepicker({
format: "yyyy-mm-dd",
endDate: new Date(dt1),
startDate: '-100y',
autoclose: true,
startView: 2
});
$('.pptIssueDate').datepicker({
format: "yyyy-mm-dd",
endDate: new Date(dt1),
startDate: '-100y',
autoclose: true,
startView: 2
});
$('.passport_validate_till').datepicker({
format: "yyyy-mm-dd",
startDate: new Date(dt1),
autoclose: true,
startView: 2
});
var dt4 = '2023-02-15';
var blocked_dates = ["01-01-2023","02-01-2023","06-01-2023","13-01-2023","20-01-2023","27-01-2023","03-02-2023","10-02-2023","17-02-2023","24-02-2023","01-01-2023","02-01-2023","06-01-2023","13-01-2023","20-01-2023","27-01-2023","03-02-2023","10-02-2023","17-02-2023","24-02-2023"];
var available_dates = [];
var fullCapicity_dates = ["15-02-2023","16-02-2023","20-02-2023","21-02-2023","22-02-2023","23-02-2023","27-02-2023","28-02-2023"];
var offDates_dates = ["17-02-2023","18-02-2023","19-02-2023","24-02-2023","25-02-2023","26-02-2023"];
var allowArray = [1,2];
if(checkService == 'Normal')
{
/*if((jQuery.inArray(2, allowArray)!='-1') || (jQuery.inArray(3, allowArray)!='-1') || (jQuery.inArray(4, allowArray)!='-1'))
{
var classFull = 'fullcapspecial';
var tooltipTitle = ' ';
var backDatetitle = 'Not Allowed';
}else{
var classFull = 'fullcap';
var tooltipTitle = 'Slots Full';
var backDatetitle = 'Not Allowed';
}*/
var classFull = 'fullcap';
var tooltipTitle = 'Slots Full';
var backDatetitle = 'Not Allowed';
}else{
var classFull = 'fullcap';
var tooltipTitle = 'Slots Full';
var backDatetitle = 'Not Allowed';
}
$('.app_date').datepicker({
language: "en",
Default: true,
format: "yyyy-mm-dd",
startDate: new Date(dt4),
endDate: '2023-02-28',
autoclose: true,
forceParse:true,
startView: 0,
beforeShowDay: function(date){
var formattedDate = formatDate(date);
if ($.inArray(formattedDate.toString(), blocked_dates) != -1){
return {
enabled : false,
classes: 'inactiveClass',
tooltip: 'Holiday'
};
}
if ($.inArray(formattedDate.toString(), available_dates) != -1){
return {
enabled : true,
classes: 'activeClass',
tooltip: 'Book'
};
}
if ($.inArray(formattedDate.toString(), fullCapicity_dates) != -1){
return {
enabled : false,
classes: classFull,
tooltip: tooltipTitle
};
}
if ($.inArray(formattedDate.toString(), offDates_dates) != -1){
return {
enabled : false,
classes: 'offday',
tooltip: 'Off Day'
};
}
return {
enabled : false,
tooltip: backDatetitle
};
return;
}
});
/*====== CALL POP FOR PL/PT IN NORMAL CASE=======*/
if(checkService == 'Normal')
{
if((jQuery.inArray(2, allowArray)!='-1') || (jQuery.inArray(3, allowArray)!='-1') || (jQuery.inArray(4, allowArray)!='-1'))
{
/*$(document).on('click', '.fullcap,.fullcapspecial', function () {
$(".datepicker").hide();
$('.popupBG').show();
$('#IDBodyPanel').show();
});
$(".popupCloseIcon").click(function() {
$(".popupBG").hide();
$("#IDBodyPanel").hide();
});*/
/*$('input[type=radio][name=serviceChange]').change(function() {
if (this.value == 'Premium') {
$("#premiumService").prop('value', 'GO FOR PREMIUM');
}
else if (this.value == 'Prime') {
$("#premiumService").prop('value', 'GO FOR PRIME TIME');
}
});*/
}
}
/*====== CALL POP FOR PL/PT IN NORMAL CASE=======*/
var eventhandler = function(e) {
e.preventDefault();
}
if (checkService == 'Premium' || checkService == 'Prime' || checkService == 'Premium-Saturday') {
$('input[name="vasId[]"]:checked').each(function() {
$("#vasId"+this.value).bind('click', eventhandler);
});
}
if (checkService != 'Premium')
{
$(document).on('click', '.chkbox', function () {
if($(this).val() == 1)
{
if($(this).is(":checked")){
//$("#vasId6").prop('checked', true);
//$("#vasId6").bind('click', eventhandler);
}else{
//$("#vasId6").prop('checked', false);
//$("#vasId6").unbind('click', eventhandler);
}
}
});
}
});
</script>
Solved
Related
ive been trying to login with the following code in a chinese monitoring system that uses js forms.
i assume i cannot log in because the payload is encrypted with a public key and posted to a randomly generated URL.
import sys, re, requests
class GMU:
def __init__(self):
payload = {'inputAccount': 'admin','inputPassword': 'admin'}
s = requests.Session()
p = s.post('http://10.40.100.146/',data=payload)
self.p = p
r = s.get('http://10.40.100.146/ActiveSignal/ActiveSignalPartial?equipmentId=300001003')
data = str(r.content)
self.data = data
def ask():
return GMU()
n = ask()
print(n.p)
print(n.data)
Here is a post header
Payload
Initiator
looking in the initatior section "send" i found loginname.js with the following code:
var publicKey = "-----BEGIN PUBLIC KEY-----MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC6MqYui/VMzy0qQE2c6S24fNbph7Hr/Nh29aJJ0kWjINV3zPgJXZrmJp43PaQBxHkq3cESuSf9zUCBS0wZtvFL8LTU1Iehnh/rPVKfGHQaHoD928n7CXuGwnEsyl63p6wwgIjiENVTMaReCJz79N2fhXFK99cA1/B7JXRtCPr/pwIDAQAB-----END PUBLIC KEY-----";
var clientMenuTemplateType = 4;
function logout() {
BootstrapDialog.show({
title: lang["Exit the confirmation"],
message: lang["Quit or not?"],
cssClass: 'user-dialog',
buttons: [{
label: lang["Confirm"],
cssClass: 'btn blue btn-outline dropdown-toggle',
action: function () {
//执行操作
location.href = '.././Account/Logout';
}
}, {
label: lang["Cancel"],
action: function (dialog) {
dialog.close();
}
}]
});
}
$("#loginBtn").click(function () {
Login();
});
$('#inputPassword').bind('keyup', function (event) {
if (event.keyCode == "13") {
//回车执行
Login();
}
});
$('#inputAccount').bind('keyup', function (event) {
if (event.keyCode == "13") {
//回车执行
Login();
}
});
$('#loginBtn').bind('keyup', function (event) {
if (event.keyCode == "13") {
//回车执行
Login();
}
});
var flag = 0;
$("#pswdVisual").click(function () {
var input = document.getElementById('inputPassword');
if (flag == 0) {
input.type = 'text';
$("#pswdVisual").addClass("glyphicon-eye-open");
$("#pswdVisual").removeClass("glyphicon-eye-close");
flag = 1;
} else {
input.type = 'password';
$("#pswdVisual").addClass("glyphicon-eye-close");
$("#pswdVisual").removeClass("glyphicon-eye-open");
flag = 0;
}
});
function Login() {
var options = {
positionClass: 'toast-bottom-right'
}
var account = $('#inputAccount').val();
var password = $('#inputPassword').val();
if (!account || account == null || account === "") {
toastr.error(lang["Username cannot be empty!"], lang["login failure"], options);
} else if (!password || password == null || password === "") {
toastr.error(lang["Password cannot be empty!"], lang["login failure"], options);
} else {
var data = account + "&" + password;
//RSA Encrypt
var jsEncrypt = new JSEncrypt();
jsEncrypt.setPublicKey(publicKey);
var key = jsEncrypt.encrypt(data);
$.ajax({
type: "post",
url: currentUrl + "Account/LoginAction/?t=" + Math.random(),
data: {
encryptContext: key
},
dataType: "json",
success: function (response) {
if (response != null) {
if (response.url !== "") {
cookieObject.setCookie("userName", account);
if (response.url.indexOf("Default/Default?ZT=") !== -1) {
location.href = currentUrl + "Default/Default#ZT=" + response.url.replace("Default/Default?ZT=", "");
} else {
location.href = currentUrl + "Default/Default#Page=" + response.url;
}
}
else if (response.error !== "")
console.log(response.error);
else if (response.show !== "") {
if (response.show == lang["The user name does not exist"]) {
toastr.error("", lang["login failure"], options);
} else {
toastr.error(response.show, lang["login failure"], options);
}
}
}
},
error: function () {
}
});
}
};
i dont know if should be passing the rsa encrypted payload or there is some way to just provide the user and password and let the js thing generate itself.
global:
import re
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from patterns import PATTERNS
PATTERNS = {
'select_list': {
'click': r'javascript.*[0-9]+.*\s.*[0-9]+.*\s.*{}.*;',
'select_list_views': r'/Integration/chooselist/{}'
},
login: {"..."}
}
driver = webdriver.Firefox()
driver.get(r"login_uri")
This section directs to targeted page,
views(PATTERNS['login']) # func performs login
list_name = r'ABC TEXT.COM'
pk = 1234
# get lists_views
lists_href = r'//a[#href="{}"]'.format(PATTERNS['select_list']['select_list_views'].format(pk))
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, lists_href))).click()
source = driver.page_source # page source HTML
then element_href is to be parsed from: source = driver.page_source,
using flag list_name
element_href = '//a[#href="{}".format(re.findall(r'javascript.*[0-9]+.*\s.*[0-9]+.*\s.*{}.*;'.format(list_name), source)[0])
will relove to :
'//a[#href="javascript:postSelect("123", "1234", "ABC TEXT.COM");"]'
which is slightly different than inspected one,
seems that a JS function reformats the link, i don't know when exactly.
element's link from inspection:
Select
finally when i try to select element by XPATH:
try:
element_href = r'//a[#href="{}"]'.format(re.findall(PATTERNS['select_list']['click'].format(list_name), source)[0])
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, element_href))).click()
except IndexError:
print("could not parse link")
i was able to click the element by selecting it with XPATH copied from Firefox:
driver.find_element(By.XPATH, '/html/body/div[2]/div/div[4]/table/tbody/tr[104]/td[3]/a').click()
The only problem with copied XPATH, there is no dynamic way to map it to list_name since 104 != 123
scripts in html_source:
<div style="float: none; clear: both;"></div>
</div>
<script data-cfasync="false" src="/cdn-cgi/scripts/5c5dd728/cloudflare-static/email-decode.min.js"></script><script src="https://some_url/jquery-ui-1.10.3.custom.min.js"></script>
<script src="https://some_url/jquery.ui.touch-punch.min.js"></script>
<script src="https://some_url/js/bootstrap.min.js"></script>
<script src="https://some_url/bootstrap-select.js"></script>
<script src="https://some_url/bootstrap-switch.js"></script>
<script src="https://some_url/flatui-checkbox.js"></script>
<script src="https://some_url/flatui-radio.js"></script>
<script src="https://some_url/jquery.tagsinput.js"></script>
<script src="https://some_url/jquery.placeholder.js"></script>
<script src="https://some_url/jquery.fancybox.min.js"></script>
<script type="text/javascript">
function ShowLoadingAJAX() {
$('body').addClass("loading");
}
function HideLoadingAJAX() {
$('body').removeClass("loading");
}
function DisplaySuccessMessage(msg) {
$('#alert_danger').hide();
$('#alert_info').hide();
$('#alert_success_message').html(msg);
$('#alert_success').show();
}
function AppendSuccessMessage(msg) {
$('#alert_danger').hide();
$('#alert_info').hide();
$('#alert_success_message').html($('#alert_success_message').html() + '<br/> → ' + msg);
$('#alert_success').show();
}
function DisplayErrorMessage(msg) {
$('#alert_success').hide();
$('#alert_info').hide();
$('#alert_danger_message').html(msg);
$('#alert_danger').show();
}
function DisplayInfoMessage(msg) {
$('#alert_danger').hide();
$('#alert_success').hide();
$('#alert_info_message').html(msg);
$('#alert_info').show();
}
function HideSuccessMessage() {
$('#alert_success_message').html('');
$('#alert_success').hide();
}
function HideErrorMessage() {
$('#alert_danger_message').html('');
$('#alert_danger').hide();
}
function HideInfoMessage() {
$('#alert_info_message').html('');
$('#alert_info').hide();
}
function loginAsSuperUser(id) {
$('#SuperLoginAsUserID').val(id);
$('#superLoginForm').submit();
}
$(document).ready(function () {
$('#some_string_body').css('display', 'block');
var tooltipOptions = { placement: 'right' };
$('.some_string_tooltip').tooltip(tooltipOptions);
var popoverOptions = { placement: 'right' };
$('.some_string_popover').popover(popoverOptions);
$('#alert_success_close_button').click(function (e) {
e.preventDefault();
$('#alert_success_message').html('');
$('#alert_success').hide();
});
$('#alert_danger_close_button').click(function (e) {
e.preventDefault();
$('#alert_danger_message').html('');
$('#alert_danger').hide();
});
$('#alert_info_close_button').click(function (e) {
e.preventDefault();
$('#alert_info_message').html('');
$('#alert_info').hide();
});
});
</script>
<script>
var href_parts = window.location.href.split('/');
var lastFancyboxHeight = 0;
var fancyDocReady = false;
var fancyRefreshParent = false;
function escapeHtml(unsafe) {
return unsafe
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
function getFancyboxY(id) {
var bs = $('#' + id + '-box-statement');
if (bs.length && bs.offset() && bs.offset().top) {
return (bs.offset().top + 'px');
} else {
return '200px';
}
}
function showActivityLog() {
var href_iframe_url = href_parts[0] + '//' + href_parts[2] + '/Activity/Recent';
//$('#fancy-styler').html('.fancy-styler-top { top: ' + getFancyboxY(id) + ' !important; }');
$.fancybox({
type: 'iframe',
href: href_iframe_url,
scrolling: 'no',
padding: 0,
openEffect: 'none',
closeEffect: 'none',
closeClick: false,
nextClick: false,
autoResize: false,
autoHeight: false,
autoSize: false,
autoCenter: true,
fitToView: false,
//fixed: false,
width: 1160,
height: 900,
tpl: {
closeBtn: '<div style="position: absolute; top: -22px; left: 0px; z-index: 8040; height: 28px; line-height: 30px; background-color: #428bca; color: #fff; cursor: pointer; font-size: 14px; font-weight: bold; padding-left: 12px; padding-right: 12px; border-top-right-radius: 6px; border-top-left-radius: 6px;">Recent Activity</div>'
},
afterClose: function () {
},
beforeShow: function () {
//$(".fancybox-wrap").addClass("fancy-condition-editor-2");
$(".fancybox-wrap").addClass("fancy-styler-top-2");
}
});
}
function getActivitiesColorAjax() {
NumProfileActivityChecks++;
if ($('#__AjaxAntiForgeryForm input[name=__RequestVerificationToken]').length) {
$.ajaxSetup({ cache: false });
var dataPost = {
__RequestVerificationToken: $('#__AjaxAntiForgeryForm input[name=__RequestVerificationToken]').val(),
p1: "a",
p2: "b"
};
$.post("/Activity/PostColorAjax", dataPost, function (data) {
if (!data.color || data.color === 'green') {
//$('#profile-name-icon').css('color', '#1abc9c');
$('#profile-name-icon').css('color', OriginalProfileNameIconColor);
} else {
$('#profile-name-icon').css('color', '#e74c3c');
}
//console.log('PostColorAjax (' + NumProfileActivityChecks + '): ' + data.color);
if (NumProfileActivityChecks <= 10) {
//for the first 10 minutes, check every 60 seconds.
setTimeout(getActivitiesColorAjax, 60000);
} else if (NumProfileActivityChecks <= 120) {
//for the first 120 minutes, check every 120 seconds.
setTimeout(getActivitiesColorAjax, 120000);
} else {
//after 120 minutes, start checking with exponential backoff.
//120 + (NumProfileActivityChecks - 120) * 2
var tot = 1000 * (120 + Math.pow((NumProfileActivityChecks - 120), 2));
setTimeout(getActivitiesColorAjax, tot);
}
});
}
}
</script>
<script type="text/javascript">
$(document).ready(
function () {
//$('a[rel="popover"]').popover({placement: 'bottom'});
//$('#settings_general_mc_api_key_error').addClass('alert-error error');
}
);
function postSelect(id, connectionID, ListName)
{
$("#ID").val(id.toString());
$("#IntegrationID").val(connectionID);
$("#ListName").val(ListName);
$("#emChooseListForm").submit();
}
</script>
</body>
</html>
Although link is matched from the page source code directly,
driver can't locate element and simply timesout..
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, element_href))).click()
Traceback (most recent call last):
File "<ipython-input-53-7a3495af695d>", line 1, in <module>
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, element_href))).click()
File "c:\python\python37\lib\site-packages\selenium\webdriver\support\wait.py", line 80, in until
raise TimeoutException(message, screen, stacktrace)
TimeoutException
Please tolerate my description if it is poor, this is my first post on stackoverflow,
Thanks
I am trying to scrape a web page with dynamic javascript loading using selenium, but the table that I want to scrape is never actually loading in the source and is instead just showing javascript. The code I am trying to run is the following:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium import webdriver
from bs4 import BeautifulSoup
url = ""
browser = webdriver.Firefox(executable_path=r'/Users/brendanbernstein/Downloads/geckodriver')
browser.get(url)
WebDriverWait(browser, 10).until(
EC.visibility_of_element_located((By.ID, "maintable")))
html_page = browser.page_source
browser.quit()
soup = BeautifulSoup(html_page)
Unfortunately, even using selenium, the javascript is not executing. The script that executes and generates the table I believe looks like the below and is all I'm seeing in the scraped source code:
<script type="text/javascript">
var hash = window.location.hash.substring(1);
$(document).ready(function () {
if (hash != '') {
activaTab(hash);
} else {
loadIframeSource3();
};
//$('i').tooltip({ placement: 'bottom', trigger: 'manual' }).tooltip('show');
});
function activaTab(tab) {
if (tab.indexOf('comment') >= 0) {
tab = 'comments';
loaddisqus();
} else if (tab.indexOf('readContract') >= 0) {
loadIframeSource();
} else if (tab.indexOf('balances') >= 0) {
loadIframeSource2();
};
$('.nav-tabs a[href="#' + tab + '"]').tab('show');
};
function updatehash(strhash) {
if (strhash == '') {
history.replaceState("", document.title, window.location.pathname);
} else {
var baseUrl = window.location.href.split('#')[0];
history.replaceState("", document.title, baseUrl + '#' + strhash);
}
}
var disqusloaded = false;
function loaddisqus() {
if (disqusloaded == false) {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
disqusloaded = true;
}
updatehash('comments');
}
var readContractLoaded = false;
function loadIframeSource() {
if (readContractLoaded == false) {
readContractLoaded = true;
document.getElementById('readcontractiframe').src = '/readContract?a=0xe94327d07fc17907b4db788e5adf2ed424addff6&v=0xe94327d07fc17907b4db788e5adf2ed424addff6';
}
}
var token_holders_loaded = false;
function loadIframeSource2() {
if (token_holders_loaded == false) {
token_holders_loaded = true;
document.getElementById('tokeholdersiframe').src = '/token/generic-tokenholders2?a=0xe94327d07fc17907b4db788e5adf2ed424addff6&s=11000000000000000000000000';
}
}
var token_transactions_loaded = false;
function loadIframeSource3() {
if (token_transactions_loaded == false) {
token_transactions_loaded = true;
document.getElementById('tokentxnsiframe').src = '/token/generic-tokentxns2?contractAddress=0xe94327d07fc17907b4db788e5adf2ed424addff6&a=&mode=';
}
}
</script>
Any suggestions?
I want to redirect and pass some data to other page.But not using query string and not pass data in URL
(function() {
var app = angular.module('PlateformApp', [])
app.controller('PlateformController', function ($scope,$window) {
//This will hide the DIV by default.
$scope.IsVisible = false;
$scope.ShowHide = function (platform) {
//If DIV is visible it will be hidden and vice versa.
$scope.IsVisible = $scope.IsVisible ? true : true;
//alert(platform);
document.getElementById("platform").value = platform;
var myEl = angular.element( document.querySelector( '#plat_val' ) );
myEl.text(platform);
}
$scope.storeAppWindow = function()
{
//store_url = $scope.storeUrl;
test_bc_url = ""
text_sh_url = ""
platform_val = document.getElementById("platform").value;
$http.get("/user/installedapp")
.then(function(response) {
$scope.myWelcome = response.data;
});
if (platform_val == "BC")
$window.open(test_bc_url, "popup", "width=500,height=400,left=10,top=50");
else if (platform_val == "Sh")
$window.open(text_sh_url, "popup", "width=500,height=400,left=10,top=50");
}
});
})();
Here It will open new window but i want to pass platform_val text_sh_url url in another page.And i am using flask in python.
You can pass the data by various methods, using $stateParams,using Storages, using factories or services. You can find the example using storage in my answer in this thread: sharing data using storages
(function() {
var app = angular.module('PlateformApp', [])
app.factory('newService', function() {
function set(data) {
datatosend = data;
}
function get() {
return datatosend;
}
return {
set: set,
get: get
}
});
app.controller('PlateformController', function($scope, $window, newService) {
//This will hide the DIV by default.
$scope.IsVisible = false;
$scope.ShowHide = function(platform) {
//If DIV is visible it will be hidden and vice versa.
$scope.IsVisible = $scope.IsVisible ? true : true;
//alert(platform);
document.getElementById("platform").value = platform;
var myEl = angular.element(document.querySelector('#plat_val'));
myEl.text(platform);
}
$scope.storeAppWindow = function()
{
//store_url = $scope.storeUrl;
test_bc_url = ""
text_sh_url = ""
platform_val = document.getElementById("platform").value;
$http.get("/user/installedapp")
.then(function(response) {
$scope.myWelcome = response.data;
});
if (platform_val == "BC") {
$window.open(test_bc_url, "popup", "width=500,height=400,left=10,top=50");
}
else if (platform_val == "Sh") {
var data = {
'platform_val': platform_val,
'text_sh_url ': text_sh_url
};
newService.set(data);
$window.open(text_sh_url, "popup", "width=500,height=400,left=10,top=50");
}
}
});
})();
And,in the page where you want to get the data. Just inject newService in the controller of that page and use newService.get(data)
app.controller('pageController',function($scope,newService){
var datafromanothercontroller = newService.get(data);
console.log(datafromanothercontroller );
})
I'm making an uploader for my project, and I try to avoid any flash-based solutions (I dont like flash much and target for mobile platforms support).
The whole process seems rather simple: I have a form, nice jQuery progress bar, I can make ajax requests with timeout from a script to update progressbar status...
If I do it according to Webpy cookbook, the only thing I don't get is how to recieve any info from server: how many bytes/chunks/whatever were already written?
You can create ajax uploader using FormData for the modern browsers.
$.fn.uploader = function( options ) {
var defaults = {},
opts = $.extend( defaults, options ),
that = $( this ),
url = that.data( "upload_url" ),
is_uploading = false;
function upload( files ) {
$.get( "/file/blank.html" );
if ( FormData === undefined ) {
alert( "Your browser does not support standard HTML5 Drag and Drop" );
return;
}
var xhr = new XMLHttpRequest(),
new_element = $( "<li><p>Loading</p><span></span></li>" )
.appendTo( that ),
xhr_upload = xhr.upload,
form = new FormData();
xhr_upload.addEventListener( "progress", function( e ) {
if( e.lengthComputable ) {
var p = Math.round( e.loaded * 100 / e.total );
new_element.children( "span" ).text( e.loaded == e.total ? "Processing..." : p + "%" );
}
}, false);
xhr_upload.addEventListener( "load", function( e ){}, false);
xhr_upload.addEventListener( "error", function( error ) { alert( "error: " + error ); }, false);
xhr.open( "POST", url, true );
xhr.setRequestHeader( "X-Requested-With", "XMLHttpRequest" );
xhr.onreadystatechange = function ( e ) {
if ( xhr.readyState == 4 ) {
is_uploading = false;
if( xhr.status == 200 ) {
var data = $.parseJSON( e.target.responseText );
if ( data.status == 0 ) {
new_element
.fadeOut(function (){ $( this ).remove(); })
.children( "span" ).text( "Upload error!" );
} else {
that.html( data.html );
}
} else {
new_element
.fadeOut(function (){ $( this ).remove(); })
.children( "span" ).text( "Upload error!" );
}
}
};
$.each( files, function() {
form.append( "files", this );
});
is_uploading = true;
xhr.send( form );
}
that.bind({
"dragover": function( e ) {
var dt = e.originalEvent.dataTransfer;
if( !dt || is_uploading ) { return; };
if( $.browser.webkit ) { dt.dropEffect = "copy"; };
$( this ).addClass( "active" );
return false;
},
"dragleave": function( e ) {
$( this ).removeClass( "active" );
},
"dragenter": function( e ){ return false; },
"drop": function( e ){
var dt = e.originalEvent.dataTransfer;
$( this ).removeClass( "active" );
if( !dt || !dt.files || is_uploading ) { return; };
upload( dt.files );
return false;
}
});
$( document ).bind({
'dragenter': function( e ) { return false; },
'dragleave': function( e ) { return false; },
'dragover': function( e ) {
var dt = e.originalEvent.dataTransfer;
if ( !dt ) { return; }
dt.dropEffect = "none";
return false;
}
});
};
On the server side I process it like this:
def POST(self):
i = web.webapi.rawinput()
try:
files = i.files
if not isinstance(files, list):
files = [files]
for f in files:
if f.filename:
filetype, encoding = mimetypes.guess_type(f.filename)
# do smth with f.file
except KeyError:
pass
if web.ctx.env.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest':
web.header("Content-Type", "application/json")
return json.dumps(dict(status=1, html=unicode(render_partial.files(uploaded_files))))
else:
raise web.seeother(web.ctx.env.get("HTTP_REFERER", "/"))
Otherwise you may look into nginx upload progress module or apache2 upload progress module, uWSGI has got this feature too.