I am developing a website and trying to make it as interactive as possible, so the least page reloads or redirections possible.
I need to submit a form through the POSTmethod:
<form method = "post" id = "form">
#<Text Inputs>
<input type = "submit" class = "form-control" onclick = "post_to_url('/url/', $('#form').serialize()); ">
</form>
And I am using this code to submit it using XMLHttpRequest
function post_to_url(url, content){
const xhr = createXmlHttpRequestObject();
xhr.onload = function () {
console.log(xhr.responseText);
};
xhr.open('POST', url, true);
xhr.setRequestHeader("Content-type", url + "x-www-form-urlencoded");
xhr.send(content);
}
function createXmlHttpRequestObject(){
var xmlHttp;
if (window.XMLHttpRequest){
xmlHttp = new XMLHttpRequest();
}else{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlHttp;
}
My problem is that even using this code the page still reloads. In the backend, if my application (using Python Flask) redirects to the page I have requested from, the page just reloads. If the application returns a response text, the browser gets directed to the url I am posting to and displays the response text in a page for itself.
I have looked at a w3schools Try It example that makes a post request in the same way as I do. Here, the request is clearly done in the background without affecting the interface seen by the client that browses the website.
So I would like to know: Have I missed something? Are there different procedures for the XMLHttpRequest depending on how the server responds? Any answers are welcome and will be attentively considered.
The page reloading has virtually nothing to do with your JavaScript.
You are clicking a submit button that is inside a form!
Modern JavaScript would bind the event handler to the form's submit event using JS (instead of the submit buttons click event using HTML).
You can then prevent the default behaviour of a form submission.
const form = document.querySelector("form");
form.addEventListener("submit", form_handler);
function form_handler(event) {
event.preventDefault(); // Don't submit the form normally
post_to_url('/url/', $(this).serialize());
}
Do write server-side code to handle a regular form submission when the JS fails. This is best practice.
Related
I want to send large files and report the upload status. It should be easy, and there are lots of answers on this site demonstrating it. But for some reason it doesn't work for me, not on Firefox, nor Chrome.
I've got a form with files (defined as <form id="form" method="post" enctype="multipart/form-data">) that I'm posting using this code:
function post() {
const request = new XMLHttpRequest();
request.upload.addEventListener("progress", (e) => {
console.log("progress: " + e.loaded + "/" + e.total);
});
request.open("post", formElement.action);
request.responseType = "json";
console.log("Start sending");
request.send(new FormData(document.getElementById('form');));
}
But the minute I click the button which activates this function, the browser stops responding until the whole operation is done and then it just renders the json response.
The console doesn't show any message (not even the "start sending", let alone the progress), and when I inspect the page after sending the post request, it shows as if it doesn't have any JS or DOM at all. i.e. the page is showing, but is not inspectable and non-interactive.
What am I doing wrong?
You need to prevent the default action of the form, as MaksTech pointed out. Just forget the jQuery part of his, only the following line is important:
e.preventDefault();
There are plenty of other solutions you can also modify the action of your form to the following
<form onsubmit="event.preventDefault(); post();">
or attach that listener accordingly
Your form submits as a normal form, so you should cancel that like so:
let $form = $('#form');
$form.on('submit', function (event) {
event.preventDefault();
// This will stop default submition so you can do it manually,
// i.e. as AJAX (XMLHttpRequest)
// Your function goes here...
});
Here's some more information about what's happening here on official JQuery docs.
I am trying to get data form a website about institution using XMLHttpRequest but rather than data I am getting error page please help
My code:-
var url = '[https://tsecet.nic.in/institute_details.aspx?iCode=JNTH][3]';
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Typical action to be performed when the document is ready:
document.write( this.responseText);
}
}
xhttp.open("GET", url , true);
xhttp.send();
Target Web Page Address:-
https://tsecet.nic.in/institute_details.aspx?iCode=JNTH
If I try to open
https://tsecet.nic.in/Default.aspx>>then click on >>
institute profile >> then click on>>JNTH
Then I am able to get data in browser Else I am redirected to an error page
Please help me...
Note
I am trying to get this data from a different website and a different
domain This website is scripted in aspx
The AJAX request you're trying to run can't do that, as the pages have the X-XSS-Protection: 1 header, blocking such requests. It looks as if they allow the internals URIs to launch only within a "frame" set by the homepage. Unfortunately, I can't tell for sure. In short, you are going to need another approach.
I'm trying to write a LibreJS compatibility web extension for a website. The intended browser is Icecat version 52+.
A form is broken on this website because it has a proprietary onSubmit script.
When I set the onSubmit of the form to my extension's JavaScript and submit the form, it responds with a URL.
When entered manually by copying and pasting this URL into the URL bar it redirects to the correct page.
However, when I get the exact same URL in Javascript and redirect it like this, the webpage behaves differently and gives an error page saying it thinks it's a crawler.
I have tried every other method for redirecting I could find on Stack Overflow like setting document.location.href, window.location.href, window.location.replace(redirect))
My question is how do I fix this? Code:
var http = new XMLHttpRequest();
http.open('POST', url, true);
http.onload = function (){
console.log("URL in response to post:");
var redirect = // verified this is the correct URL
location.href = redirect; // website gives an error page:
//Error! No saved objectValues at all -- crawler? bad link? filter?
return;
};
http.send(form_data);
I am trying the following :
<html>
<script src ="myscript.js" type = "text/javascript">
// in this file i have the foo functions defined...
</script>
<!--- here the page is defined -->
<form action = "some.php" method = "post">
<input type = "submit" name ="exec" value = "EX" style="width:40px" id = "EX" onClick="foo();">
</html>
Now, in myscript.js :
function foo() {
var req;
req = new XMLHttpRequest();
req.open("POST", "mydomain.name/hello.php", false);
req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
// ldt is a successfully defined string,
// i am not showing the complete function, but an alert here
// showes that ldt is successfully defined
req.send(ldt);
alert("sent");
alert(req.status);
if(req.status == 200)
{
var lddata = req.responseText;
alert(lddata);
}
}
Not that in my javascript, I have called hello.php, while the form in the initial htmp goes to a different file : some.php.
The file hello.php just spits "hello world" , and nothing else - at this moment, nothing is doe with the post variables.
Now, I would expect that until req.send() recieves a response, it javascript wont execute any futher, and before some.php is loaded, i will at least be alerted about the state of req.
However, in firefox (all files are being excuted from a local apache server, besides for hello.php, which is in mydomain.name. I have CORS enabled by default.), before I get to know the status of req via an alert, the next page, some.php is loaded.
What is wrong?
PS: there are some questions in the similar topic in SO, but i did not seem to have made any progress with them.
EDIT: as mentioned in the comment : this is the plan
Click on the "EX" button, in the html file at the begining, causes the onClick function foo() to get activated.
foo() does the XmlHttpRequest() to load a response from hello.php somewhere else (mydomain.name)
Then foo() alos sets the value of an hidden input element
Then since EX is a submit button, the form submits everything (including the newly set hidden element) to some.php, which is in the same server.
Edit 2: Also tried with
req.open("POST", "http://mydomain.name/hello.php", false);
as mentioned in a comment, did not work either.
I am trying to create a bookmarklet that, upon clicking, would request some information from the user (a url and a couple other fields in this case) and then send that data to a php page on my server and then display the result.
I would like to do an Ajax call for this so that I don't actually redirect to the new page, just get the data but I assume I would run into the "Same Origin Policy" limitation of Ajax.... is there any known way of basically doing the same thing?
Also, what would be the best way to pass the parameters? I already have a mechanism in place to recieve the parameters as a post message from a form...is there any way I could just reuse this?
You can set a bookmarklet by create a bookmark and add that piece of code below in location, but, according to same origin policy limitation, that will only work when the current tab is on the same location, here www.google.com.
If I've understand well your needs, that should be ok for your problem.
var request = new XMLHttpRequest();
request.open("GET", "http://www.google.com", true);
request.onreadystatechange = function() {
var done = 4, ok = 200;
if (request.readyState == done && request.status == ok) {
if (request.responseText) {
alert(request.responseText);
}
}
};
request.send(null);
I don't know if POST would work.
You won't be able to do a post, but a GET will work fine. If you're using something like jQuery, it will simply create a script tag with a src URL which would send the data you are looking to submit.
You will have to return JSON style data.
See: http://docs.jquery.com/Ajax/jQuery.getJSON
Alternatively, your bookmarklet could create an iframe on the page, and that could do you work of submitting the data (you could use post then) if you weren't looking to communicate between the iframe and the page itself, but instead just use user input to submit.