Unable to get text from element in nightwatchjs - nightwatch.js

I'm currently using nightwatchjs (latest version) and I'm trying to get the text of the element below ("Welcome to the newest....."), but I can't seem to find it.
Currently, I'm using the following code;
browser.getText('css selector', '.bfs-details__about-seller__why-buy p', function(result) {
console.log('element text = ', result.value);
});
But I get an empty value.
Am I missing something obvious here?
thanks

As I see it, the problem is not the selector but how you try to log it.
Try console.log('element text = ' + result.value);
Or as an alternative (thats how I do it):
browser.getText('css selector', '.bfs-details__about-seller__why-buy p', function(result) {
myValue = result.value;
});
browser.perform(function () {
console.log(myValue)
});
Why use perform: Nightwatch API Perform

Related

Posting an array using Titanium HttpClient

I am trying to post to a webservice using Titanium HttpClient like so:
var non_data = {
user_id: Facebook_ID,
"friends_ids[0]":friendIds[0],
"friends_ids[1]":friendIds[1]
};
var non_xhr = Ti.Network.createHTTPClient({
onload: function(){
Titanium.API.info('Status: ' + this.status);
Titanium.API.info('ResponseText: ' + this.responseText);
Titanium.API.info('connectionType: ' + this.connectionType);
Titanium.API.info('location: ' + this.location);
alert("Get_Non_Friends response: " +this.responseText);
}
});
non_xhr.open('POST', myURL);
non_xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
non_xhr.send(non_data);
But it doesn't seem to be getting the array elements right. Can anyone tell how to post and array of params.
Also I found a post on TIMOB that says to do something like this, which I am currently trying:
non_xhr.open('POST', myURL);
//non_xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
non_xhr.send('user_id=someData&friends_ids[0]=someData);
Can anyone tell me the best approach for this problem?
The problem seems to be with the send method. The send method should be something like this
non_xhr.send({paramName : non_data});
The paramName is the name which is required by the web service. Ex
non_xhr.send({
file: abc.jpg
});
Also its advised to have onerror method too just like onload method.

jQuery Ajax - Cant parse json?

I got a very strange problem, I thought this worked before but it doesn't any more. I dont even remember changing anything. I tried with an older jQuery library.
I got an error that says: http://i.imgur.com/H51wG4G.png on row 68: (anonymous function). which refer to row 68:
var jsondata = $.parseJSON(data);
This is my ajax function
I can't get my alert to work either because of this error. this script by the way is for logging in, so if I refresh my website I will be logged in, so that work. I also return my json object good as you can see in the image. {"success":false,"msg":"Fel anv\u00e4ndarnamn eller l\u00f6senord.","redirect":""}
When I got this, I will check in login.success if I got success == true and get the login panel from logged-in.php.
$('#login_form').submit(function()
{
var login = $.ajax(
{
url: '/dev/ajax/trylogin.php',
data: $(this).serialize(),
type: 'POST',
}, 'json');
login.success(function(data)
{
var jsondata = $.parseJSON(data);
console.log(jsondata);
if(jsondata.success == true)
{
$.get("/dev/class/UI/logged-in.php", function(data) {
$(".login-form").replaceWith(data);
});
}
else
{
alert(jsondata.msg);
$('#pwd').val('');
}
});
return false;
});
Thank you.
If the response you have showed in the attached screenshot is something to go by, you have a problem in your PHP script that's generating the JSON response. Make sure that thePHP script that's generating this response (or any other script included in that file) is not using a constant named SITE_TITLE. If any of those PHP files need to use that constant, make sure that that SITE_TILE is defined somewhere and included in those files.
What might have happened is that one of the PHP files involved in the JSON response generation might have changed somehow and started using the SITE_TITLE costant without defining it first, or without including the file that contains that constant.
Or, maybe none of the files involved in the JSON generation have changed, but rather, your error_reporting settings might have changed and now that PHP interpreter is outputting the notice level texts when it sees some undefined constant.
Solving the problem
If the SITE_TITLE constant is undefined, define it.
If the SITE_TITLE constant is defined in some other file, include that file in the PHP script that's generating the response.
Otherwise, and I am not recommending this, set up your error_reporting settings to ignore the Notice.
Your response is not a valid JSON. You see: "unexpected token <".
It means that your response contains an unexpected "<" and it cannot be converted into JSON format.
Put a console.log(data) before converting it into JSON.
You shoud use login.done() , not login.success() :)
Success is used inside the ajax() funciton only! The success object function is deprecated, you can set success only as Ajax() param!
And there is no need to Parse the data because its in Json format already!
jQuery Ajax
$('#login_form').submit(function()
{
var login = $.ajax(
{
url: '/dev/ajax/trylogin.php',
data: $(this).serialize(),
type: 'POST',
}, 'json');
login.done(function(data)
{
var jsondata = data;
console.log(jsondata);
if(jsondata.success == true)
{
$.get("/dev/class/UI/logged-in.php", function(data) {
$(".login-form").replaceWith(data);
});
}
else
{
alert(jsondata.msg);
$('#pwd').val('');
}
});
return false;
});

KnockoutJS with IE8, occasional problems with Stringify?

A number of our users are still on IE8. Some of them occasionally are reporting problems when trying to post data to our servers (via a big button labeled "SAVE").
There is a script error that IE8 shows, which is: Unexpected call to method or property access, always pointing to the same line in the KnockoutJS 2.2.0 (debug, for now) library, line 450, which is as follows:
return JSON.stringify(ko.utils.unwrapObservable(data), replacer, space);
The method in my code that is at the root of the stack trace where this happens is this:
self.saveSingle = function (onSuccess, onFailure) {
ko.utils.arrayForEach(self.days(), function (day) {
day.close();
});
var jsonData = ko.toJSON(self);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: applicationLocation + "/api/assignmentapi/save",
data: jsonData,
success: function (data) {
self.status(data.Status);
self._isDirty(false);
ko.utils.arrayForEach(self.days(), function (day) {
day.clean();
});
if (onSuccess)
onSuccess();
},
error: function (data) {
onFailure();
},
dataType: "json"
});
};
We do strip out a number of properties that are not necessary to our POST as we convert the object to JSON, using this approach: http://www.knockmeout.net/2011/04/controlling-how-object-is-converted-to.html
OurType.prototype.toJSON = function () {
var copy = ko.toJS(this);
delete copy.someUnneededProperty1;
delete copy.someUnneededProperty2;
delete copy.someUnneededProperty3;
delete copy.someUnneededProperty4;
return copy;
}
When it fails, it fails consistently on the line
var jsonData = ko.toJSON(self);
Now here comes the real mess:
It's not consistently happening
It doesn't happen to all IE8 users
We can't consistently reproduce it
The structure of our model that we're serializing doesn't appear matter
The jscript.dll is the current version for IE8
I was also experiencing this issue. Digging deeper I found a few things:
It was only failing occasionally, I found this by running the code in the console
The code in the data-bind was trowing an exception except the message was being swallowed due to IE8 gobbling up the message when using a try {} finally {} block (without catch).
Removing the try finally revealed a cannot parse bindings message.
When I started to get close to figuring out the issue (digging deep into the knockout code) it seemed to disappear in front of my eyes. This is the section of code it was failing on, catching the exception at the end of the code:
ko.utils.extend(ko.bindingProvider.prototype, {
'nodeHasBindings': function(node) {
switch (node.nodeType) {
case 1: return node.getAttribute(defaultBindingAttributeName) != null; // Element
case 8: return ko.virtualElements.virtualNodeBindingValue(node) != null; // Comment node
default: return false;
}
},
'getBindings': function(node, bindingContext) {
var bindingsString = this['getBindingsString'](node, bindingContext);
return bindingsString ? this['parseBindingsString'](bindingsString, bindingContext, node) : null;
},
// The following function is only used internally by this default provider.
// It's not part of the interface definition for a general binding provider.
'getBindingsString': function(node, bindingContext) {
switch (node.nodeType) {
case 1: return node.getAttribute(defaultBindingAttributeName); // Element
case 8: return ko.virtualElements.virtualNodeBindingValue(node); // Comment node
default: return null;
}
},
// The following function is only used internally by this default provider.
// It's not part of the interface definition for a general binding provider.
'parseBindingsString': function(bindingsString, bindingContext, node) {
try {
var bindingFunction = createBindingsStringEvaluatorViaCache(bindingsString, this.bindingCache);
return bindingFunction(bindingContext, node);
} catch (ex) {
throw new Error("Unable to parse bindings.\nMessage: " + ex + ";\nBindings value: " + bindingsString);
}
}
});
But yea, it stopped becoming reproducible so I came up with a hack that I tested and works earlier, just retrying the data parsing. So this:
data-bind="value: ko.computed(function(){return ko.toJSON(appViewModel.model()[0])})"
Became this:
data-bind="value: ko.computed(function(){while (true) { try { var json = ko.toJSON(appViewModel.model()[0]); return json; }catch(e){}}})"
Yes, it's very yucky, but it seems to do the trick until our users no longer need IE8 or the Knockout issue is fixed.
I have no idea if this will fix it, but you can use the mapping plugin to go between JS and JSON:
var mapping = {
'ignore': ["propertyToIgnore", "alsoIgnoreThis"]
}
var viewModel = ko.mapping.toJS(data, mapping);
Taken from my answer to this question
I'd give this a try and see if it helps, as there's nothing obviously wrong in your approach.
Are you sure it's IE8 users who are hitting the issue? IE7 does not support JSON.stringify. You'll need to include the json2.js library to support IE7 and lower.

twitter bootstrap typeahead 2.0.4 ajax error

I have the following code which definitely returns a proper data result if I use the 2.0.0 version, but for some reason bootstrap's typeahead plugin is giving me an error. I pasted it below the code sample:
<input id="test" type="text" />
$('#test').typeahead({
source: function(typeahead, query) {
return $.post('/Profile/searchFor', { query: query }, function(data) {
return typeahead.process(data);
});
}
});
When I run this example I'm getting a jQuery bug that says the following:
**
item is undefined
matcher(item=undefined)bootst...head.js (line 104)
<br/>(?)(item=undefined)bootst...head.js (line 91)
<br/>f(a=function(), b=function(), c=false)jquery....min.js (line 2)
<br/>lookup(event=undefined)bootst...head.js (line 90)
<br/>keyup(e=Object { originalEvent=Event keyup, type="keyup", timeStamp=145718131, more...})bootst...head.js (line 198)
<br/>f()jquery....min.js (line 2)
<br/>add(c=Object { originalEvent=Event keyup, type="keyup", timeStamp=145718131, <br/>more...})jquery....min.js (line 3)
<br/>add(a=keyup charCode=0, keyCode=70)jquery....min.js (line 3)
<br/>[Break On This Error]
<br/>return item.toLowerCase().indexOf(this.query.toLowerCase())**
Any thoughts? ... The same code works in the 2.0.0 version of the plugin, but fails to write to my knockout object model.
THIS IS WORKING TYPEAHEAD CODE FOR the 2.0.0 version:
var searchFunction = function(typeahead, query) {
$.ajax({
url: "/Profile/searchFor?tableName=" + tableName + "&query=" + query + "&extendedData=" + $("#" + extendedData).val(),
success: function(data) {
if (data.errorText != null) {
toggleLoading("false");
showDialog(data.errorText, "Error");
return;
}
var result = data.results.split("::");
typeahead.process(result);
},
select: function(event, ui) {
}
});
}
$("#" + inputBoxId).typeahead({
source: searchFunction,
onselect: function(obj) {
}
});
1) Bootstrap typeahead v2.0.2 solution
have a look at this pull request, it looks like what you're looking for (its a fork from bootstrap typeahead v2.0.2).
I use it myself and it's working :)
2) Bootstrap typeahead v.2.1.0-work in progress solution
Also you can try this solution. I just changed my project to use this one, becouse it's gonna be supported in future versions and it looks cleaner :)
In my case:
$("#typeahead").typeahead({
source: function(query, process) {
$.post('url_path', { q: query, limit: 4 }, function(data) {
process(data);
}); // end of post
}
});
Where script url_path requiers 2 arguments q (string) and limit (results limit) and returns json response (array):
Example response to query i with limit 4:
["Eminem","Limp Bizkit","Rihanna","Will Smith"]
For people trying to generate the JSON data (without using php json_encode) and wondering why bootstrap-typeahead fork by Terry Rosen won't work on ajax call
The format of the returned JSON data has to be of the form :-
[{"id":"1","name":"Old car"},{"id":"2","name":"Castro trolley car"},{"id":"3","name":"Green classic cars"},{"id":"4","name":"Cars parked in Antique Row"}]
Note the quotes
Having spent the whole day trying to figure out what the problem was, i thought it would be wise to post it here. Maybe, my understanding of JSON was wrong, but firebug shows the returned data as valid JSON even if the id and name fields are not quoted. Moreover, the response header should be set to 'application/json'. Hope this helps someone.
On version 2.0.4 typeahead is buggy and does not accept functions as source, only arrays. I upgraded to 2.1 and it works as expected.

Ajax prototype to load page then update hash

I have 3 page with different concept/layout/animation.
I'm using prototype & script.aculo.us
I have this in my navigation:
<ul>
<li>PAGE1</li>
<li>PAGE2</li>
</ul>
and this is in my js:
windows.location.hash: 'web';
function showPage() {
startloading();
var url: '/localhost/page2'+web;
new Ajax.Updater('maincontent', 'page2', { method: 'get' });
finishloading();
}
the question & problem is:
Why in windows location hash is still: /localhost/page1/#page2 with or without if I use var url?
All the animation in page 2 doesn't work, because I didn't put the header, but if put I it, I got double header and still the animation won't work either.
Can anybody give me the solution?
Thank you very much.
In your code
var url: '/localhost/page2'+web;
line throws error so hash cannot be changed. Fix it to
var url = '/localhost/page2'+web;
then it should work.
The correct way to update your hash is:
window.location.hash = '#'+yourValue;
Hard to tell what exactly you're trying to do with your function but there's a few things that are clearly a bit wrong.
function showPage(var) {
startloading();
var url: '/localhost/page'+var;
new Ajax.Updater('maincontent', url, { method: 'get' });
finishloading();
}
depending on what you're actually doing its fairly likely you would probably want something more like this:
function showPage(var) {
var url = '/localhost/page'+var;
new Ajax.Updater('maincontent', url, { method: 'get' ,
onCreate: function(){
startloading();
},
onComplete: function(){
finishloading();
}
});
}
Thats complete guesswork though, if you can provide more detail i can help more.

Resources