ASP Classic loses URL parameters from Ajax submitted data [duplicate] - ajax

I'm implementing Google's Instant Search in my application. I'd like to fire off HTTP requests as the user types in the text input. The only problem I'm having is that when the user gets to a space in between first and last names, the space is not encoded as a +, thus breaking the search. How can I either replace the space with a +, or just safely URL Encode the string?
$("#search").keypress(function(){
var query = "{% url accounts.views.instasearch %}?q=" + $('#tags').val();
var options = {};
$("#results").html(ajax_load).load(query);
});

Try encodeURIComponent.
Encodes a Uniform Resource Identifier (URI) component by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two "surrogate" characters).
Example:
var encoded = encodeURIComponent(str);

encodeURIComponent works fine for me. we can give the url like this in ajax call.The code shown below:
$.ajax({
cache: false,
type: "POST",
url: "http://atandra.mivamerchantdev.com//mm5/json.mvc?Store_Code=ATA&Function=Module&Module_Code=thub_connector&Module_Function=THUB_Request",
data: "strChannelName=" + $('#txtupdstorename').val() + "&ServiceUrl=" + encodeURIComponent($('#txtupdserviceurl').val()),
dataType: "HTML",
success: function (data) {
},
error: function (xhr, ajaxOptions, thrownError) {
}
});

Better way:
encodeURIComponent escapes all characters except the following: alphabetic, decimal digits, - _ . ! ~ * ' ( )
To avoid unexpected requests to the server, you should call encodeURIComponent on any user-entered parameters that will be passed as part of a URI. For example, a user could type "Thyme &time=again" for a variable comment. Not using encodeURIComponent on this variable will give comment=Thyme%20&time=again. Note that the ampersand and the equal sign mark a new key and value pair. So instead of having a POST comment key equal to "Thyme &time=again", you have two POST keys, one equal to "Thyme " and another (time) equal to again.
For application/x-www-form-urlencoded (POST), per http://www.w3.org/TR/html401/interac...m-content-type, spaces are to be replaced by '+', so one may wish to follow a encodeURIComponent replacement with an additional replacement of "%20" with "+".
If one wishes to be more stringent in adhering to RFC 3986 (which reserves !, ', (, ), and *), even though these characters have no formalized URI delimiting uses, the following can be safely used:
function fixedEncodeURIComponent (str) {
return encodeURIComponent(str).replace(/[!'()]/g, escape).replace(/\*/g, "%2A");
}

I'm using MVC3/EntityFramework as back-end, the front-end consumes all of my project controllers via jquery, posting directly (using $.post) doesnt requires the data encription, when you pass params directly other than URL hardcoded.
I already tested several chars i even sent an URL(this one http://www.ihackforfun.eu/index.php?title=update-on-url-crazy&more=1&c=1&tb=1&pb=1) as a parameter and had no issue at all even though encodeURIComponent works great when you pass all data in within the URL (hardcoded)
Hardcoded URL i.e.>
var encodedName = encodeURIComponent(name);
var url = "ControllerName/ActionName/" + encodedName + "/" + keyword + "/" + description + "/" + linkUrl + "/" + includeMetrics + "/" + typeTask + "/" + project + "/" + userCreated + "/" + userModified + "/" + status + "/" + parent;; // + name + "/" + keyword + "/" + description + "/" + linkUrl + "/" + includeMetrics + "/" + typeTask + "/" + project + "/" + userCreated + "/" + userModified + "/" + status + "/" + parent;
Otherwise dont use encodeURIComponent and instead try passing params in within the ajax post method
var url = "ControllerName/ActionName/";
$.post(url,
{ name: nameVal, fkKeyword: keyword, description: descriptionVal, linkUrl: linkUrlVal, includeMetrics: includeMetricsVal, FKTypeTask: typeTask, FKProject: project, FKUserCreated: userCreated, FKUserModified: userModified, FKStatus: status, FKParent: parent },
function (data) {.......});

use jQuery.param().....
Description: Create a serialized representation of an array, a plain object, or a jQuery object suitable for use in a URL query string or Ajax request. In case a jQuery object is passed, it should contain input elements with name/value properties.

try this one
var query = "{% url accounts.views.instasearch %}?q=" + $('#tags').val().replace(/ /g, '+');

Related

If one of my POST Parameters contains character '+' it gets converted to ' ' instead of passing it correctly

When passing the id "vpzYeZkOy4HpNo + DLBb4WQ ==" disappears "+" in the body of id.
Can you try passing + as a URL encoded value => %2B?
Edit: #David beat me to it

ptor.findElements always returns true

I have the following Code, which never runs the error portion
ptor.findElements(protractor.By.css(elementCss)).then(function (elems) {
element = elems;
elementFound = true;
// if element.all(...).count()
console.log("inside then clause , Element Found");
}, function (err) {
console.error("waiting for element( " + elementCss + " ) to be found " + currentCount + "/" + timeout);
}); //ptor.findElement
even if the elementCss ='abc', some junk value, it always resolve into then clause
and not into reject/error as that is a junk css name.
findElement on the other hand behaves as expected. am i missing something here ?
The API for findElement returns en error if the element is not found by the given selector.
The API for findElements is to return an empty list if the selector does not match any element.
From findElement documentation :
If the element cannot be found, a bot.ErrorCode.NO_SUCH_ELEMENT result will be returned by the driver

How to deal with randomly generated post request parameters in Jmeter Scripts?

I am writing jmeter scripts for my web-based application. I am using firefox-firebug to watch POST request parameters. I could successfully write login page scripts because it had only "username" and "password" parameters.
But, after logging into the web application, I realized that, there are randomly generated required parameters which are sent along with the post request.
So, I am trying to find out the way to deal with these parameters.
Please let me know, if you have dealt with this situation.
Example: These are my post request parameters:
externalId=971&submit.go=Go&submit.go=&013f57c77c2a%3A6eed%3A1b320be7=105f230e-9f86-40f8-9473-215975812128
Where **013f57c77c2a%3A6eed%3A1b320be7** parameter and it's value are generated differently each time.
I don't know how to define this parameter.
I found an answer. You can use List Extractor(Regular Expression Extractor).
You can define any pattern as per your criteria.
for example regex patter is : input type="hidden" name="([^"]+?)" value="([^"]+?)"
Step2) Use Beanshell pre processor with this script.
log.info("=====================");
count = Integer.valueOf (vars.getObject("hiddenList_matchNr") ) ;
log.info("Number of hidden fields in previous sampler: " + count);
for (i=1; i <= count; i++) {
paramName = vars.getObject("hiddenList_"+ i + "_g1");
paramVal = vars.getObject("hiddenList_"+ i + "_g2");
log.info("Adding request parameter: " + paramName + " = " + paramVal);
sampler.addArgument(paramName, paramVal);
}
log.info("=====================");

Firefox & AJAX oddity: DOM replacements not working again after just working

these are the two functions (externally loaded):
function replaceText(element, text) {
if (element != null) {
clearText(element);
var newNode = document.createTextNode(text);
element.appendChild(newNode);
}
}
function replaceImage(element, maker, imageState) {
replaceText(element, "replacing image " + maker + " with " + imageState + " version");
var imagePath = "_img/coffeeMaker_";
if (maker != null)
{
document.getElementById("coffeeMakerImg"+ maker).src = imagePath + imageState + ".png";
}
}
now here's the part that calls these functions. *notice that the replaceText() is called from within replaceImage()
replaceText(cmStatus_01, "BREWING " + name + "'s " + size + " " + beverage);
replaceImage("feedback", "01", "full");
document.forms[0].reset();
okay. now here's the kicker: the FIRST replaceText() works fine in ALL browsers. the replaceImage() fails ONLY in Firefox which CONTAINS A CALL TO replaceText() that only JUST worked as advertised!! i could see how i might have screwed up the image replacement (even though i copy/pasted it from another working project that DOES replace the image in FF...so weird...), but i do NOT see how the replaceText() can fail: it just worked!
so: whaaaaat!? i'm thinking its some kind of scope issue, but i'm stumped as to why.
totally stumped. forehead really sore...
thank for your time and help. i'm praying this isn't something really retarded...
WR!
PS: i'm also confused why, if i remove the quotes from the element name in the replaceImage() call, it breaks; but it works in the replaceText() call without brackets just fine...
okay. i figured it out. the problem was actually what i was passing into the functions:
cmStatus_01 was NOT the actual ID of the div. it was evaluated earlier like so:
var cmStatus_01 = document.getElementById('divName');
but i WAS passing the divName into the replaceImage() function and it was expecting the evaluted version of it, like cmStatus_01. so it broke.
so when i actually retooled the function so i was ONLY passing divName, it obviously worked. this is the retool:
function replaceNodeText(id, newText)
{
var node = document.getElementById(id);
while (node.firstChild)
{
node.removeChild(node.firstChild);
}
node.appendChild(document.createTextNode(newText));
}
project deadline too tight! it's making my brain fail. :P
also: apologies for not posting where the variables came from. that would have helped enormously, i'm sure and i don't know why i didn't think to post them as well.
thank you for your patience and your time.
WR!

setAttribute, onClick and cross browser compatibility

I have read a number of posts about this but none with any solid answer. Here is my code:
// button creation
onew = document.createElement('input');
onew.setAttribute("type", "button");
onew.setAttribute("value", "hosts");
onew.onclick = function(){fnDisplay_Computers("'" + alines[i] + "'"); }; // ie
onew.setAttribute("onclick", "fnDisplay_Computers('" + alines[i] + "')"); // mozilla
odiv.appendChild(onew);
Now, the setAttribute() method (with the mozilla comment) works fine in mozilla but only if it comes AFTER the line above it. So in other words it seems to just default to whichever gets set last. The .onclick method (with the ie comment) does not work in either case, am I using it incorrectly?
Either way I can't find a way to make this work at all in IE, let alone in both. I did change the function call when using the .onclick method and it worked fine using just a simple call to an alert function which is why I believe my syntax is incorrect.
Long story short, I can't get the onclick parameter to work consistently between IE/Mozilla.
-- Nicholas
onew.setAttribute("type", "button");
Never use setAttribute on HTML documents. IE gets it badly wrong in many cases, and the DOM-HTML properties are shorter, faster and easier to read:
onew.type= 'button';
onew.onclick = function(){fnDisplay_Computers("'" + alines[i] + "'"); }; // ie
What is ‘alines’? Why are you converting it to a string and surrounding it with single quotes? It looks like you are trying to do something heinous involving evaluating code in a string (which is what you're doing below in the ‘onew.setAttribute’ version). Evaluating JavaScript code in strings is almost always the Wrong Thing; avoid it like the plague. In the above case, IE should do the same as Firefox: it shouldn't work.
If ‘alines[i]’ is a string, I guess what you're trying to do is make it remember that string by constructing a code string that will evaluate in JavaScript to the original string. But:
"'" + alines[i] + "'"
is insufficient. What happens if ‘alines[i]’ has an apostrophe in, or a backslash?
'O'Reilly'
you've got a syntax error and possible security hole. Now, you could do something laborious and annoying like:
"'" + alines[i].split('\\').join('\\\\').split("'").join("\\'") + "'"
to try to escape the string, but it's ugly and won't work for other datatypes. You could even ask JavaScript to do it for you:
uneval(alines[i])
But not all objects can even be converted to evaluatable JavaScript source strings; basically the entire approach is doomed to failure.
The normal thing to do if you just want to have the onclick callback call a function with a parameter is to write the code in the straightforward way:
onew.onclick= function() {
fnDisplay_Computers(alines[i]);
};
Generally this will work and is what you want. There is, however, a slight wrinkle which you may have hit here, which could be what is confusing you into considering the wacky approach with the strings.
Namely, if ‘i’ in this case is the variable of an enclosing ‘for’ loop, the reference to ‘alines[i]’ won't do what you think it does. The ‘i’ will be accessed by the callback function when the click happens — which is after the loop has finished. At this point the ‘i’ variable will be left with whatever value it had at the end of the loop, so ‘alines[i]’ will always be the last element of ‘alines’, regardless of which ‘onew’ was clicked.
(See eg. How to fix closure problem in ActionScript 3 (AS3) for some discussion of this. It's one of the biggest causes of confusion with closures in both JavaScript and Python, and should really be fixed at a language level some day.)
You can get around the loop problem by encapsulating the closure in its own function, like this:
function callbackWithArgs(f, args) {
return function() { f.apply(window, args); }
}
// ...
onew.onclick= callbackWithArgs(fnDisplay_Computers, [alines[i]]);
And in a later version of JavaScript, you'll be able to say simply:
onew.onclick= fnDisplay_Computers.bind(window, alines[i]);
If you would like to be able to use ‘Function.bind()’ in browsers today, you can get an implementation from the Prototype framework, or just use:
if (!('bind' in Function.prototype)) {
Function.prototype.bind= function(owner) {
var that= this;
var args= Array.prototype.slice.call(arguments, 1);
return function() {
return that.apply(owner,
args.length===0? arguments : arguments.length===0? args :
args.concat(Array.prototype.slice.call(arguments, 0))
);
};
};
}
I usually use something like:
onew.onclick = new Function("fnDisplay_Computers('" + alines[i] + "')");
this should work both in IE e Firefox.
Use the addEventListener() function with "click" for the type argument for Mozilla-based browsers, and attachEvent() function with "onclick" as the sEvent argument for IE; I find it best to use a try/catch statement, for example:
try {
onew.attachEvent("onclick", //For IE
function(){fnDisplay_Computers("'" + alines[i] + "'"); });
}
catch(e) {
onew.addEventListener("click", //For Mozilla-based browsers
function(){fnDisplay_Computers("'" + alines[i] + "'"); },
false);
}
I think #3 protesteth too much. In a lot of situations I'm building a table dynamically and need to pass parameters to the callback function. It isn't a typesafe issue since my variable parm is an integer index to the table row in question. Here's code with both a variable and fixed parameter that seems to be cross-browser compliant:
for (i = 0; i < arrTableData.length; i++) {
eleTR = objTable.insertRow(i + 1);
cell = eleTR.insertCell(0);
cell.width = "21";
var myElement = document.createElement('img');
myElement.setAttribute('src', 'images/button_down.gif');
myElement.setAttribute('alt', 'Move item down');
myElement.onclick = new Function('moveItem(' + i + ',0)');
cell.appendChild(myElement);
}

Resources