In this case, Let's take Google as example:
The code is JScript .NET, which is basically a .NET version of Javascript. Regardless of language, Anyone with appending type of skill can answer my question.
This code is used in Fiddler(It's a Man-in-the-middle proxy)
if (oSession.uriContains("&q=")) // oSession is a Fiddler object session // uriContains() function, checks for case-insensitive string from the URI
{
var str = oSession.fullUrl;
var sAppend = "test1+test2+test3";
if (!oSession.uriContains(sAppend))
{
oSession.fullUrl = str.replace( "&q=","&q="+sAppend);
}
}
For those who are confused, It says, If &q= is present in the URI, replace/append &q= with &q=test1+test2+test3
Problem: It appends test1+test2+test3 instantly, when it sees &q= in the URL.
Basically, how do I make it wait until I click the submit/search button
Thank you.
Identifying your problem
I'm assuming:
you want to use Fiddler for your solution (since you're already using it)
you've figured out how to alter the request URI (as shown in your example), and your problem is that you want to target only those requests where the "search" button was clicked, not auto-submitted searches
Isolating those requests that stem from the search button being pressed on google is not straightforward, but I came up with a hack that seems to work. Basically, the oq (original query) get parameter is only added when the user explicitly hits button/enter key, so we test for its presence in order to identify such requests.
Solution
In your OnBeforeRequest method in Fiddler Handlers class (where you're already putting your code), we'll:
Check that request is to www.google.com and contains q parameter
If true, log (in the fiddler log) that a query was submitted to google.com &
highlight request in pink
Check that request contains oq parameter (original query)
If true, log alert that submit button was pressed & highlight request in Light Forest Green
Code
if(oSession.HostnameIs('www.google.com') && oSession.uriContains("&q=")){
FiddlerApplication.Log.LogString('query submitted to google.com...');
oSession['ui-backcolor'] = 'pink'; //highlight this request
//test for original query
if(oSession.uriContains('&oq=')){
FiddlerApplication.Log.LogString('SUBMIT BUTTON OR ENTER CLICKED (probably)');
oSession['ui-backcolor'] = '#369369'; //highlight in Light Forest Green
//whatever sort of request manipulation you want to do here...
}
}
Other notes:
I'm assuming you want to prepend your query string to the existing q value, i.e. q=Hello will become q=test1+test2+test3Hello. If you want to replace it you need More Regex.
Depending on your needs, Naomi or Ahmed's request may be better (it's in-browser, not in fiddler).
Modifying a request or response in Fiddler
Understanding Fiddlerscript
Well in Javascript you can bind actions to events. In your case the event is the submit of the form For example:
function addEventsToHTML(){
var form1 = document.getElementById('form1');
form1.onsubmit = submitHandler;
function submitHandler(){
alert("You just submit: "+this.email.value);
}
}
If you want to bind it on click you can do:
object.onclick=function(){myScript};
Or
object.addEventListener("click", myScript);
Note: The addEventListener() method is not supported in Internet Explorer 8 and earlier versions.
Related
I have a JavaScript function :
function post(aAction) {
var form = document.createElement("form");
form.action=aAction;
document.body.appendChild(form);
form.submit();
alert(form.action);
}
( I'm an experienced developer but not much experience with JScript - lifted that post() function from some website. )
I am passing this string into the function: A URL with query information:
http://testServer:3072/aQuerySite.dll/GetErrors?server=server1:5678
This URL returns a page listing error messages from the specified server: "server1:5678" - an argument passed to a server side query as
server=server1:5678
in the URL.
If I paste that URL directly into a browser and post it, the correct page with appropriate data is returned, and the browser address shows the complete URL as it was sent.
But when I pass the URL into my function, I get back a correctly formatted page but no records, and the browser address shows the URL truncated after the ? token : http://testServer:3072/aQuerySite.dll/GetErrors? The page returns showing no records because the query parameters after ? never got to the server for evaluation - query runs looking for nothing.
alert(form.action) in the function, which I added for debugging, shows the correct URL with query arguments, as does my debugger (WebStorm) and as mentioned, if I hit the URL directly from the browser, I get the correct result. I can only conclude that my URL is getting truncated in the form.submit() call.
This happens in IE, FireFox and Chrome. I also tried using ? for "?" - same result.
Why is this happening? How can I fix it?
It seems like you're trying to use a newly created form to redirect a user through its submission.
That is not necessary, as you can simply redirect the user using the following:
window.location = 'your_url';
In your case, you say that the querystring is being replaced with a simple ?.
That's because you created a form, and this form uses GET to post its data.
So if the form action is https://www.stackoverflow.com, the query string will be added with a interrogation following by the key/value pairs.
Let's suppose you have a form with two inputs named a and b, when you submit them, the query string would look like this:
https://www.stackoverflow.com?a=zzz&b=zzz
If you simply put this url in your form action, it will replace the query string with its own data when you submit it. Since your form has no named inputs, the query string will be empty, that's why you have an empty ? after the url.
This topis is already present in other posts but none of the solutions mentioned worked for me so here I am, hoping someone can point me in the right direction.
Basically, I have an application with Primefaces 3.5 with 2 commandButtons that execute backing bean methods to generate two different reports as an output stream (no GET available). One of this report is generated as attachment while the other one should be displayed in another tab. Both in the same form.
My problem comes with the report generated in a separate tab: since the reports share the same form, I cannot use target=blank in the form definition and since I have to do validations in my backing bean, I must show possible error messages in the main tab, opening the new one only in case everything goes smoothly.
I tried the following js in the form page:
function test() {
document.getElementById("formRep3_1").target = '_blank';
}
called by the bean with
RequestContext.getCurrentInstance().execute("test()");
after validation successful. But it doesn't work.
I also tried setting an oncomplete="test()" on report button, slightly modifying the js like this:
function test() {
var v = '<h:outputText value="#{repReqStatus.resultCheck}" />';
if (v.value == "success") {
document.getElementById("formRep3_1").target = '_blank';
}
else {
alert('no');
}
}
but it seems the oncomplete doesn't get called at all! Not even if I do another check like
oncomplete="if (!args.validationFailed){test()}"
So yeah, I'm lost. Any help is really appreciated.
Thanks!
You can't change the link's target during invoking the link's action. It's too late.
Your best bet is to keep out the target="_blank" and instead invoke a JavaScript window.open() on the desired URL. You can store the PDF report in session, or prepare request parameters for the URL so that it can generate the desired PDF report based on those request parameters.
Hashchange is for when
index.php
Changes to, say
index.php#my-hash
i.e.
$(window).bind('hashchange', function() {
// do stuff
});
But is there an event for when there is a ? after the url, i.e.
index.php?id=foo&something_else=bar...
Edit
Okay, it's when I submit a form. I submit the form and then the URL changes to
index.php?id=blah#my-hash
However I tried listening for a) the hashchange and b) the form submit:
$('form').submit(function() {
go_to_signup_form();
});
Neither of which work (I think the page is refreshing?). I can't alter the php too much because it's part of a cms and I don't want to break anything that's happening in say, the controller class so I would rather just try to see when:
index.php
changes to
index.php?id=blah#my-hash
Edit #2
Thanks everyone for the feedback, got it working with:
if (url.indexOf("?") !== -1) {
go_to_signup_form();
}
Nope, that is because the parameters (?foobar) aren't usually used for client-side code. Linking to a new parameter on the same url (index.php -> index.php?foo=bar) makes your browser load a new page, while adding a hash (index.php -> index.php#foo=bar) does not make the browser transmit any data to the server.
The hash section of a url, it's a client-side piece of data. As such, it is useful to have a change event listener for it.
Try these in your console, on a random site that doesn't have a hash in the url yet:
window.location.href += "?test"
and:
window.location.href += "#test"
You will see that the first one will reload the page (Send a new HTTP request), the second one will not appear to do anything.
To prevent a form from submitting:
$('#target').submit(function() {
// Your onclick code here
return false; // Do not submit.
});
The problem with that is that the "hashchange" (technically it means navigation to an anchor) is an entirely client-sided operation. But an URL with arguments (the "?" operator) is fulfilled with a new HTTP request to the server, which results in a new document being sent to the user. That means when a user clicks on a link index.php?id=foo, the page is reloaded.
But you can check the arguments of the URL the page was loaded with by examining the window.location.href string.
Example URL: http://twitter.realgamingreview.com/index.php
Edit: forgot to mention: use the test sign in: test/test for username/password.
I am attempting to do a simple AJAX request to retrieve some data from a database. The target file, serverTime.php, seems to be working perfectly; it inserts the desired data and returns the desired responseText.
However, the request seems to be firing twice. This is clear when I step through the JavaScript using Firebug. This causes the page to 'reset' (not exactly sure), such that my cursor loses focus from its current textbox, which is a new problem. The URL also says, "localhost/twitter/index.php?message=", even if my message is not actually empty. I want to fix this fairly minor problem before something major comes of it.
The JavaScript is below. ajaxRequest is my XMLHTTPRequest object. Any help is appreciated!
//Create a function that will receive data sent form the server
ajaxRequest.onreadystatechange = function(){
if (ajaxRequest.readyState == 4){
document.getElementById('output').innerHTML = ajaxRequest.responseText;
}
}
// build query string
var message = document.myForm.message.value;
var queryString = "message=" + message;
//send AJAX request
ajaxRequest.open("GET", "serverTime.php" + "?" + queryString, true);
ajaxRequest.send(null);
Thanks,
Paragon
I've seen this many times, and for me it's always been firebug. Try TURNING OFF firebug and submit the request again. Use fiddler or some other means to verify the request only executed once.
When I write AJAX functions in Javascript, I usually keep around a state variable that prevents a new request from being dispatched while one is currently in progress. If you just want to ignore requests that are made before another one finishes, you can do something like this:
Initialize inProgress to false.
Set inProgress to true right before calling ajaxRequest.send(). Do not call ajaxRequest.send() unless inProgress is false.
ajaxRequest.onreadystatechange() sets inProgress to false when the state is 4.
In some cases, however, you'd like to queue the actions. If this is the case, then you can't just ignore the request to ajaxRequest.send() when inProgress is true. Here's what I recommend for these cases:
Initialize ajaxQueue to an empty global array.
Before calling ajaxRequest.send(), push the request onto ajaxQueue.
In ajaxRequest.onreadystatechange() when the state is 4, pop the array to remove the request just services. Then, if ajaxQueue is not empty (array.size > 0), pop again and call send() on the object returned.
My issue was completely unrelated to AJAX. Instead, it was a simple (but obscure) issue where with two textboxes in my form, I was able to hit enter and not have the page reload, but with only one, the page would reload for some reason.
I have since changed my event system such that I am not relying on something so unreliable (now using jQuery to listen for the Enter key being pressed for specific textboxes).
Thanks to those of you who took the time to answer my misinformed question.
I have a link that when clicked needs to call a controller action with certain data which must be retrieved via JavaScript. The action will be returning a FileStreamResult.
I looked at #Url.Action but I couldn't figure out how (or even if) I could pass value dictionary stuff which had to be retrieved via JS.
So then I went with a $.post from a click handler. The problem I'm having is that I'm not sure what to do in my success: function() to return the file stream result to the user. Or even if I can.
So any help on how you would do something like this would be great..
So then I went with a $.post from a click handler. The problem I'm having is that I'm not sure what to do in my success: function() to return the file stream result to the user. Or even if I can.
Exactly. You can't do much with a received byte in javascritpt: obviously you cannot save it on the client computer nor pass it to some external program on the client. So don't call actions that are supposed to return files using AJAX. For those actions you should use normal links:
#Html.ActionLink("download file", "download", new { id = 123 })
and let the user decide what to do with the file. You could play with the Content-Disposition header and set it to either inline or attachment depending on whether you want the file to be opened with the default associated program inside the browser or prompt the user with a Save File dialog.
UPDATE:
It seems that I have misunderstood the question. If you want to append parameters to an existing link you could subscribe for the click event in javascript and modify the href by appending the necessary parameters to the query string:
$(function() {
$('#mylink').click(function() {
var someValue = 'value of parameter';
$(this).attr('href', this.href + '?paramName=' + encodeURIComponent(someValue));
return true;
});
});
Instead of going with a post, I'd go with associate a JQuery on click handler of the link which would call the controller action. This is assuming that the action method returns a FileStreamResult and sets the correct content type so that the browser interprets the result and renders it accordingly.
With your approach you'd have to interpret in the onSuccessHandler of the post on how to render the generated stream.