I have the following js function that sends a post request back to the main index page. This script is working in Chrome but is not sending any parameters in firefox while still posting back to the page. I am verifying this via the network tab after inspecting the page in firefox.
function addDrive(ans){
$.post("index.php", {add_drive: ans });
location.reload();
}
This function is called via a onClick on a button I have placed on my page:
<button onClick="addDrive('y')">Add Drive</button>
I have used similar functions in the past that have worked for both firefox and chrome and I just cant figure out why this does not work in firefox.
My suggestion would be doing something like this :
function addDrive(ans) {
$.post("index.php", {add_drive: ans}).then(function() {
location.reload();
});
}
This would ensure that you reload the page only after successfully finishing the post request. You could also provide a success handler instead if you prefer that instead of using this promises API. You could also do the same in an always handler to ensure it reloads the page even if the request fails but that would be subjective to your requirements.
However, I would argue that this doesn't look like good practice at all, if you have to reload the page you could just have a form and post that instead of trying to post using the jquery handler. You could do something like form.submit() in javascript and that would submit the form and it would submit the data in the form by a post request as long as the method on the form is set to 'POST', that way you don't have to reload the page manually and you can do that from the server end.
Try to reload your page after successful post:
$.post("index.php", {add_drive: ans}).done(function( data ) {
location.reload();
});
Related
I'm trying to request a page and click a button on it without opening a window so I'm thinking post could work. Here is my code:
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"</script>
<script>
$(document).ready(function() {
$.post(
"http://m.roblox.com/Catalog/VerifyPurchase?assetid=161075864&type=tickets&expectedPrice=1",
$("ui-block-a").submit();
);
alert("work");
});
</script>
</head>
<body>
</body>
</html>
If I'm understanding post correctly, the first argument is the url to which it requests from and the second argument is the one where you can send data. I'm trying to send a request to click the "buy" button on the page if you follow the link. Can anyone help?
A post request sends data to a given URL. What the server does with that data from that point is entirely up to the server. It is very unlikely that the web page you are trying to simulate a button press on allows that behavior. If that was possible in general, it would leave users open to some very large security vulnerabilities. For example, a site could simulate donating money via PayPal without the user ever knowing.
In this particular case, the button appears to submit a form. In that case, you could always attempt to send the request directly to the page that the form submits to, which would simulate submitting the form. However form submissions are generally protected against stuff like this, because again, it could be used to act on behalf of the user.
Basically, the best option for something like this is to provide the user with instructions detailing what they need to do, and then open the page for them.
Assuming there is no other issues like CORS you can do the post like you are trying to do, but the following is invalid.
$.post( "http://m.roblox.com/Catalog/VerifyPurchase?assetid=161075864&type=tickets&expectedPrice=1", $("ui-block-a").submit();
You are doing a POST which required the data being send to the server to be in the request body and not the URL string.
When you post to a page you are actually posting directly to the server and not a page and in this case unless the $("ui-block-a").submit(); is returning data for the page you are posting to, it is not needed.
The following would be closer to what you are looking for with that post
$.post( "http://m.roblox.com/Catalog/VerifyPurchase", { assetid: "161075864", type: "2pticketsm", expectedPrice: "1" } );
If it was successful you should see a allow-orgins error in your developer / inspector console.
$.post() is an abbreviated form of $.ajax(), with POST pre-selected as type. There are also $.get() (with GET pre-selected as type), and $.load() (with the returned data immediately injected into the specified element). But $.ajax() is the grand-daddy of them all.
AJAX is a method of exchanging data with a processor file on a server, without leaving / refreshing the page you are on. That is, with AJAX (or $.post), you can send information to a processing page on the server -- such as: my_processor.php -- the processing page can do something with the data (for example, use the data to query a database), and then echo out data, which is returned to the originating page. The received data can then be injected into a DIV on the original page, or something of the sort.
An ajax routine is usually triggered by some event on the originating page (the user presses a button, or selects a value in a drop-down, or some such). Javascript (or jQuery) code detects the event, and the AJAX code is usually actioned in the javascript event.
Here are some simple examples of what has been described.
I am trying to call __doPostBack from within JavaScript and then navigate to another page. The script I have is:
$(document).ready(function() {
$("a.change-link").click(function(){
__doPostBack("","");
location.href='pageToGoTo';
});
});
The code is not getting to the location.href='pageToGoTo' line after the post back.
Is there anyway to achieve this functionality?
Thanks
location.href='pageToGoTo'; will never be executed since you're posting the entire form back to the server. You'll need to redirect the request on the server-side.
Response.Redirect = "pageToGoTo";
I am utilizing a Google Form on a webpage. I copied the source code from the form directly onto my page so that I can modify some of the HTML instead of using an iframe. Then instead of taking the user to the google docs response page I would like to redirect them to another page.
The trouble that I am running into is with the page redirect. I was able to get this working properly in Chrome and Firefox with this:
<form target="GoogleResponse" action="https://docs.google.com/spreadsheet/
formResponse?formkey=xxxxxxxxxxxxxxxxxxxxxxxxxx&ifq;" onsubmit="
window.location = 'targetPage.html';" method="POST" id="ss-form">
IE and Safari both did the redirect automatically and the response never got written to the Google Form. If I drop the redirect, the action works perfectly in both and the response is recorded in the Google spreadsheet.
So I attempted to pull the action out and instead did it everything in onsubmit instead, like so:
<form target="GoogleResponse" onsubmit="this.action = https://docs.google.com
/spreadsheet/formResponse?formkey=xxxxxxxxxxxxxxxxxxxxxxxxxx&ifq';
window.location = 'targetPage.html';" method="POST" id="ss-form">
Same problem as before, IE and Safari both redirect, and nothing is written to the Google spreadsheet. And once again, if I remove the redirect the response gets recorded in all browsers. I can also do other stuff like throw in an alert after the action, and everything continues to work fine. The only time I see the issue is with the redirect.
So at this point the only thing I can figure is that their is some sort of conflict between the redirect and the action. I have pretty limited working knowledge of javascript and forms so any help or recommendations would be greatly appreciated!
Sounds like the browsers have not complete the form submission before handling the redirect. onsubmit happens before the submission itself so you can not handle the issue there.
Use the onload function of the target iframe for the redirect.
This has been asked in similar manner:
Old Google Form redirect after submission
Take a good look at the answer. The onload function of the iframe will handle the redirect, so the redirect will not happen until the submission is complete and a response has been given from google. So when the hidden response from google is loaded we fire a redirect. This is async functionality between the client and server. We are waiting for the server to handle the data before redirecting.
Extended note: You could try putting the redirect within a setTimeout function. This would delay the execution of the redirect, allowing the server to handle the submission first. But setTimeout requires a fixed amount of time, so if the data handling is not synchronous (ie. asynchronous) setTimeout will not work as it may fire to early or too late. Asynchronous data handling applies when the data processing requires an undetermined amount of time (such as http requests).
I would like not to dispaly the pop-up message below when post back occurs. My page has nothing to do with pricing it is displaying ms chart that updates on postback. How to disable in code or java script?
to display the webpage again internet explorer needs to resend the information you've previously submitted.
This is the javascript i've tried: doesn't work though.
<script type="text/javascript">
// <!--
function submitForm() {
window.opener.document.forms[0].submit();
}
// -->
</script>
and is attached the function to the form as so:
<body>
<form id="form1" runat="server" onsubmit="submitForm()">
I'd bet you're doing this in your JavaScript:
FB.Event.subscribe('auth.login', function(response) {
window.location.reload();
});
FB.Event.subscribe('auth.logout', function(response) {
window.location.reload();
});
While the above code comes from the Facebook documentation, and it works for a standalone website implementing the Facebook JavaScript SDK, it will break your Facebook App in Internet Explorer and Firefox by causing an infinite loop.
When Facebook loads an App, it sends information about the user's authentication state via POST. The SDK processes this data and authenticates the user.
By telling the JavaScript SDK to reload the page upon successful authentication, Firefox and Internet Explorer interpret this to mean they should send the POST data again, too. Your App receives the POST data again, re-authenticates the user, and reloads the page, causing the infinite loop.
Solution: don't use window.location.reload(). Instead you'll need to set window.location.href (or otherwise strip the POST data from the browser request).
For those less fluent in Javascript like I am, I'll expound a bit on what Aaron said. At least this is what I dug up after reading his post.
window.location.href = window.location.href;
this will replace the document.location.reload(); and works as advertised.
I ended up having to modify the window.location.href string because my page behaved differently depending on what page the user came from. So here's my complete method for posterity.
function RefreshParentPage()
{
//document.location.reload();
var redirectURL = window.location.href;
if (window.location.href.indexOf("showpage=summary") > -1) {
redirectURL = document.location.href.replace("showpage=summary", "showpage=events")
}
window.location.href = redirectURL;
}
That means this page was obtained after doing a POST request. The best way to stop that is to redirect to the same page after having processed the POST request in your server code.
I have an application in which most requests are submitted via AJAX, though some are submitted via "regular" HTTP requests. If a request is submitted and the user's session has timed out, the following JSON is returned:
{"authentication":"required"}
The JavaScript function which submits all AJAX requests handles this response by showing a popup message and redirecting the user back to the login page.
However, when a non-AJAX request receives this response the JSON is simply shown in the browser because the response is processed directly by the browser (i.e. the aforementioned JavaScript function is bypassed). Obviously this is not ideal and I would like the non-AJAX requests that receive this response to behave the same as the AJAX requests. In order to achieve this, I can think of 2 options:
Go through the application and convert all the requests to AJAX requests. This would work, but could also take a long time!
The JSON shown above is generated by a very simple JSP. I'm wondering if it might be possible to add a JavaScript event handler to this JSP which is run just before the content is displayed in the browser - I'm assuming this would never be called for AJAX requests? This handler could call the other JavaScript code that displays the popup and performs the redirection.
If anyone knows how exactly I can implement the handler I've outlined in (2), or has any other potential solutions, I'd be very grateful if they'd pass them on.
Cheers,
Don
3) Change your AJAX code to add a variable to the GET or POST: outputJson=1
You cannot add a handler to the JSP that way. Anything you add to it will make it a non-JSON producing page.
There are two options that I can see:
Add a parameter to the page by appending a URL parameter to the screen that modifies the output.
URL: http://domain/page.jsp?ajaxRequest=true
would output json only
URL: http://domain/page.jsp
would display a jsp page that could forward to another page.
OR
change the response to have the forwarding code in the JSP that will get executed by the web browser if it is hit directly. Then have your calling AJAX to strip the forwarding code out, and then process what is left.
4) Read up on the 'Accept' request HTTP header.
Then, on the server side tailor the output:
e.g.
if(Accept contains application/json...) { // client asking for json, likely to be XHR
return {"foo":"bar"}
} else { // other
return "Location: /login-please";
}
Start with a smarter error message, like this:
{"error":"authentication required"}
Wrap the JSON output in a callback:
errorHandler({"error":"authentication required"});
Have a handler waiting in your script:
function errorHandler(r) {
alert(r.error);
}
And don't forget to send it down as text/javascript and not application/x-json.