I need to post some data to a webservice using a single button click.
I don't want to show the reply received from the server, which a simple HTML form does. So I came up with the following code:
<!DOCTYPE html>
<html>
<head>
<script>
function sendData() {
var form = document.createElement('form');
form.action = "https://posttestserver.com/post.php";
form.method = 'POST';
var input = document.createElement('input');
input.type = 'hidden';
input.name = "args";
input.value = "on";
form.appendChild(input);
form.submit();
alert("Submited!");
}
</script>
</head>
<body>
<button onclick="sendData();">Click Me!</button>
</body>
</html>
Please enlighten me what exactly is going wrong, because its not posting any data.
Any reason you have to use JavaScript to create the form? Is it simply not posting the input or is the form failing to submit? You can always use your Web Inspect tool to see the request.
Try opening your web inspector and look at the console for any JavaScript errors.
your posted data found at
http://www.posttestserver.com/data/2015/12/16/21.17.23451563624
plz, see the image.
you can use ajax to post data instead of form submit.
params = {
'input':'on'
}
$.ajax(url,post,params,succ,err)
Solutions as per my understanding :
If you are placing script in head tag, refer 'Where should I put <script> tags in HTML markup?'. The conclusion is to put scripts in the head tag and use the async or defer attributes.
Append form to your body before submitting the form.
document.body.appendChild(form);
Place script before body tag.
Not sure why you want to create a form using JS just to post some data to server when you could have used ajax. As already mentioned in previous answers you can use jQuery. If you are reluctant to use jQuery, you could have used XML HTTP Request (XHR) object
A simple solution using jQuery would be
$.ajax({
type: 'POST',
url: 'https://posttestserver.com/post.php',
data: {'args': 'on'}
});
Since you want the data to send on clicking a button, you could trigger the event on button click
$('button').on('click', function() {
$.ajax({
type: 'POST',
url: 'https://posttestserver.com/post.php',
data: {'args': 'on'}
});
});
My main aim was
I don't want to show the reply received from the server
So I added an IFRAME in the page and then added it as the form's target
<form action="MYLINK" method="POST" target="hidden-form">
...
</form>
<IFRAME style="display:none" name="hidden-form"></IFRAME>
Now the reply from server is not visible
Related
This question already has an answer here:
Understanding HTML Form Element behavior
(1 answer)
Closed 1 year ago.
I have a simple online form that calls a PHP script on submit.
<form name="newform" id="regForm" action="../includes/submit.inc.php" method="post">
When the submit button is clicked the site URL in the browser changes to http://example.com/includes/submit.inc.php and the page is blank.
I want to display a Thank you message after form is submitted and I want the URL to remain http://example.com
I've tried using JS to hide the main container of my website and enabling a DIV with the thank you message.
function submit() {
document.getElementById("main").style.display = "none";
document.getElementById("success").style.display = "inline";
}
document.getElementById('regForm').onsubmit = function () {
var terms = document.getElementById('consentBox');
if (!terms.checked) {
showWarnings(warnings);
return false;
}
submit();
return true;
};
This kind of works I can see the thank you message for a split second but then the browser goes to http://example.com/includes/submit.inc.php and the page is blank. I really want to avoid redirecting to another .php file. I know I could do something like this:
header( "location: ../success.php", true, 301 );
But prefer to display the message on the same page. How can I achieve this?
Thanks in advance.
You can add post php code in the same page where you written the main code.
For example-
<form name="newform" id="regForm" action="inex.php" method="post">
<?php
//and your php post code here
?>
This can achieved through the use of AJAX and the serialization of the form. This is written with the assumption that the php script returns a status message (html block looking to be displayed) upon successful completion. This can also be helpful for error handling, in the event there is an issue within the php script. This example makes use of the jQuery library.
<form name="myForm" id="myForm">
<input type="text" name="input1">
<input type="text" name="input2">
</form>
// Using jQuery
$('#myForm').submit(function(e) {
//Prevent Default
e.preventDefault();
// Gather Form Values into Array
var values = {};
$.each($('#myForm').serializeArray(), function(_, kv) {
values[kv.name] = kv.value;
});
$.ajax({
method: "POST",
url: "pathToFile/formHandlingFile.php",
dataType: "html",
data: {
vals: values
}
})
.done(function(data) {
$('#main').hide()
$('#success').html(data)
$('#success').show()
})
});
I don't know if it is possible or not. I referred some site, but I didn't get exact answer.
I am using
click
When I send this request to server in the response page easily I can see "id=4" in address bar, obviously which is not secure, But in post request we cant see this.
So can we convert a get request to post or ant other way is there to hide this from address bar.
Thanks in advance.
Firstly, to convert GET to POST, simply change the link to a form:
<form id="myForm" action="xyz" method="post">
<input type"hidden" name="id" value="4"/>
</form>
This form will not be visible and you can easily auto-submit it using JavaScript in your link:
click
Secondly and more importantly, both GET and POST are equally not secure over HTTP. To secure them, use HTTPS and they will be both equally secure, so no need to change if GET is working for you.
click
Dynamically create a from and post it.
function postForm() {
var form = $('<form method="POST" action="xyz"></form>');
$(document.body).append(form);
form.append('<input type="hidden" name="id" value="4"/>');
form.submit();
}
As Racil suggested in comments, you can also do the following
click
and then
$('#postLink').click(function(e){
e.preventDefault();
//create form and post
});
Call a java script function on onclick which will make the form submission using post method or you can use ajax call to post the data and get your desired results.Use id as a parameter in function.
<a href="#" onclick="postData(4)">
/// Javascript function for ajax call
function postData(id){
var param = { "Id": id};
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "xyz.aspx",
data: JSON.stringify(param),
success: function (data) {
/// Recive data here or do your stuff here
}
}
Make a form having single input type hidden and onclick set value of that input type hidden element and submit form using jquery.
<form id="target" action="destination.html">
<input type="hidden" id="hiddenValue">
</form>
/// Javascript function for setting value of hidden element and form submission using jquery
function postData(id){
$("#hiddenValue").val(id);
$("#target").submit();
}
Hopefully this will solve your problem.
Here I create a form with iframe.
I want to save those data name and category using an ajax request.
Here's a google spreadsheet where I want to save those data https://docs.google.com/spreadsheets/d/1WXzTVsIAKsGvXgm4ivRzTPN2P8kupJDcnH5sHdc0Vhw/edit?usp=sharing
I'm using bookmarklet so this is a script of it.
when I do this nothing is done. No error and no console log? I don't get it? Please help me I'm new on this.
My code looks like this , this file is called script.js :
(function(){
var f = '<form action="" method="post"> Name: <input type="text" id="name" name="name">Category <select name="category" id="category"><option value="first">First</option><option value="second">Second</option><option value="third">Third</option></select><br><input type="submit"></form>';
var iframe = document.createElement('iframe');
document.body.appendChild(iframe);
iframe.contentWindow.document.open();
iframe.contentWindow.document.write(f);
iframe.contentWindow.document.close();
$("#submit").click(function(){
var name = $('#name').val();
var category = $('#category').val();
console.log("po ajax" , name , category);
$.ajax({
url: "https://docs.google.com/spreadsheets/d/1WXzTVsIAKsGvXgm4ivRzTPN2P8kupJDcnH5sHdc0Vhw/edit?usp=sharing",
data: { "name": name,"category": category},
type: "POST",
dataType: "xml",
statusCode: {
0: function () {
// window.location.replace("ThankYou.html");
console.log("error");
},
200: function () {
// window.location.replace("ThankYou.html");
console.log("ok");
}
}
});
});
})()
EDIT:
here is my index.html page where I defined my bookmarklet:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<title></title>
</head>
<body>
<p> Bookmarklet</p>
</body>
</html>
You cannot bind event to element that is in iframe from parent page.
As you are adding your form in iframe, the javascript function for binding click event to submit button should be also in iframe.
And because you are using jquery, the Jquery reference should be also exists in iframe.
You are not making an ajax call, because your form is submitted the default way and therefore reloads the page before your js function. You need to prevent the form submission by changing $("#submit").click(function(){ to $("#submit").click(function(e){ e.preventDefault(); ...//continue with current code
$("#submit") wants an id to bind to so I suggest you rewrite <input type="submit"> to <input id="submit" type="submit">
Hmm. There are a whole lot of issues here.
the javascript code is separate from the iframe content. (This is the Sangram Parmar answer.)
I'd recommend getting rid of the iframe in test, and just add the <form> code block as raw html.
The jquery #submit identifier doesn't fit the situation. Personally, I'd add a <form id="form_id" ... term and then call it via $(#form_id)..click(function(e){... Oh, wait. This is the concern raised by P-A.
Good catch by Velimir Tchatchevsky on the prevent default behavior (but I do see action="" in the original code. I do think the prevent default behavior is a good practice.
Next we will start getting Cross-Origin Request (CORS) errors depending on which browser the user is using.
You can fix that by using jsonp instead of xml as the data type, but when you do that the error you will see is: Refused to execute script from 'https://docs.google.com/spreadsheets/d/1NTlfje4H-K3KyvBvUDqIA0z7pz_VQpijJV5…ery22304475027782793899_1462276071176&name=&category=first&_=1462276071177' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled. Sigh. Not sure what that is, yet...
Aha... I think this link will prove helpful. Look at the response by 'dev' and the links he has provided.
I've programmed a contact form that sends out an email with the details of the inputs.
On submission,(action="send_form_email.php") it takes me to the actual PHP file page. Is there any way to prevent this? I currently use this code below to bring me back to the page where the form is, but this prevents the other script from running that lets the person know that the form was submitted successfully.
header("Location: http://cvolden.net/");
Below is the code that will not echo out:
echo "<script type='text/javascript'>alert('thanks');</script>";
This form repeats on several pages on the website. In the end, I want the customer to remain on the current page and for them to be notified that everything was sent correctly.
THanks for help!
You cant. Default functionality for forms will redirect to whatever the action attribute holds. In order to do what you need, you need to use AJAX
easy example with Jquery:
$("form").submit(function(){
var postdata = $(this).serialize();
var url = $(this).attr("action"); //something.php;
$.post(url, postdata, function(res){
console.log(res); //your PHP results
alert('thanks');
});
});
set target to iframe it will load on same page.
<form action="send_form_email.php" method="post" target="my_iframe">
.........................
</form>
<iframe name="my_iframe" style="display:none"></iframe>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
function DoPost(){
$.post("index.html", { name: "John", time: "2pm" } );
}
</script>
</head>
<body>
GO
</body>
</html>
I made function and trying to call that function, inside that function I mentioned url and data as mentioned here. But, It's not working for me.
NOTE : Even I mentioned in my post title, then also I want to clarify that, I want to navigate to another page using POST method through simple hyperlink.
Create an html form with all the data you need to send and specify as action the page you need to forward the user.
<form method="post" id="theForm" action="REDIRECT_PAGE.php">
Then put some hidden fields in that form.
<input type="hidden" name="name" value="John">
<input type="hidden" name="time" value="2pm">
</form>
Wrap this inside of your doRedirect function and the redirect will work while correctly submitting your POST data.
document.getElementById('theForm').submit()
As a side note, you may want to redirect the user to a .php page not a .html one if you need to read POST data. This depends on your server configuration but, by default, I don't think you can run PHP code inside of a .html file.
I know this question is almost 4 years old and there is already an accepted answer, but I would like to provide an alternative solution as well as point out your mistake.
Part 1: The Solution
The conventional solution for navigating with a POST request is a form, which the accepted answer uses. I will build on top of this by presenting a solution to programmatically create forms using DOM.
var payload = {
name: 'John',
time: '2pm'
};
var form = document.createElement('form');
form.style.visibility = 'hidden'; // no user interaction is necessary
form.method = 'POST'; // forms by default use GET query strings
form.action = 'index.html';
for (key in Object.keys(payload)) {
var input = document.createElement('input');
input.name = key;
input.value = payload[key];
form.appendChild(input); // add key/value pair to form
}
document.body.appendChild(form); // forms cannot be submitted outside of body
form.submit(); // send the payload and navigate
I used index.html as per your original code, but I would take the accepted answer's advice and use PHP to accept and process the POST data.
Part 2: The Problem
The main problem with your original solution is that it used $.post, a helper function built on top of $.ajax. AJAX is meant to be used when retrieving data from a server and using it within current page, rather than navigating to another page.
This should work fine.
Similar to one answer, but a better one.
var payload = {
name: 'John',
time: '2pm'
};
var form = document.createElement('form');
form.style.visibility = 'hidden';
form.method = 'POST';
form.action = link;
$.each(Object.keys(payload), function(index, key) {
var input = document.createElement('input');
input.name = key;
input.value = payload[key];
form.appendChild(input)
});
document.body.appendChild(form);
form.submit();
function js_navigate_with_post(js_url, js_post_params)
{
var js_html='';
js_html += "<form id='js_navigate_with_post' method='post' action='"+js_url+"'>\n";
js_html += "<input type='hidden' name='js_navigate_with_post' value='true'>\n";
for (var js_key in js_post_params) {
if (js_post_params.hasOwnProperty(js_key))
{
js_html += "<input type='hidden' name='"+js_key+"' value='"+js_post_params[js_key]+"'>\n";
}
}
js_html += "</form>\n";
jQuery('body').append(js_html);
jQuery('#js_navigate_with_post').submit();
}
Finally, I did it, but not exactly as I wanted. But it is helpful for me. Now, sharing for others
<html>
<head>
<script type="text/javascript">
function DoPost() {
document.postlink.submit();
}
</script>
</head>
<body>
GO
<form action="demo.php" name="postlink" method="post">
<input type="hidden" name="name" value="this is my POST data">
</form>
</body>
</html>
I got it working finally in one of my projects.
You can try
<html>
<head>
</head>
<body>
<button id="clickme">GO</button>
</body>
<script>
$("#clickme").click(function(e){
var myForm = '<form id="ff" action="page2.php" method="POST">\
<input name="name" value="John">\
<input name="time" value="2pm">\
</form>';
$('body').append(myForm);
$('#ff').submit();
$('#ff').remove();
});
</script>
</html>
<html>
What do you mean it is not working? How can it work when you post results to a simple .html page?
The $.post function is a shorthand for $.ajax, which I always found easier to read and debug! Please have a look again in the link that you provided and see the examples in the bottom of the page!
For example:
$.post("test.php", { name: "John", time: "2pm" } );
Update: No, it shouldn't go to the index.html. What your code actually does is sending post variables to an .html page, so basically it doesn't do that much. That said, you can do what you want with many different solutions, see two of them below:
You can either add an done event on the $.post function, for example:
$.post("test.php", { name: "John", time: "2pm" } ).done(function() { alert("Success, do the redirection here!"); });
Or maybe maybe redirect using get variables instead of post ones? for example:
window.location = "index.php?username=blah&pass=blah";
and deal with them in the php page.
ps. the above solution obviously is for testing purposes, if you go that way you will have somehow to encrypt your data!