Nightwatch Ajax request - nightwatch.js

I am having a <label id=ajaxtest>Not ajax</label> in the HTML page. After 5 seconds the label get changed to <label id=ajaxtest>Called ajax</label>
I am using nightwatch and trying to assert the text whether "Called ajax" is coming. I am new to nightwatch and kind of stuck how I can go. I tried few steps using asynch function and getText the label and nothing seems to work.
'Should display "Called ajax" message': (client) => {
home
.waitForElementVisible('#ajaxlabel',1000)
.assert.containsText('#ajaxlabel', 'not ajax');
client
.executeAsync(function(done) {
(function fn(){
// tried getText() here but the code is not working..
return done("Finally");
})();
}, [], function(result) {
console.log("Inside Final:"+result.value);
});

You can probably use the before/after methods to accomplish this.
home.expect.element('#ajaxlabel').text.to.contain('Called ajax').after(5000);

Related

AngularJS : ng-selectize is not initializing selctize options after AJAX call

I'm using ng-selectize directive to a select box using angularJS. Options to the slectbox are retrieved from an AJAX call. AJAX call response is coming in proper format.If do inspect element, select box options are populated properly. But in the UI, options are not rendered. Is there any specific reason for this behaviour? The same code is working fine in another place.
Here is my code:
HTML:
<select multiple="multiple"
ng-model="email.existing"
ng-options="obj.email for obj in emailLists track by obj.email"
placeholder="Choose from existing email address"
selectize>
Javascript
angular.module('myApp', [
'myApp.controllers',
'myApp.services',
'ngDialog',
'angular-selectize'
]);
angular.module('myApp.services', []).
factory('myAPIservice', function($http) {
var myAPI = {};
myAPI.getAllEmail = function( data ) {
return $http.post(APP_BASE_URL + "director/getallemail", data );
}
return myAPI;
});
angular.module('myApp.controllers', [])
.controller('myCntrl', function($scope, myAPIservice, ngDialog) {
myAPIservice.getAllDirectorsEmail({}).success(function (response) {
$scope.emailLists = response;
});
});
The above code retrieves email list from url. Sample response will look like this.
AJAX Response
If I change the javascript code to
angular.module('myApp.controllers', [])
.controller('myCntrl', function($scope, myAPIservice, ngDialog) {
$scope.emailLists = new Array({email:'abc#def.com'},{email:'lmn#opqr.com'})
});
and the response will be
Without AJAX call
Can anyone help me resolve this issue?

CasperJS not submitting $_POST array

I have a form which contains a hidden field;
<input name="qsID" type="hidden" value="1368113958" />
This is a hidden field added by Concrete5.
When submitting the form its like the hidden field does not exist, Concrete5 (PHP) cannot see the hidden field so presumably CasperJS is not sending the hidden field.
Why is this happening?
Update
Using var_dump I can see that the whole $_POST array is empty
Update 2
It seems that this single piece of code is the difference between the form being posted correctly and failing;
casper.waitForSelector("#Question33",
function success() {
this.test.assertExists("#Question33");
this.click("#Question33");
},
function fail() {
this.test.assertExists("#Question33");
});
This code also breaks the posting of form data
casper.waitForSelector("form#miniSurveyView576 input[name='Question34']",
function success() {
this.test.assertExists("form#miniSurveyView576 input[name='Question34']");
this.click("form#miniSurveyView576 input[name='Question34']");
},
function fail() {
this.test.assertExists("form#miniSurveyView576 input[name='Question34']");
});
I basically had to scrap this code as it did not work at all.
What I ended up with was something like this
casper.test.begin('web site up', 4, function(test) {
casper.start(url).then(function() {
this.test.assert(
this.getCurrentUrl() === url, 'url is the one expected'
);
this.test.assertHttpStatus(200, url + ' is up');
functions.viewPortCapture(casper, viewports[0], "1001");
test.assertExists(x("//a[normalize-space(text())='ABC']"));
this.click(x("//a[normalize-space(text())='ABC']"));
this.waitForUrl(/abc\/$/, function(){
test.assertExists("input[type='submit']");
});
});
casper.run(function() {
test.done();
});
});

Ajax send parameters through url

I'm new with ajax and thought i'd be a fun experiment to put into my project. I've created my own lightbox type feature to send a message on a website I'm creating. When the user clicks "Send Message", that's when the lightbox appears, and at the top I'm trying to get it to say "Send message to User", where User is the name of the user they're sending a message too. My lightbox html elements are actually on a seperate webpage, which is why I'm using ajax. this is what I have so far, and can't seem to figure out what the problem is:
user.php page
<div id = "pageMiddle"> // This div is where all the main content is.
<button onclick = "showMessageBox(UsersName)">Send Message</button>
</div>
Note: The username passes correctly into the javascript function, I have checked that much.
main.js page
function showMessageBox(user){
alert(user); // where i checked if username passes correctly
var ajaxObject = null;
if (window.XMLHttpRequest){
ajaxObject = new XMLHttpRequest();
}else if (window.ActiveXObject){
ajaxObject = new ActiveXObject("Microsoft.XMLHTTP");
}
if (ajaxObject != null){
ajaxObject.open("GET", "message_form.php", true);
ajaxObject.send("u="+user);
}else{
alert("You do not have a compatible browser");
}
ajaxObject.onreadystatechange = function(){
if (ajaxObject.readyState == 4 && ajaxObject.status == 200){
document.getElementById("ajaxResult").innerHTML = ajaxObject.responseText;
// use jquery to fade out the background and fade in the message box
$("#pageMiddle").fadeTo("slow", 0.2);
$("#messageFormFG").fadeIn("slow");
}
};
}
message_form.php page
<div id = "messageFormFG">
<div class = "messageFormTitle">Sending message to <?php echo $_GET['u']; ?></div>
</div>
Note: When accessing this page directly through the URL, giving it a parameter of u and a value, it displays correctly
Use jQuery.ajax();
http://api.jquery.com/jQuery.ajax/
$.ajax({
type: "GET",
url: "message_form.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
freakish way to do it (old school) :)
anyway i think the problem may be that you are loading an entire html page to a div! meaning tags and stuff, a good way to understand what's wrong would be to use a debugger and see what comes in ajaxObject.responseText.
Hope this helps.
Btw convert to jQuery ajax!! saves you loads of time =)
I believe that you need to add a request header prior to sending your data. So you'd have this:
ajaxObject.open("GET", "message_form.php", true);
ajaxObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxObject.send("u="+encodeURIComponent(user));
Instead of what you have.
However, it may be a good idea to allow a library to do this for you. It looks like you already have jQuery loaded, so why not let it handle your AJAX requests instead?
I figured it out after watching some ajax tutorials from bucky :) aka thenewboston. If I'm using the GET method, i just had to add the parameter to the end of the url in the .open function, instead of passing it through the send function (like you would a post method).
if you want to send number of field values using ajax.you can use serilalize function.
Example:
jQuery.ajax({
url: 'filenamehere.php',
type: 'post',
data: $("#formidhere").serialize(),
success: function(data){
..//
}
});

Strange issue with ajax POST

I have this html page with the form
<form method="post" id="form1" name="form1" action="/status_comment/save">
//Some text inputs
<input type="text" name="new_comment" id="new_comment" onkeydown="post_comment(event,'13')" >
</form>
And this is my javascript function to do the POST call
function post_comment(event,item_id)
{
var keyCode = ('which' in event) ? event.which : event.keyCode;
if(parseInt(keyCode)==13 && event.shiftKey!=1)
{
var str = $('#form1').serialize(); // Gets all the filled details
$.post('/status_comment/save',
str,
function(data){
alert(data);
});
}}
Backend is done using Django and this is the return statement
data=simplejson.dumps(data)
return HttpResponse(data, mimetype='application/json')
The referral url is say "/xyz".
The thing is, after the form gets submitted, it is being automatically redirect to the "/status_comment/save" page instead of remaining on the same page.
I tried the get method and it works fine but not the POST method.
I tried debugging it, so changed the url in post call to the referral url, then it refreshs the page instead of doing nothing.
Also the alert() command inside the function above doesnt work, so its probably not being entered into.
Interesting thing I have noticed, when looking at the web developer console, the Initiator for the POST call in this page is being displayed as "Other" while the initiator for GET call and POST call (in other pages, where its working) is "jquery-1.8.0.min.js:2"
Any thoughts? Thanks...
First you really shouldn't try to capture the enter if you can avoid it. Use the submit binding. It makes everything more obvious and easier for your fellow developers (I bet I am not the only one who thought "What the heck is KeyCode 13?").
I'm wondering if perhaps being more explicit might help. Have you tried calling preventDefault and stopImmediatePropagation?
$('#form1').submit(function(evt) {
evt.preventDefault();
evt.stopImmediatePropagation();
// serialize and be AJAXy yada yada yada
If that doesn't work, or for some reason you prefer to handle capturing enter on your own, then you might want to have the above code in addition to your keydown handler. So it would be:
<input type="text" name="new_comment" id="new_comment" onkeydown="post_comment(event,'13')" >
...
$('#form1').submit(function(event) {
event.preventDefault();
event.stopImmediatePropagation();
}
function post_comment(event,item_id)
{
event.preventDefault();
event.stopImmediatePropagation();
var keyCode = ('which' in event) ? event.which : event.keyCode;
if(parseInt(keyCode)==13 && event.shiftKey!=1)
{
var str = $('#form1').serialize(); // Gets all the filled details
$.post('/status_comment/save',
str,
function(data){
alert(data);
});
}
}
Start by getting rid of the onkeydown attribute from the input:
<form method="post" id="form1" name="form1" action="/status_comment/save">
//Some text inputs
<input type="text" name="new_comment" id="new_comment" />
</form>
And then simply subscribe to the .submit() event of this form using jquery and perform the AJAX request in there. Don't forget to return false from it to ensure that the default action is canceled and the browser stays on the same page:
$('#form1').submit(function() {
var str = $(this).serialize(); // Gets all the filled details
$.post(this.action, str, function(data) {
alert(data);
});
return false; // <!-- that's the important part
});

Jquery Ajax autocomplete: action of a controller not available

I was trying to create an autocomplete field using jquery and ajax. I tried the code below but it gives me an error that the action of the controller is not available. Here is the code in my exeternal .js file:
$(function () {
$("#inputfield").autocomplete({
source: '<g:createLink controller="fruit" action="findFruit">'
});
});
And this is the code from my Fruit controller:
def findFruit = {
def fruitsearch= Fruit.withCriteria {
ilike 'fruit', params.term + '%'
}
render (fruitsearch?.'fruit' as JSON)
}
I used firebug to see whats going on, and when I tried an input on the texfield, it says that the action findFruit is not available.
Am I missing something? Or is their something wrong on the code? Thanks
Since your js code is evaluated from an external js file you should try using pure js code instead of grails tags (coz they won't work)
Try using relative path like:
$( "#inputfield" ).autocomplete({
source: '/app-name/controller/action'
});
see if this works.

Resources