I have got a problem with my test in CasperJS.
This is my code:
var casper = require('casper').create({
viewportSize:{
width:1920,
height: 1080
}
});
casper.start('http://myweb.es/', function() {
})
//COMPROBACION DE POPUP LOGIN
casper.then(function(){
this.click('.btn-attendee');
this.waitForSelector(
'#form_signup2',
function(){
//El parametro 'INFO' es para que el echo aparezca en color VERDE
this.echo('Existe el popup SIGNUP', 'INFO');
this.capture('signup.jpg', undefined, {
format: 'jpg',
quality: 75,
});
this.echo('pantallazo signup', 'INFO');
this.wait(4000, function() {
this.fill('form#form_signup2', {
'first_name': 'Perico',
'last_name': 'Palotes',
'email': new Date().getTime()+'#testing.es',
'password': '123456'
//Ponemos false porque sino nos haria el SUBMIT del formulario y no queremos eso.
//En el email la pasamos un numero aleatorio para que no de fallo al ejecutar el script varias veces
}, true);
//PROBLEM HERE! No run this CLICK
this.click('.checkbox');
this.capture('form.jpg', undefined, {
format: 'jpg',
quality: 75,
});
this.echo('pantallazo form', 'INFO');
});
},
function(){
//El parametro 'ERROR' es para que el echo aparezca en color ROJO
this.echo('error login', 'ERROR')
},
10000
);
});
casper.run();
My problem is that in the comment //PROBLEM this.capture runs but the this.click does not run and this class is good and works in the console of firebug with Mozilla.
this.click does not run in this part of code.
What's my problem?
you need to learn how casperjs uses jquery. it has to be passed to the evaluate function inside of your casper function.
If you don't wish to click by jquery, you could just say casper.click(x('yourXpath'));
Otherwise you need to make sure your jQuery attempts to click are using the right context.
high level example to use jquery...
casper.then(function () {
// this is your casper function
this.evaluate(function () {
// this is the function that can now manipulate the page using jQuery
$('.yourClass').click();
});
});
Related
Hello Everyone i have modal dialog that trigger database insertion when it has been closed. However when i check my table in DB i often duplicate insertion.
The insertion is done thru ajax call. Here is my source code
$(`#closingModal-${alertId}`).on('hidden.bs.modal', function (e)
{
//..Load la map pour la localisation du badge d'alerte
loadMapByMacAddress(macAddress)
//..Inserer dans la BD le nom de l'utilisateur qui a ferme le modal
const alarmId = parseInt(alertId.replace('alerte', ''));
$.ajax({
url: "/Observer/SetStopDynamicAlarm",
type: "POST",
data: {
LastUpdate: dateFermeture.toJSON(),
AlarmId: alarmId
}
});
$(this).remove();
});
I don't really any error in the above source code. Any help woud be appreciated.
Thanks
I use a SweetAlert2 Popup with an AJAX request. Once the user clicks on submit I execute the request.
In the PHP file I then make some validation on the submitted data and depending on the result I want to give a feedback in SweetAlert2 for the user as information.
Here is my SweetAlert2 Code:
$('#sweet-ajax').click(function () {
swal({
title: "Sure?",
text: "Clicking on validated sends the data to our tool.",
type: "warning",
showCancelButton: true,
closeOnConfirm: false,
confirmButtonText: "Yes, submit!",
cancelButtonText: "Cancel",
showLoaderOnConfirm: true,
confirmButtonClass: 'btn btn-success',
cancelButtonClass: 'btn btn-danger m-l-10',
preConfirm: function(givenData){
return new Promise(function(resolve, reject) {
setTimeout(function(){
//if statment only for test purposes filled with 2==1
if(2 == 1){
swal("Oops", "Sorry something strange happend!", "error")
}else{
resolve()
}
}, 2000)
})
},
allowOutsideClick: false
}).then(function(givenData){
$.ajax({
type: "post",
url: "/assets/php/checkTool.php",
data: {registration: "success", amount: ammountInput, email: "test#example.com"},
})
swal({
//only if the response from the AJAX is correct - but how?
type: 'success',
title: 'Correct!',
html: 'All safe! Here is the answer from the tool: ' //need to get the return value of the AJAX request and append it here
})
}, function(dismiss) {
if (dismiss === 'cancel') {
swal(
'Cancelled',
'The action have been cancelled by the user :-)',
'error'
)
}
})
});
And the checkTool.php file:
<?php
$registration = $_POST['registration'];
$ammountInput= $_POST['ammount'];
$email= $_POST['email'];
//only some demo things here. Implement it after the SweetAlert2 stuff works properly
if ($registration == "success"){
return response(json_encode(array("abc"=>'Success')));
}else{
return response(json_encode(array("abc"=>'Error')));
}
?>
How can I now determinate what is the response from the AJAX request in the Javascript Code of SweetAlert2?
Is it possible to handle the AJAX response in SweetAlert2?
Wrap your sweet alert inside the ajax .done(function(response){}) function
}).then(function(givenData){
$.ajax({
type: "post",
url: "/assets/php/checkTool.php",
data: {registration: "success", amount: ammountInput, email: "test#example.com"},
}).done(function(response) {
if(response['abc'] === 'Success') {
swal({
type: 'success',
title: 'Correct!',
html: 'All safe! Here is the answer from the tool: ' + response['answer']
})
}
});
})
}, function(dismiss) {
In my experience what made it work, keeping in mind the use of showLoaderOnConfirm: true is doing the ajax call inside the preconfirm, and getting from the json response the elements I need as follows:
swal({
title: "Sure?",
text: "Clicking on validated sends the data to our tool.",
type: "warning"
showLoaderOnConfirm: true,
preConfirm: function () {
return new Promise(function (resolve) {
$.ajax({
type: "POST",
contentType: "application/json; charset=UTF-8",
data: JSON.stringify(objectToPost),
url: "/assets/php/checkTool.php",
dataType: 'json', // in ,my case the absence of this was the cause of failure
})
// in case of successfully understood ajax response
.done(function (myAjaxJsonResponse) {
console.log(myAjaxJsonResponse);
swal(
"My title!",
"My response element is: " + myAjaxJsonResponse.selectedElement,
"success"
);
})
.fail(function (erordata) {
console.log(erordata);
swal('cancelled!', 'The action have been cancelled by the user :-)', 'error');
})
})
},
})
.catch(swal.noop)
The swal being invoked when clicking a button, on my scenario.I hope this helps someone, as it took me quite some time to make it work.
I am using ng-grid(UI-grid) in my angular project.
My client gave me tabled grid as mockup. Now I want to design UI-grid as per the clients design.
Please suggest me the way how can I achieve this.
Here is an example on how to add image to ng-grid. You have to use cellTemplate, the content of this can be stored into a separate *.html file as well...
// main.js
var app = angular.module('myApp', ['ngGrid']);
app.controller('MyCtrl', function ($scope, $http) {
$http.post('/MyPage/index.json?details=full').success(function (data) {
$scope.carData = data;
});
$scope.updatecar =function(row){
$http.post('/MyPage/index.json?details=&carID='+row.getProperty('carID')+'&enable='+row.getProperty('link')).success(function (data) {
$scope.carData = data;
});
};
$scope.gridOptions = {
data: 'carData',
columnDefs: [{field: 'carName', displayName: 'car Name'},
{field: 'carTemperature', displayName: 'Temperature'
, cellTemplate:
'<div ng-class="ngCellText">' +
'{{row.getProperty(col.field)}} <img ng-src="{{row.getProperty(\'imageName\')}}" alt=""/>'+
' <a href ="" ng-click="updatecar(row)">' +
'{{row.getProperty(\'linkText\')}} </a>' +
'</div>'
}
]
};
});
I want to memorize the response of an ajax request, how I can do it?
In the code above, I found "" in the console...
How can I do it? any suggests?
var jsoncolumnset = '';
Ext.Ajax.request({
scope: this,
url: 'index.php',
params: {
m: 'Columnset',
a: 'readDefault'
},
reader: {
type: 'json',
root: 'rows'
},
success: function(response){
//Passo tutto il json (dovrebbe essere fatto un decode, ma viene gestito da Alfresco)
jsoncolumnset = response.responseText;
this.getStore('Documents').proxy.extraParams.columnset = response.responseText;
},
failure: function(){
//TODO: gestione fallimento chiamata
}
});
console.log(jsoncolumnset);
Ajax is asynchronous so while you have started the request in your Ext.Ajax.request call, the response has not come back by the time console.log(jsoncolumnset) is being executed.
The 'success' method will execute when the server response comes back to the browser which could be milliseconds or seconds later - either way the code mapped to the 'success' event is executed after the console.log executes.
So it appears the snippet is from code nested in some object since you have the "this" scope in place. .
You can add some event based logic that works nicely with ajax. Here is an idea:
// add this custom event in line with other bindings or in the objects constructor or a controllers init method
this.on('columnsready', this.logColumns);
// add this method to the main object
handleColumnResponse: function () {
//Passo tutto il json (dovrebbe essere fatto un decode, ma viene gestito da Alfresco)
this.jsoncolumnset = response.responseText;
this.getStore('Documents').proxy.extraParams.columnset = response.responseText;
// fire the custom event
this.fireEvent('columnsready');
},
// add this as an example of where you would put more logic to do stuff after columns are setup
logColumns: function () {
console.log(this.jsoncolumnset);
},
Ext.Ajax.request({
scope: this,
url: 'index.php',
params: {
m: 'Columnset',
a: 'readDefault'
},
reader: {
type: 'json',
root: 'rows'
},
// map to the handler method in the main object
success: this.handleColumnResponse,
failure: function(){
//TODO: gestione fallimento chiamata
}
});
Thanks to this answer I was able to get javascript to execute when being loaded via an ExtJS AJAX call.
However, the following code does not work the same in all browsers (on mac):
chrome: works, alert pops up
safari: works, alert pops up
firefox: works, but only when Firebug is enabled, when Firebug is not enabled, the script is ignored
How can I get javascript to execute via AJAX call in Firefox without having Firebug installed?
Ext.onReady(function(){
var menuItemStart = new Ext.Panel({
id: 'panelStart',
title: 'Start',
html: 'This is the start menu item.',
cls:'menuItem'
});
var menuItemApplication = new Ext.Panel({
id: 'panelApplication',
title: 'Application',
html: 'this is the application page',
cls:'menuItem'
});
var regionMenu = new Ext.Panel({
region:'west',
split:true,
width: 210,
layout:'accordion',
layoutConfig:{
animate:true
},
items: [ menuItemStart, menuItemApplication ]
});
var regionContent = new Ext.Panel({
id: 'contentArea',
region: 'center',
padding:'10',
autoScroll: true,
html: 'this is the content'
});
new Ext.Viewport({
layout: 'border',
items: [ regionMenu, regionContent ]
});
menuItemStart.header.on('click', function() {
Ext.Ajax.request({
url: 'content/view_start.php',
success: function(objServerResponse) {
regionContent.update(objServerResponse.responseText);
}
});
});
menuItemApplication.header.on('click', function() {
Ext.Ajax.request({
url: 'content/view_application.php',
success: function(objServerResponse) {
var responseText = objServerResponse.responseText;
console.log(responseText);
regionContent.update(responseText);
var scripts, scriptsFinder=/<script[^>]*>([\s\S]+)<\/script>/gi;
while(scripts=scriptsFinder.exec(responseText)) {
eval(scripts[1]);
}
}
});
});
});
The base that is being loaded:
<script type="text/javascript">
alert('inside application view');
</script>
<?php
echo 'this is the application view at ' . date('Y-m-d h:i:s');
?>
console.log(responseText);
this line seems problematic to me. console exists only when Firebug is on, so you'll have to comment it, or do some checking whether it exists before using it.
console.log is your culprit.
Whenever you're logging in JavaScript, it's a good idea to check if console exists before calling it's functions:
if(window.console) console.log('whatever');
That way, it will only execute when the console is available.
Not sure if removing console.log fixed this for you, but please see my other answer regarding the loadScripts config also.