I have a page that contains the HTML form with javascript setup like if you click on a button with someid, the form gets submitted. I verified this by firing this in browser console:
document.getElementById("arcotsubmit").click()
As soon as it gets fired, the url changes and form gets submitted.
Now i tried to replicate this with casper.js:
var casper = require('casper').create({});
casper.start('https://cib.icicibank.com/corp/BANKAWAY?Action.CorpUser.Init1.001=Y&AppSignonBankId=ICI&AppType=corporate', function() {
this.echo(this.getTitle());
});
casper.then(function(){
this.click("#arcotsubmit");
});
casper.then(function(){
console.log(this.getCurrentUrl())
});
casper.run();
It stays on the same URL and downloads the same page. I want to download the html that appears after the button gets clicked by casper. The URL is live and can be tested directly.
My point is if i can use this command in browser console
document.getElementById("arcotsubmit").click()
and make it redirect, why i am unable to do it with
this.click("#arcotsubmit") in casperjs?
It is submit instead click for redirecting. The default event for input[type=image] is submit so that try this:
casper.test.begin('Test page.', 2, function suite(test) {
casper.start(
'https://cib.icicibank.com/corp/BANKAWAY?Action.CorpUser.Init1.001=Y&AppSignonBankId=ICI&AppType=corporate',
function() {
this.echo(this.getTitle());
test.assertUrlMatch(/BANKAWAY?/, 'Current location is ' + this.getCurrentUrl());
}
);
casper.then(function(){
this.fill('#rt', {}, true);
this.wait(2000, function() {
test.assertUrlMatch(/BANKAWAY;/, 'New location is ' + this.getCurrentUrl());
});
});
casper.run(function() {
test.done();
});
});
It will be passed.
Test Result Screen Shot
Possible quick fix. If Casper's click isn't working, but your code works in console of the browser, try using Casper's evaluate function.
casper.then(function() {
this.evaluate(function() {
document.getElementById("arcotsubmit").click();
});
});
Related
I have this function, where I have a ajax call and in the success function, i have refresh the bootstrap table, now after the refresh i have a trigger command which i want to happen only when the refresh is done, how to do that,
success: function (result) {
console.log(result);
$('#overlay').hide();
swal({
title: result['msg'],
// text: result['text'],
type: result['type'],
showConfirmButton: true
});
$('#prospect_table').bootstrapTable('refresh');
element.parent('div').parent('div').parent('td').parent('tr').prev('tr').find('td:first').find('a').trigger('click')
}
the last event click happens at its specific time but I want to run that command only when the refresh is done,ie status=200
Thanks!
I have tried:
var evnCilck = element.parent('div').parent('div').parent('td').parent('tr').prev('tr').find('td:first').find('a').trigger('click'); // Or any other click function
$('#prospect_table').bootstrapTable('refresh', function(e){
evnCilck();
});
and
$('#prospect_table').bootstrapTable('refresh', function() {
element.parent('div').parent('div').parent('td').parent('tr').prev('tr').find('td:first').find('a').trigger('click');
});
No help from this.
You can do it like this
$('#prospect_table').bootstrapTable('refresh', function() {
element.parent('div').parent('div').parent('td').parent('tr').prev('tr').find('td:first').find('a').trigger('click');
});
Along with triggering an refresh event You also need to bind refresh eventlistener to the table like this :
var $table = $('#table');
$table.on('refresh.bs.table',function(){
// do your stuff here
element.parent('div').parent('div').parent('td').parent('tr').prev('tr').find('td:first').find('a').trigger('click');
})
You can do it by this way -
var evnCilck = element.parent('div').parent('div').parent('td').parent('tr').prev('tr').find('td:first').find('a').trigger('click'); // Or any other click function
$('#prospect_table').bootstrapTable('refresh', function(e){
evnCilck();
});
I have an application that uses tinyMCE. In this page, the user will compose a message then previews it on another page (not using tinyMCE's preview). I currently have an AJAX function that saves the content when the user clicks away from the tinyMCE UI. The problem is, I have different kinds of links on this same page, sometimes when a user clicks on the link, the AJAX function fails to save the content before redirecting, thus resulting to a blank preview or unsaved message.
<div>
<textarea id='msg'></textarea>
<a id='preview'>Preview</a>
<a id='other_page'>Other Page</a>
<a id='another_page'>Another Page</a>
</div>
Here are the JavaScript handlers and functions.
<script>
// INITIALIZE TINYMCE
tinyMCE.init({
// SAVE CONTENT ON BLUR
editor.on('blur', function() { save_message(this); });
})
function save_message(){
var msg= tinyMCE.get('msg ').getContent();
$.ajax({
statusCode : { 404: function(){alert('Not Found');} },
type : 'post',
data : {msg:msg},
url : '<script_that_handles_save>',
success : function(res){ // DO SOMETHING }
});
}
// WHEN PREVIEW IS CLICKED
$('a.preview).click(function(){
save_message();
});
$('a.other_page).click(function(){
save_message();
});
$('a.another_page).click(function(){
save_message();
});
</script>
A few things, your save_message() function is an AJAX call that needs to complete and send back a response for it to work. When you click an anchor tag, the function is called (a per your code above) but the page redirects before the function returns a response.
Also it seems like you are calling the function redundantly for each anchor tag, why not call it once for ALL anchor tags, like so a.click(function(){ // your function here });
Your code logic is good, you only need to re-structure and simplify it, like so:
tinyMCE.init({
// SAVE CONTENT ON BLUR
editor.on('blur', function() { save_message(this); });
})
$('a').click(function(e){
// prevent the redirect
e.preventDefault();
var msg= tinyMCE.get('msg ').getContent();
var location = $(this).attr('href');
// execute ajax
$.ajax({
statusCode : { 404: function(){alert('Not Found');} },
type : 'post',
data : {msg:msg},
url : '<script_that_handles_save>',
success : function(res){
// redirect on success
window.location.href = location
}
});
});
You can create some kind of flag variable, which will tell if links should be prevented from redirecting or not. Before sending AJAX request to save message, set this variable to true, and after successful request set it back to false. Also set an event listener on all links, which will check this flag variable, and if it equals true, prevent redirecting.
Example code:
var linksDisabled = false;
function save_message() {
linksDisabled = true;
$.ajax({
success: function() {
linksDisabled = false;
}
// some other options
})
}
$("a").click(function(event) {
if (linksDisabled) {
event.preventDefault();
}
});
I have a simple form that gets submitted when a user clicks open in the file browse window once they have completed selecting an image.
My HTML looks like something below.
<form id="imgForm" action="action.php" method="post" enctype="multipart/form-data">
<div class="fileUpload btn btn-lg btn-primary">
<span>Choose File</span>
<input id="imageToBeUploaded" type="file" class="upload" name="image"/>
</div>
</form>
JavaScript
$("body").on('submit', '#imgForm', function(){
$(this).ajaxForm({target:'#uploadStatus'});
console.log("submitting...");
return false;
});
/* Uploading Profile BackGround Image */
$('body').on('change','#imageToBeUploaded', function() {
//submit the form
$("#imgForm").submit();
});
My issue is that the form gets submitted but redirects to the action.php page with response. I was hoping to stop the redirect from happening while getting back a response on the current page instead. return false; doesn't seem to be working as per documentations at http://malsup.com/jquery/form/#ajaxSubmit
Any help would be greatly appreciated!
Please note that I have to support IE8/9 which means formData is out of the question!
Thank you.
Try implementing this code:
window.location.href it's a property that will tell you the current URL location of the browser. Changing the value of the property will redirect the page.
$("body").on('submit', '#imgForm', function(){
var a;
var b;
window.location.href = "../currenturl.htm?parameter1="+a+"¶meter2="+b;
or
window.location.href = "../currenturl.htm";
//where your browser need to stay(current) url should be mentioned here.
});
Just try this JavaScript/jQuery code and manage with your server script.
$(document).ready(function (e) {
/* Uploading Profile BackGround Image */
$('#imageToBeUploaded').on('change', function() {
//submit the form
$("#imgForm").submit();
alert('Form submitted');
});
$('#imgForm').ajaxForm({
target:'#uploadStatus',
beforeSubmit:function(){
alert('File uploading...');
},
success:function(){
alert('File uploaded');
},
});
});
Good Luck ['}
The page you've referenced is about $(this).ajaxSubmit(options); and not $(this).ajaxForm(options);. Have you tried $(this).ajaxSubmit(options);? The two are not synonymous. You seem to be mixing up their implementations.
Per the documentation, here is how to use ajaxSubmit():
$(document).ready(function() {
$('#imgForm').on('submit', function(){
$(this).ajaxSubmit({target:'#uploadStatus'});
console.log("submitting...");
return false;
});
$('#imageToBeUploaded').on('change', function() {
//trigger submit event
$("#imgForm").submit();
});
});
And ajaxForm():
$(document).ready(function() {
$('#imgForm').ajaxForm({target:'#uploadStatus'});
$('#imageToBeUploaded').on('change', function() {
//trigger submit event
$("#imgForm").submit();
});
});
You don't want to use delegated events unless you really have to. If the form is loaded after the DOM ready event, then by no means use delegated events.
from: Prevent page reload and redirect on form submit ajax/jquery
$("body").on('submit', '#imgForm', function(event){
$(this).ajaxForm({target:'#uploadStatus'});
console.log("submitting...");
event.preventDefault();
return false;
});
/* Uploading Profile BackGround Image */
$('body').on('change','#imageToBeUploaded', function(event) {
//submit the form
$("#imgForm").submit();
});
$(document).ready(function (e) {
/* Uploading Profile BackGround Image */
$('#imageToBeUploaded').on('change', function() {
//submit the form
$("#imgForm").submit();
alert('Form submitted');
});
$('#imgForm').ajaxForm({
target:'#uploadStatus',
beforeSubmit:function(){
alert('File uploading...');
},
success:function(){
alert('File uploaded');
},
});
});
You can try this:
use $(this).closest("#imgForm").submit();
instead of: $("#imgForm").submit();
$('#imageToBeUploaded').on('change', function() {
//submit the form
$(this).closest("#imgForm").submit();
$("#imgForm").submit();
});
$('form#imgForm').on('submit',function(e){
e.preventDefault();
$(this).ajaxSubmit({
url: 'upload',
uploadProgress: function (event, position, total, percentComplete){
//display status
$(".progress-bar").width(percentComplete + '%');
$('.progress-bar').html(percentComplete+'%');
},
success: function(response){
alert('Success');
},
error: function(response, status, e){
alert('Oops something went.');
},
resetForm: true
});
});
You need this in your script tag <https://code.google.com/p/struts2-jquery/source/browse/trunk/struts2-jquery-plugin/src/main/resources/template/js/plugins/jquery.form.min.js?r=1645>
Try this
$(document).ready(function() {
$("#imgForm").ajaxForm({
target:'#uploadStatus'
});
});
$('body').on('change','#imageToBeUploaded', function() {
//submit the form
$("#imgForm").submit();
});
You should use event.preventDefault(); instead of return false with jQuery
$("body").on('submit', '#imgForm', function(event){
event.preventDefault();
$(this).ajaxForm({target:'#uploadStatus'});
console.log("submitting...");
return false;
});
Alot of people might not agree with me but returning false is usually saying something failed, while your ajax submit might actually have worked just fine, so it could bring mixed results to your original caller. In this case it does't matter but I will only return false if something actually failed or went wrong or when a boolean is requested. If empty result I would return null, rather then false. Just convictions I suppose..
not sure why you have 2 js functions but you could combine both functions as :
$(document).ready(function() {
/* Uploading Profile BackGround Image */
$('body').on('change','#imageToBeUploaded', function() {
//submit the form
$('#imgForm').ajaxForm({target:'#uploadStatus'});
console.log("submitting...");
});
});
I currently have this code:
crossroads.addRoute('/login', function(){
$.ajax({
url: '/login',
type: 'GET',
data: {
},
success: function(msg) {
$('#' + main_window).html(msg);
}
})
});
Along with this hasher.js for maintaining history:
function parseHash(newHash, oldHash){
crossroads.parse(newHash);
}
hasher.initialized.add(parseHash); //parse initial hash
hasher.changed.add(parseHash); //parse hash changes
hasher.init(); //start listening for history change
$('a').on('click', function(e) {
e.preventDefault();
hasher.setHash($(this).attr('href'));
});
Now when I have a link that says #/login and click it, the login page is loaded fine. However, if the user clicks the login link again, the page doesn't reload. I know the click is registering, but the routing/hashing isn't firing. How do I manage to do this?
Any help would be greatly appreciated. Thanks!
You are not changing anything with hasher.setHash("#/currentpage") because you are already on that page. So the change event never gets fired. You could probably just go:
$('a').on('click', function(e) {
e.preventDefault();
hasher.setHash('');
hasher.setHash($(this).attr('href'));
});
But that would clutter the history, so you could force a reload on the click, if you make the loading method available:
var loadLogin = function(){
$.ajax({
.... your ajax settings ....
});
};
crossroads.addRoute('/login', loadLogin);
$('a').on('click', function(e) {
e.preventDefault();
var newHash = $(this).attr('href');
if(newHash === '/login' && hasher.getHash() === '/login') {
loadLogin()
} else {
hasher.setHash(newHash);
}
});
EDIT
As #Patchesoft pointed out, crossroads has a property called ignoreState, which will force any request to go though the router function, even if on the current page - https://millermedeiros.github.io/crossroads.js/#crossroads-ignoreState
Your can force the call of your route by this:
// add this dummy route first
crossroads.addRoute('noop', function() { } );
$('a').on('click', function(e) {
// route to dummy route
hasher.setHash('noop');
// and then replace by your login route
hasher.replaceHash('login');
}
I am using the following code to add a button to a page
$("#myDiv").html("<button id='fileUpload'>Upload</button>");
I am then creating an Ajax Upload instance on the button.
var button = $('#fileUpload'), interval;
new AjaxUpload(button, {
action: '/upload.ashx',
name: 'myfile',
onSubmit: function(file, ext) {
button.text('Uploading');
this.disable();
// Uploding -> Uploading. -> Uploading...
interval = window.setInterval(function() {
var text = button.text();
if (text.length < 13) {
button.text(text + '.');
} else {
button.text('Uploading');
}
}, 200);
},
onComplete: function(file, response) {
button.text('Upload');
window.clearInterval(interval);
}
});
What I want to do is append the button to the page then simulate clicking it automatically. How would I go about doing this?
Update
The code now reads:
$("#myDiv").html("<button id='fileUpload'>Upload</button>");
var button = $('#fileUpload'), interval;
new AjaxUpload(button, {
action: '/upload.ashx',
name: 'myfile',
onSubmit: function(file, ext) {
button.text('Uploading');
this.disable();
// Uploding -> Uploading. -> Uploading...
interval = window.setInterval(function() {
var text = button.text();
if (text.length < 13) {
button.text(text + '.');
} else {
button.text('Uploading');
}
}, 200);
},
onComplete: function(file, response) {
button.text('Upload');
window.clearInterval(interval);
}
});
$('#fileUpload').click();
The .click event does not seem to fire. It is reached in the code but does nothing...
** Update **
$('#fileUpload').click();
needs to be
$('input').click();
Please check the accepted answer for why.
What I want to do is append the button
to the page then simulate clicking it
automatically. How would I go about
doing this?
The short answer is that you don't.
The long answer:
First you need to understand how AJAX Upload works.
Plugin creates invisible file input on
top of the button you provide, so when
user clicks on your button the normal
file selection window is shown. And
after user selects a file, plugin
submits form that contains file input
to an iframe. So it isn’t true ajax
upload, but brings same user
experience.
There are two things here:
fileUpload is not the actual file input
Generally, <input type="file"> element cannot be clicked/set programmatically in modern browsers for security reasons.
You don't actually have a click handler on the button, hence nothing happens.
Simply by going
$('#fileUpload').click();
You can call the click handler on the button like this:
$('#fileUpload').click();
You have already handled adding it to the page.
$('body').append('Go').find('#send').click();