casperjs fill form doesn't work - javascript

I have a problem with casperjs.
I want to fill a form but casperjs says the form is not found... In the code I can't see a form name so I tried to use the formid without success
Here is the source code of the website where I want to fill the form
<tr class="wcontent" valign="top">
<td></td>
<td id="wcontent_login" class="widgetMiddleMiddle" style="display: block; height: 213px;">
<iframe frameborder="no" src="/WebInt.nsf/loginWidget.xsp?widgetUniqueId=anonymous-login-default" scrolling="no">
<!DOCTYPE html>
<html lang="de">
<head>
<body class="xspView tundra">
<form id="view:_id1" class="xspForm" enctype="multipart/form-data" action="/GI7/WebInt.nsf/loginWidget.xsp?widgetUniqueId=anonymous-login-default" method="post">
<div id="inactive_loginWidget">
<div class="inactive_loginLeft">Anmeldung</div>
<div class="inactive_loginRight">
<div style="height:27px;background-color:#004178;color:white;padding:10px; width:227px;margin-bottom:5px;text-align:center;">
<div>
<input id="username" type="text" placeholder="Benutzername" onkeypress="return handleKeyPressed(event)" onfocus="var elem = document.getElementById(''); if(elem != null) {hideLabel(elem, 'username');}" onblur="var elem = document.getElementById(''); if(elem != null) {if(document.getElementById('username').value == '') { showLabel(elem); } else { hideLabel(elem); }}" name="username" autocomplete="off" vk_19ae7="subscribed">
</div>
<div class="cleaner3px"></div>
<div>
<div class="cleaner3px"></div>
<div title="Anzahl der Spalten für die Darstellungsbreite des Browsers einstellen.">
<div class="cleaner10px"></div>
<div class="button" style="margin-left: -5px; cursor: default;" onmouseover="setHoverEffectButton(this, '');" onmouseout="resetHoverEffectButton(this, '');" onmousedown="setPressedButtonEffect(this, '');" onclick="handleKeyPressed(event, true)">
</div>
</div>
<script type="text/javascript">
<input id="view:_id1__VUID" type="hidden" value="!1k37604fezbng88zt78ksqv5x!" name="$$viewid">
<input type="hidden" name="$$xspsubmitid">
<input type="hidden" name="$$xspexecid">
<input type="hidden" name="$$xspsubmitvalue">
<input type="hidden" name="$$xspsubmitscroll">
<input type="hidden" value="view:_id1" name="view:_id1">
</form>
</body>
</html>
</iframe>
My casperjs Code
var casper = require("casper").create({
verbose: true,
logLevel: "debug"
});
function wait5seconds() {
casper.wait(5000, function() {
this.echo('2');
});
}
// casper.options.waitTimeout = 40000;
casper.start("https://Testseite.de/WebInt.nsf/loginWidget.xsp", function() {
this.echo("Page title: " + (this.getTitle()));
wait5seconds();
});
casper.then(function(){
this.fillSelector('Formname ????', {
'username': 'Hans',
'password': 'Wurst'
}, true);
});
casper.then(function() {
casper.capture('Test2.png');
});
casper.then(function() {
this.evaluate(function(){
//trigger click event on submit button
document.querySelector('input[type="submit"]').click();
});
});
casper.then(function() {
casper.capture('Test3.png');
});
casper.run();
I also tried to solve my problem with queryselector but still no success :(

I think you are missing 'form; from the selector.
Something along the lines of:
this.fillSelectors('form#view:_id1', {
casper.then(function(){
this.fillSelector('Formname ????', {
'username': 'Hans',
'password': 'Wurst'
}, true);
});
This question might help: How to use fillSelectors in casperjs

Yes but every time i start the Test it breaks in step 4 :
casper.then(function(){
this.echo("Formstart");
this.fillSelector('form#view:_id1', {
'username': 'XX',
'password': 'XX'
},true);
this.echo("Formend");
});
Formstart works but Formend does not get printed so the mistake must be there ....
I changed it now to :
casper.then(function(){
this.echo("Formstart");
this.fillSelector('form#view:_id1', {
'input[name="username"]': 'XX',
'input[name="password"]': 'Xx'
},true);
this.echo("Formend");
});
but still no success :(

Finally i solved it with an debugger and Post request:
casper.open('https://XXX/WebInt.nsf',
{
method: 'post',
data: {'username':'XX','password':'XX'}
}, function(response){
if(response.status == 200){
require('utils').dump(this.page.content);
}
});
:)

Related

Automatic Login Using JavaScript not Working Properly

I would like it such that a user only has to sign-in once and then the next time they open the hybrid app the get signed in automatically. The JavaScript code below here works but only when I remove the 'login/submit' div () which I need. How can I get around this?
HTML;
<body>
<form name="EventConfirmRedirection" class="Form" method="post" action="index.php" id="myForm" data-ajax="false">
<div class="user_login3"><input style="text-transform:lowercase" type="text" name="username" id="username" placeholder="username"></div>
<div class="user_login3"><input type="password" name="password" id="password" placeholder="password"></div>
<div style="margin-left:5%; width:45%; font-size:5px;">
<input data-theme="c" type="checkbox" id="rememberMe" name="rememberMe"/>
<label for="rememberMe"><span style="font-size:12px">remember me</span></label>
</div>
<div style="margin-left:5%; color:#FF0000; font-weight:bold" id="error"></div>
<div class="login"><input type="submit" value="LOGIN" name="submit" data-theme="e" id="submit"></div>
</form>
</body>
JAVASCRIPT;
$(document).ready(function() {
"use strict";
if (window.localStorage.checkBoxValidation && window.localStorage.checkBoxValidation !== '') {
$('#rememberMe').attr('checked', 'checked');
$('#username').val(window.localStorage.userName);
$('#password').val(window.localStorage.passWord);
document.EventConfirmRedirection.submit();
} else {
$('#rememberMe').removeAttr('checked');
$('#username').val('');
$('#password').val('');
}
$('#rememberMe').click(function() {
if ($('#rememberMe').is(':checked')) {
// save username and password
window.localStorage.userName = $('#username').val();
window.localStorage.passWord = $('#password').val();
window.localStorage.checkBoxValidation = $('#rememberMe').val();
} else {
window.localStorage.userName = '';
window.localStorage.passWord = '';
window.localStorage.checkBoxValidation = '';
}
});
});
AJAX
$(document).ready(function() {
"use strict";
$("#submit").click( function(e) {
e.preventDefault();
if( $("#username").val() === "" || $("#password").val() === "" )
{
$("div#error").html("Both username and password are required");
} else {
$.post( $("#myForm").attr("action"),
$("#myForm :input").serializeArray(),
function(data) {
$("div#error").html(data);
});
$("#myForm").submit( function() {
return false;
});
}
});
});
#chiboz in your javascript, instead of using:
document.EventConfirmRedirection.submit();
use:
$('#submit').click();

How to store the values retrieved from content script into textboxes with a button click

I am new to building chrome extension. I am using content script to retrieve the values. But Iam unable to load the values into the popup.html.
Below is the code.
popup.html
<head>
<script src="popup.js"></script>
</head>
<body>
<form id="addbookmark">
<p><label for="title">Title</label><br />
<input type="text" id="title" name="title" size="50" value="" /></p>
<p><label for="url">Url</label><br />
<input type="text" id="url" name="url" size="50" value="" /></p
<p><label for="jsonName">Json Name</label><br />
<input type="text" id="jsonName" name="jsonName" value=""/></p>
<p><label for="jsonKey">Key</label><br />
<input type="text" id="jsonKey" name="jsonKey" value="" /></p>
<p><label for="jsonValue">JSON Value</label><br />
<input type="text" id="jsonValue" name="jsonValue" value="" /></p>
<p>
<input id="submitJson" type="submit" value="Send JSON Object / Valued" />
<!-- <span id="status-display"></span> -->
</p>
</form>
</body>
</html>
popup.js
function onPageDetailsReceived(pageDetails) {
document.getElementById('title').value = pageDetails.title;
document.getElementById('url').value = pageDetails.url;
document.getElementById('jsonValue').value = pageDetails.retrievedJsonValue;
}
window.addEventListener('load', function(evt) {
document.getElementById('submitJson').addEventListener('click',function(){
var jsonName = document.getElementById('jsonName').value;
if(jsonName.length > 1){
var jsonKey = document.getElementById('jsonKey').value;
var jsonValueToFind = "";
jsonValueToFind = jsonName+"."+jsonKey;
chrome.runtime.getBackgroundPage(function(eventPage) {
eventPage.getPageDetails(function(response){
alert(response.url);
document.getElementById('url').value = response.url;
}, jsonValueToFind);
});
}
});
});
event.js
function getPageDetails(callback,jsonValueToFind) {
chrome.tabs.executeScript(null,
{code:'var jsonValue ='+jsonValueToFind},
function(){
chrome.tabs.executeScript(null,{file: 'content.js' });
});
chrome.runtime.onMessage.addListener(function(message) {
callback(message);
});
}
content.js
chrome.runtime.sendMessage({
'title': document.title,
'url': window.location.href,
'retrievedJsonValue': jsonValue
});
Can anybody help me in storing the values to text boxes in the popup boxes, after the button click.
For the particular task the event page and separate content script file aren't even necessary:
manifest.json:
"permissions": ["tabs", "activeTab"]
popup.html:
...............
<script src="popup.js"></script>
</body>
</html>
popup.js ("load" event isn't needed since the script is executed after DOM is parsed):
document.getElementById('submitJson').addEventListener('click', function() {
var jsonName = document.getElementById('jsonName').value;
if(jsonName.length > 1) {
var jsonKey = document.getElementById('jsonKey').value;
getPageDetails(jsonName + "." + jsonKey, function(pageDetails) {
Object.keys(pageDetails).forEach(function(id) {
document.getElementById(id).value = pageDetails[id];
});
});
}
});
function getPageDetails(jsonValueToFind, callback) {
chrome.tabs.executeScript({code: jsonValueToFind}, function(result) {
var value = result[0];
chrome.tabs.query({currentWindow: true, active: true}, function(tabs) {
callback({
url: tabs[0].url,
title: tabs[0].title,
jsonValue: value
});
});
});
}
tabId (the first parameter of executeScript) is simply omitted due to being optional.
injected script result is the last value in the code and it's passed in an array result.

onsubmit validateForm funxtion is not working

here for validation i used onsubmit event.
but any how its not working.
i just want check that textbox filed is empty or not.
<!DOCTYPE html>
<html>
<head>
<title>temple3</title>
<link rel="stylesheet" type="text/css" href="temple3css.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>
<body>
<div id="popup-content" class='container'>
<div id="container1">
<form id="form" class="form" onsubmit="return validateForm()">
<h1>Feedbak Form</h1>
<div class="content">
<div class="intro"></div>
<div id="section0" >
<div class="field roption">
<input type="radio" name="view" value="public" checked="checked"> <span>Public</span>
<input type="radio" name="view" value="private" ><span>Private</span>
</div>
<div class="field category">
<label for>Category:</label>
<select class="dropDownCate" autofocus>
<option value="bug">Bug</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</div>
<div class="field message">
<label for="Comments">Comments:</label>
<textarea id="comments" name="Comments" placeholder='Your Feedback Here!' autofocus></textarea>
</div>
<div class="field">
<label for="Email">Email</label>
<input type="email" id="email" name="Email" placeholder="example#stevens.edu(optional)" autofocus>
</div>
<div class="field"><input type="submit" id="submit-feedback-button" autofocus></div>
</div>
</div>
</form>
</div>
</div>
<div id="popup-overlay-bg"> </div>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
function validateForm(){
var texbox=document.getElementById("comments").value;
if(texbox == "") {
document.getElementById("comments").focus();
// document.getElementById("comments").style.border = "1px solid #ff0000";
return false;
}
}
$(document).ready(function(){
$("#feedback-button").click(function(){
openfeedbackform();
});
$("#popup-overlay-bg").click(function(){
closefeedbackform();
});
$("#submit-feedback-button").click(function(){
// closefeedbackform();
});
$(window).resize(function(){
updatefeedbackform();
});
$("#submit-feedback-button").click(function(){
var category=$(".dropDownCate").val();
var roption=$('input:radio[name=view]:checked').val();
var message=$("#comments").val();
var email=$("#email").val();
$.ajax({
type: "POST",
url: "feedback.php",
data: "category="+category+ "&roption="+roption+ "&message="+message+ "&email="+email,
success:function(result)
{
if(result=="true"){
$("#form").hide();
$("#container1").html("<h3>Thank you for your feedback We will get back to you ASAP</h3> ");
}
else{
$("#form").hide();
$("#container1").html("<h3> database error </h3>");
}
}
});
return false;
});
});
function openfeedbackform(){
$("#popup-content").find('input:text').val('');
$("#popup-content").fadeIn();
$("#popup-overlay-bg").fadeIn();
updatefeedbackform();
}
function updatefeedbackform(){
$popup=$("#popup-content");
var top = "50px";
var left = ($(window).width() - $popup.outerWidth()) / 2;
$popup.css({
'top' : top,
'left' : left
});
}
function closefeedbackform(){
$("#popup-content").fadeOut();
$("#popup-overlay-bg").fadeOut();
}
</script>
</body>
</html>
earlier i used same this for form validation. but i don't why its not working here. i tried to debug but function has not been call.
The problem is you are doing ajax submit in the button click event, not in the form submit.
The click handler is triggered before the submit event handler, so the validation does not have any effect.
The solution will be to use the form submit event handler for both validation and the ajax call as given below, and then there is no need to have the inline event handler like onsubmit="return validateForm()"
$("#form").submit(function () {
if (validateForm() === false) {
return false;
}
var category = $(".dropDownCate").val();
var roption = $('input:radio[name=view]:checked').val();
var message = $("#comments").val();
var email = $("#email").val();
$.ajax({
type: "POST",
url: "feedback.php",
data: "category=" + category + "&roption=" + roption + "&message=" + message + "&email=" + email,
success: function (result) {
if (result == "true") {
$("#form").hide();
$("#container1").html("<h3>Thank you for your feedback We will get back to you ASAP</h3> ");
} else {
$("#form").hide();
$("#container1").html("<h3> database error </h3>");
}
}
});
return false;
});

Add enter for submit textarea

Hi i was created a new chat box,everithing is working but i need to when i click enter to sumit a message(to go to function Kucaj() ).Can you help me with that?
I add some code for enter but didnt work.Thanks
<?php
session_start();
if(!isset($_SESSION['username'])){
?>
<form name="forma2" action="login.php" method="post">
<table>
Username: <input type="text" name="username" /><br />
Password: <input type="password" name="password" />
<tr>
<td colspan="2"><input type="submit" name"submit" value"Login"/td>
</tr>
<tr>
<td colspan="2">Registruj se!</td>
</tr>
<?php
exit;
}
?>
<html>
<head>
<title>Maturski rad</title>
<script src="http://code.jquery.com/jquery-1.9.0.js"></script>
<script>
function Klikni(){
if(forma1.msg.value == ''){
alert('Upisi poruku!');
return;
}
var msg = forma1.msg.value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState==4&&xmlhttp.status==200){
document.getElementById('chatlogs').innerHTML = xmlhttp.responseText;
}
forma1.msg.value='';
}
xmlhttp.open('GET','insert.php?&msg='+msg,true);
xmlhttp.send();
}
$(document).ready(function(e) {
$.ajaxSetup({cache:false});
setInterval(function() {$('#chatlogs').load('logs.php');}, 2000);
});
</script>
</head>
<body>
<form name="forma1" action="#" id="forma1">
Username: <b><?php echo $_SESSION['username']; ?></b></br>
Poruka: <br />
<textarea name="msg" style="width:500px; height:100px"></textarea><br />
Posalji<br /><br />
Izloguj se<br /><br />
<script>
$("forma1").keypress(function(event) {
if (event.which == 13) {
event.Klikni();
}}
</script>
<div id="chatlogs">
Molim sacekajte da se ocita!!!
</div>
</body>
</html>
You can just add onsubmit=return Klikni(); attribute to your form and return false; to Klikni function without using .keypress(). Form submitted on user pressing enter is a default behaviour.
function Klikni(e) {
alert("Enter pressed");
return false;
}
<form name="forma1" action="#" id="forma1" onsubmit="return Klikni();">
Put your cursor into the field and press Enter.<br>
<input type="text">
</form>
try like this source,
form.submit(function(e) {
e.preventDefault();
$(this).find('[type=submit]').click();
$("form").submit();
})
Try keydown instead of keypress as:
$("forma1").keydown(function(event) {
You may use like this.It should be like this Klikni(); not like event.Klikni();
<script>
$("forma1").keypress(function(event) {
if (event.which == 13) {
Klikni(); //no need of event there..
}}
</script>

jQuery function problems

I can't execute this jquery function properly. When I click on submit's form, only shows the two first alerts and then the page reloads. So I click again on the form's submit with the page reloaded and then shows the rest of the alerts (beginning by the third one) and then the function works fine.
In conclusion: I need to click on the form's submit two times instead of one to execute the function.
Any idea? Thank you.
JS Code:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
alert("enters script");
$(function () {
alert("enters jquery function");
$(".submit").click(function () {
alert("enters click submit function");
var name = $("#name").val();
var date = $("#date").val();
var dataString = 'name=' + name + '&date=' + date;
alert("saved variables");
if (name == '' || date == '') {
alert("enters if");
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
} else {
alert("enters else");
$.ajax({
type: "POST",
url: "join.php",
data: dataString,
success: function () {
alert("enters success");
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
refresh();
}
});
}
return false;
});
});
</script>
HTML Code:
<form method="post" name="form">
<ul>
<li>
Name <input id="name" name="name" type="text" />
</li>
<li>
Date <input id="date" name="date" type="date" />
</li>
</ul>
<div >
<input type="submit" value="Submit" class="submit"/>
<span class="error" style="display:none"> Please Enter Valid Data</span>
<span class="success" style="display:none"> Registration Successfully</span>
</div>
</form>
use the event.preventdefault to stop the submission of the page
http://api.jquery.com/event.preventdefault/
Your problem is using submit buttons, they have some default behaviors other than what you add as a event to it.
replaced this:
<input type="submit" value="Submit" class="submit" />
with:
<input type="button" value="Submit" class="submit" />
this you working DEMO
other than changing the submit button to a regular button, you can fix your code by disabling that default behaviors, adding onsubmit to your form node:
<form method="post" name="form" onsubmit="return false;">
<!--your stuff-->
</form>
Try this:
<script type="text/javascript">
$( document ).ready(function() {
$(".submit").click(function(){
alert("entra en la funcion del clic del submit");
var nombre = $("#nombre").val();
var fecha = $("#fecha").val();
var dataString = 'nombre='+ nombre + '&fecha=' + fecha;
alert("variables guardadas");
if(nombre=='' || fecha=='')
{
alert("entra en el if");
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
alert("entra en el else");
$.ajax({
type: "POST",
url: "join.php",
data: dataString,
success: function()
{
alert("entra en el success");
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
refresca();
}
});
}
return false;
});
});
First of all, thank you to everybody for your help.
Finally the main problem comes from other part of the code. I was using pjax (https://github.com/thybag/PJAX-Standalone) to replace the form with other html document (in this case page1.html) after doing the mysql insert through "join.php". And I'm not calling the jquery function properly.
Explanation: You begin in page1.html, then click on "Go To Page 2" (This replace the div "content" with the body of page2.html). Then complete the form and submit it. When you click on submit, activates the jquery function (join.php mysql insert inside) and finally replace again the div "content".
Solution (this works):
page1.html
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript" src="pjax-standalone.js"></script>
<script type="text/javascript">
pjax.connect({
'container': 'content',
'beforeSend': function(){console.log("before send");},
'complete': function(){console.log("done!");
if($("#button_pg_2").length)
{
$( document ).ready(function()
{
$(".submit").click(function()
{
var nombre = $("#name").val();
var fecha = $("#date").val();
var dataString = 'name='+ name + '&date=' + date;
if(name=='' || date=='')
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax(
{
type: "POST",
url: "join.php",
data: dataString,
success: function()
{
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
replace();
}
});
}
return false;
});
});
}
}
});
</script>
<script type="text/javascript">
function replace()
{
pjax.invoke('page1.html', 'content');
}
</script>
</head>
<body>
<div id="header">
This div never changes
</div>
<div id="content">
Go To Page 2
</div>
</body>
</html>
page2.html
<html>
<body>
<form method="post" name="form">
<ul>
<li>
Name <input id="name" name="name" type="text" />
</li>
<li>
Date <input id="date" name="date" type="date" />
</li>
</ul>
<div >
<input type="button" id="button_pg_2" value="submit" class="submit"/>
<span class="error" style="display:none"> Please Enter Valid Data</span>
<span class="success" style="display:none"> Registration Successfully</span>
</div>
</form>
</body>
</html>

Categories