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.
Related
I have a working web page, complete with a JavaScript function that displays text messages based on the "non-successful" results, within the same page. Everything is working except this last step.
I need to send a JSON string to my server in a POST, and regardless of outcome, I need the user's browser to navigate to the page returned in the POST. (Just as if it were an ordinary link ( href ="" type of thing.) I am using the custom tag [OK_RESULT_URL] that my server replaces with the real URL just before the page is downloaded.
You see in my code below, that I set the URL to [OK_RESULT_URL] AND the window.location to [OK_RESULT_URL] as well, which seems wrong. That means I'm making two hits to [OK_RESULT_URL], one is a POST with a body (which is correct) and the other one a GET without a body (which is wrong).
I'm a total newbie to JavaScript, so I'm probably missing something obvious. It's as if instead of using xhr.Send() I want to say xhr.SendAndNaviateTo() ... or something like that.
Thanks for any help you can provide.
onApproval: function (response) {
showResult("Approved", JSON.stringify(response, null, ''\t''));
let xhr = new XMLHttpRequest();
let url = "[OK_RESULT_URL]";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {if (xhr.readyState === 4 && xhr.status === 200){
window.location = "[OK_RESULT_URL]"};
var data = JSON.stringify(response);
xhr.send(data);
}
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.
Yes, there are lots of questions to similar stuff but I can't figure it out, sorry.
I have a file with some javascript variables, depending on user input (but no form) and a normal HTML link to my php file.
<script>
function doStuff() {
var a = 'foo';
var b = 'bar';
window.location = 'newfile.php?a=' + a + '&b=' + b;
}
</script>
go to new php file
That works fine, I can access the data in newfile.php with $_GET.
newfile.php:
<?php
$a= $_GET['a'];
$b= $_GET['b'];
echo($a,$b); // works
?>
But I'd like to use POST. I guess I have to use ajax for that but how exactly?
jQuery is included btw so I could use $.ajax()
Any help is highly appreciated :)
EDIT:
Thanks for the quick response guys!
The JSON parsing doesn't work, I can't really figure out why - after clicking on the button the browser window disappears for a split second and I'm on the same page again which is unresponsive now :(
I went with the following code:
jQuery.post('newfile.php',{'a': a, 'b': b}); //curious: with or without ''?
setTimeout(function () {
window.location = 'newfile.php';
}, 5000); //this will redirct to somefile.php after 5 seconds
newfile.php:
$a= $_POST['a'];
$b= $_POST['b'];
echo('Testing: '.$a);
Right after clicking I can see the correct output in Firebug (Testing: foo) but of course after redirecting to the site the values are lost and I'm left with "Testing: "
What can I do?
You can use ajax to achieve this. Following is the code which works on a button click or anchor click.
HTML
<button type="button" id="button1">Click me </button>
Ajax
$('#button1').click(function() {
var a = $('#IDofYourFormelement').val();
var b = $('#IDofYourFormSecondElement').val();
$.post('/somefile.php', {'somevariable': a, 'variableB': b}, function(data) {
var parsed = JSON.parse(data);
if (parsed == 'success') {
setTimeout(function () {
window.location = '/somefile.php';
}, 3000);//this will redirct to somefile.php after 3 seconds
}
else
{
alert ('Invalid details');
}
});
});
and then in your somefile.php you can access it as
$a = $_POST['somevariable'];
$b = $_POST['variableB'];
//do some stuff and return json_encoded success/failure message
You can use the new with HTML5 FormData();
Code snippet from https://developer.mozilla.org/en-US/docs/Web/Guide/Using_FormData_Objects see also https://developer.mozilla.org/en/docs/Web/API/FormData and http://caniuse.com/#feat=xhr2 for browser support
var formData = new FormData();
formData.append("username", "Groucho");
formData.append("accountnum", 123456); // number 123456 is immediately converted to string "123456"
var request = new XMLHttpRequest();
request.open("POST", "http://foo.com/submitform.php");
request.send(formData);
I guess you are trying to post the variables using javascript and display the page post executing your post variables. Found a similar question and an answer in here - JavaScript post request like a form submit.
EDIT
The window.location will call another instance of you page and then will assign or replace the current doc, hence your previous post parameters are lost. If you want the page with your post parameters passed you need to do a form submit to your php page with method=POST also with the post parameters. That's what is written in the above stackoverflow link I shared.
I have a dynamic page with different elements in each generates, and I want to load all of their lines to an alert for example or a page with JavaScript. Is this possible?
For example, if I had this line to my page:
<marquee> This is for test </marquee>
I want to show all of it to an alert or a page, somethings like that :
Pseudo-code:
<script>
alert(getAllData) | write(getAllData)
</script>
Output: (in alert)
<marquee> This is for test </marquee>
You can use Ajax. Here's an example that alerts the contents of the page test.aspx, for example:
var rq;
// Initialize the request:
if(window.XMLHttpRequest) {
rq = new XMLHttpRequest(); // Standards-compliant way, compatible with every browser except IE6 and under
} else {
rq = new ActiveXObject('Msxml2.XMLHTTP'); // IE6-compatible.
}
// Open the request:
rq.open('GET', 'test.aspx', true); // GET is the method (you're probably familiar with this), test.aspx is the URL, and true means send asynchronously.
// Set up the state-change handler:
rq.onreadystatechange = function() {
if(rq.readyState === 4) { // Request complete
alert(rq.responseText); // The response is in the responseText property.
}
};
// Finally, send the request:
rq.send(null);
For more information, Google "Ajax." There are plenty of good tutorials.
Problem I am making ajax call to server1 i.e. csce and once I got the response I am sending the response as contents to server2 i.e.yahoo server after getting response from there I want to refresh the page or atleast redirect it to the same page. Both ajax calls are working fine. The contents I am sending are also saved the only problem is that I have to manually refresh the page to see the changes. I want to refresh the page once the contents are saved on yahoo. I tried reload and redirect commands in success function of yahoo. But nothing works. I can see the both ajax calls in the HTTPfox but not the redirect.
The url from which i am making calls is different from the url where contents are saved thats why I need to refresh the page to see the changes. i.e. I am saving in yahoo/save while sending contents and seeing changes at yahoo/edit.
I am not sure where I am going wrong. Here is my code I am using. Can anyone suggest where I am going wrong. If my problem is not clear kindly do ask me to clarify more. Thanks.
This code is the code:
function handleButtonClick()
{
// Declare the variables we'll be using
var xmlHttp, handleRequestStateChange;
// Define the function to be called when our AJAX request's state changes:
handleRequestStateChange = function()
{
// Check to see if this state change was "request complete", and
// there was no server error (404 Not Found, 500 Server Error, etc)
if (xmlHttp.readyState==4 && xmlHttp.status==200)
{
var substring=xmlHttp.responseText;
alert(substring);// I am able to see the text which is returned by the server1 i.e csce
var handleSuccess = function(o)
{
if(o.responseText !== undefined)
{
console.log(o.responseText);
**window.location.reload()** // also I tried to redirect it to the same site but that also not works
}
};
var callback ={ success:handleSuccess, failure: function(x) {
console.error(x) }, argument: ['foo','bar']};
var request = YAHOO.util.Connect.asyncRequest('POST','http://yahoo.com******', callback, substring);
}
}
xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", "http://cse*****id=c6c684d9cc99476a7e7e853d77540ceb", true);
xmlHttp.onreadystatechange = handleRequestStateChange;
xmlHttp.send(null);
}
Do you just want to display the content in your page? Why don't you try something along the lines of document.getElementById('divID').innerHTML = xmlHttp.responseText;?
With divID being the id of a div that you want to fill the content with.
try following in the handleRequestStateChange function
window.location.href = window.location.href;