navigate to another page with post request through link - javascript

<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!

Related

Mailto is not loading the subject(or body);

I have been reading a lot of topics and trying for some time now and i can't seem to get my mailto: to fill in my subject and body.
So it starts the mail-client (i have tried 3 different clients(outlook,windows standard,gmail) and every time it fills in the mail-address but never the subject and body.
totalmenu() {
var form = document.getElementById('emailform');
// form.action = "mailto:" + personeel.email + "?subject=result&body="
//+ mail();
form.action = "mailto:blabla#gmail.com?Subject=result;
}
The comment shows the actual mailto i wanted to use.
I made a new mailto with only a subject to check if it was object related but this is not working as well.
any of u guys had similar problems or maybe see what i'm doing wrong here?
I build my own little test code, and probably found what the problem is. This code seems to work:
<html>
<body>
<form id="emailform" method="POST">
<input type="text" value="this is a test">
<input type="submit" value="send email">
</form>
<script>
(function() {
var form = document.getElementById('emailform');
form.action = "mailto:blabla#example.com?Subject=result";
})();
</script>
</body>
</html>
But if I change the form method from "POST" to "GET" it doesn't work anymore.
Are you using "GET"?
I tested the code with Firefox and Chrome on Windows 10.

JQuery/AJAX & PHP - Error with isset() when using .load() function

I have a registration page on my website for which I want to implement PHP and AJAX validation. I will show template of my code (my code is much bigger) to try to explain the problem.
registration.php
<!DOCUMENT html>
<html>
<head>
<script>
$(document).ready(function(){
$("#signupForm").submit(function(event){
event.preventDefault();
var firstNameInput = $("#firstName").val();
var lastNameInput = $("#firstName").val();
$(".messageForm").load("inculdes/signup.script.php", {
firstName: firstNameInput,
lastName: lastNameInput
});
});
});
</script>
</head>
<body>
<form id="signupForm" action="includes/signup.script.php" method="POST">
<input id="firstName" type="text" name="firstName">
<input id="firstName" type="text" name="firstName">
<button id="submit" name="submit" type="submit">Submit</button>
<div class="messageForm"></div>
</form>
</body>
</html>
signup.script.php
<?php
if (isset($_POST['submit'])) {
include "dbconn.script.php";
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
//Validators for inputs in PHP with various error messages (1-15) and database INSERT and SELECT functions.
...
} else {
echo "<span>Error 16</span>";
exit();
}
}
?>
<script>
// JQuery validator for inputs and CSS style changers based on errors
...
</script>
My problem is when I click Submit button, I get error message "Error 16", so my function skip whole PHP script and does not insert data into database. I concluded that the problem is because the variable $_POST['submit'] is not set, because when I change first line of code to if (!isset($_POST[submit''])), it works like charm, but I don't wanna loose ability to prevent users from type signup.script.php in URL field of the browser and run it. How to correct this to work? The tutorial I watched has this code and in that case it works without problem.
P.S. I will expand my code if needed for solution of this problem, because I wanted to spare space so I gave the shorthand version of it.
You simply don't send "submit" with the request.
You could add it here:
$(".messageForm").load("inculdes/signup.script.php", {
firstName: firstNameInput,
lastName: lastNameInput,
submit: 1
});
or check for isset($_POST['firstName'])
Sidenote: If there wasn't an object passed in with load() it would be a GET request. Worth remembering...
Request Method
The POST method is used if data is provided as an object; otherwise, GET is assumed.
The Docs
according to the jQuery documentation of jQuery.load() (which is a shorthanded jQuery.ajax method), this sound much alike if this would be a $_GET and not a $_POST... better use something alike jQuery.ajax() in combination with method: 'POST' - or check for the $_GET in PHP.
Dear check your JavaScript code carefully
event.preventDefault(); // Preventing default form submission
$(".messageForm").load("inculdes/signup.script.php", {
firstName: firstNameInput,
lastName: lastNameInput
});
Only posts firstName and lastName to signup.script.php
And you are trying to check for isset($_POST['submit'])
It will surely be false until you pass 'submit' in post like firstName and lastName you have passed already like below
$(".messageForm").load("inculdes/signup.script.php", {
firstName: firstNameInput,
lastName: lastNameInput,
submit: 'yes'
});
Hope it helps

Pushing a button programmatically to submit a form on another page in Javascript

Please forgive the basic question, I'm very new to Javascript and web development in general. I want to use a script on one page of my site to programmaticaly press a button to submit a form on another part of the site, making a POST request. The html I have to access is the following:
html
<form action="thing.jsp" method="post"> // Beginning of form
...
<input type="submit" id="submit" value="Do something"> // Button code
...
</form>
And I think the Javascript should look something like this:
JS
<script>
var xhr = new XMLHttpRequest();
xhr.open('POST', "/stuff.jsp", true);
var params = "???????"; // What do I need to put here?
xhr.send(params);
</script>
From reading around online, my suspicion is that I may just need to get the right value for params? Though if there's another way of achieving the same result (e.g. by just sending a POST request without doing anything to the button), I'd be perfectly happy to go with that.
Thanks in advance for your time and wisdom.
You don't need to use ajax, just use this:
<input type="button" value="GO" id="buttonId" />
<script>
function go() {
document.location.href = 'http://google.com';
}
document.getElementById('buttonId').onclick = go;
</script>
please notice the button type should be 'button', not 'submit'
Using jQuery - a JS library - you can simply send a HTTP GET Request. This can then be picked up in PHP using $_GET['key'] which will hold the value.
$(function() {
$('#unique-id-btn').click(function() {
$.get('file.php', { key: $('unique-id-input').val() }).done(function(response) {
alert(response);
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="unique-id-input" placeholder="enter something...">
<button type="button" id="unique-id-btn">Click me</button>
Note, you will need to create the file.php. Inside, it will control what happens with that data being sent across, ie:
$data = $_GET['key'];
echo $data == "foo" ? "bar" : "tell me foo!";
Also note you can only run PHP in a .php file extension, not JSP.

Javascript POSTing HTML form

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

Avoid form submitting multiple times through Javascript

Let me Clear what title means:
In my code for a validation purpose of one field dependent on field "t1" I need to auto submit my form once (Just Once). But my below code is submitting it infinite times and I know the reason why its happening.
I guess Reason is everytime the form submits again JS in header runs. Please help me avoid this. Following is my code:
<html>
<head>
<script>
window.onload = function()
{
var f = document.getElementById("CheckForm");
var temp = document.getElementById("CheckForm.t1");
if(f.name == "CheckForm")
{
var temp1 = document.getElementById("t1");
temp1.value = "Task";
}
document.CheckForm.submit();
}
</script>
</head>
<body>
<form name="CheckForm" id="CheckForm" method="Post">
<input type="text" id="t1" name="t1"/>
</form>
</body>
</html>
I tried stopping it using variable like flag and static variables like arguments.callee.count = ++arguments.callee.count || 1 and placing my CheckForm.submit() line in if clause. But nothing worked. Any advice or help is appreciable.
<html>
<head>
<script>
window.onload = function()
{
var f = document.getElementById("t1");
var temp = document.getElementById("CheckForm.t1");
if(f.name == "CheckForm")
{
var temp1 = document.getElementById("CheckForm.t1");
temp1.value = "Task";
}
if(window.location.search=="")document.CheckForm.submit();
}
</script>
</head>
<body>
<form name="CheckForm">
<input type="text" id="t1"/>
</form>
</body>
</html>
Surely your form is more complex than:
<form name="CheckForm">
<input type="text" id="t1">
</form>
That will not submit anything to the server since there are no successful controls (the only control doesn't have a name).
Since the form is just submitting to the same page, you can submit a hidden value like:
<form name="CheckForm">
<input type="text" id="t1">
<input type="hidden" name="hasBeenSubmitted" value="yes">
</form>
Now when the form submits the URL of the new page will include ...?hasBeenSubmitted=yes so you can look for that value in the URL, e.g.
if (/hasBeenSubmitted=yes/.test(window.location.search)) {
// this page loaded because the form was submitted
}
If it exists, don't submit the form again.
So since you are using a post method the easiest way's to handle this is to ubmitted to a new url , however you seem set on keeping the form submitted to the same url in which case is you are using php (or really any other language) you can check if the http request has a post attribute with a value t1
<?php
if(isset($_POST['t1']){
$your_text=$_POST['t1'];
/*do some string checking to make safe and the throw into your database or mdo whatever you please with data
if you wanted to include the ip address of the user you can get a basic and most likely client ip address like so
$ip_address= $_SERVER['REMOTE_ADDR'];
if you are handing a mulitpage form look into php session or similar tech ... cookies is kind of over kill for this scenario
then include a succes page as the form has been submitted
or you could end php with this tag ?> and then have your html and start again with <?
*/
include 'form_submitted.php';
}else{
//this would be the html page that you included in your question and can be handle in same ways as form submitted
include 'my_form.php'
}
?>
Ip address may not be best included as it would stop 2 user from filling out the form if they are in the same LAN for eg. 2 people in same office or same house (if your page is acttual on the worldwide web).
I would take a look at #RobG answer as it he is basically suggesting the same type of thing with a get instead of post
ANyways hope this helps

Categories

Resources