How to pass POST parameters via URL in browser address bar - javascript

One can figure out from a webpage the parameters used for a POST request, e.g.
How to view the address of the POST request made when an HTML button is clicked?
Is this possible for POST method to enter the url with parameters in the address bar or maybe from the debugger console?
For get request, one inserts a ? between address and parameters, e.g.
https://www.w3schools.com/action_page.php?fname=Albert&lname=Einstein.
(The analog post form calls the same script.)

Here is my javascript solution.
E.g. the form on http://vizier.u-strasbg.fr/viz-bin/VizieR
requires post.
The following command can be run in the debugger console. It manipulates one input field.
form=document.getElementsByName("form0")[0]; form.isource.value="Gaia";
form.target="_blank"; form.submit()
The url is already inherited from form.action.

Sure it is possible for POST method to pass parameters in the address.
Set up a form to POST with an action /foo?bar=bat and the server will get POST form parameters and the query string parameters.
It would be trivial to create the action dynamically so that the query string in the action contains the form parameters. For example - here the when the form is submitted the POST data is appended to the query string before the form is posted via ajax. So you get the post parameters both in the URL and in the body data.
html
<!DOCTYPE html>
<html>
<body>
<form action="/something">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="John"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Doe"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
js
$("form").submit(function(e) {
e.preventDefault();
let f = $(e.currentTarget);
$.ajax({
type: "POST",
url: `${f.attr("action")}?${f.serialize()}`,
data: f.serialize(),
success: function() {
//success message maybe...
}
});
});
That said this is probably not a good idea at all.

It's not possible.
The POST params can be passed only via the request body.
You can use some kind of API client tool such as Postman, Paw or just use plain curl.

Related

I have an RESTFul API that renders HTML through a GET endpoint. How can I display this html in my wordpress website with custom header from the form?

I'm using a nocode API that returns some HTML based on some parameters in the URL when the user makes a GET request. I'd like to improve the user experience and have a form like a contact 7 form that can map user input for each form field in the call to API.
For example form would look like following:
Name: Todd
Email: todd#gmail.com
Key: zjdHSDFHSDFHSDFS
My API is example https://api.com/endpoint/v1/
When the user enters name, email and key I need to make a call like this:
My API is example https://api.com/endpoint/v1?name={name}&email={email} with the Key field passed in as a header (X-BLOBR-KEY: {key})
I couldn't figure out how to do this with javascript or with a wordpress plugin.
Here is some code. It is a generic HTML form and a custom submit function in vanilla JavaScript placed inside the head tag. I think it achieves what you want besides the header.
It is not possible to perform an HTTP redirect with headers, read more here. An alternative would be to perform an async request then if it returns HTML you could replace the existing HTML with the new HTML. This is a bit of hacky approach in my opinion.
As it stands, I'm not sure what value a header like this would be adding. If it's hard-coded into the HTML/JavaScript anyone could see it, manipulate it, or use it on their own form to spoof yours. To avoid this you could look into using PHP. I know W3 has resources for HTML forms with PHP.
<html>
<head>
<script>
function submitFunction(e) {
// Prevent the default form submitting actions to occur
e.preventDefault();
e.stopPropagation();
// Get the form
let form = document.querySelector("#myForm");
// Get all field data from the form
let data = new FormData(form);
// Convert key-value pairs to URL parameters
let params = new URLSearchParams(data);
// Build the endpoint URL
let newUrl = `https://api.com/endpoint/v1?${params}`;
// Send to endpoint URL
window.location.href = newUrl;
}
</script>
</head>
<body>
<h2>HTML Form</h2>
<form id="myForm" onsubmit="submitFunction(event)">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="John">
<br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Doe">
<br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

HTML Form method vs jQuery function type

I'm totally a newbie on frontend development and just learning about jQuery.
I'm confused about "submit a HTML form with jQuery ajax". Here is a simple example:
<form class="form" action="" method="post">
<input type="text" name="name" id="name" >
<textarea name="text" id="message" placeholder="Write something to us"> </textarea>
<input type="button" onclick="return formSubmit();" value="Send">
</form>
<script>
function formSubmit(){
var name = document.getElementById("name").value;
var message = document.getElementById("message").value;
var dataString = 'name='+ name + '&message=' + message;
jQuery.ajax({
url: "submit.php",
data: dataString,
type: "PUT",
success: function(data){
$("#myForm").html(data);
},
error: function (){}
});
return true;
}
</script>
As you see, when we click the button Send, the function formSubmit() will be invoked and the jQuery.ajax will do its job. It will send a http request with the type PUT.
But there is an attribute in the HTML form method="post", now I'm confused. When we click the button, what will actually happen? The jQuery.ajax will send a request in the js function but what will the method="post" do? Or method="post" can be ignored? If it does nothing, can we make the attribute method empty: <form class="form" action="" method="">?
Additional
Now I realise that the type of the buttion in this example is button, instead of submit. If I change the type into submit and click it, what will happen? Will it send two http requests, a post request comes from the form and a put request comes from the jQuery.ajax?
This example is badly designed and confusing.
The formSubmit function will only be called when the button is clicked. When the button is clicked, that function will run, and nothing else will happen; since the input is not a submit button, the form will not attempt to submit. All network activity will result from the jQuery.ajax inside the function. In this case, the <form> and the method="post" are ignored completely, since the form doesn't get submitted - the method used will be the one in the .ajax function, which is PUT.
But the form is still submittable, if the user presses enter while focused inside the <input type="text". If they do that, then the formSubmit function will not be called (since the button wasn't clicked), and the user's browser will send the name and the message as form data to the server, on the current page - and yes, as a POST. (Is the current page this code is on submit.php? If not, that may be a mistake. Perhaps the person who wrote the code completely overlooked the possibility of the form being submitable without using the button.)
To make the example less confusing, I'd change the button to a submit button, and add a submit handler to the form instead of a click listener to the button. Then have the submit handler return false or call e.preventDefault so that all network activity goes through the .ajax call.
The method attribute in HTML Form is used to send the form data when you're sending it without the help of an Ajax Request or any other scripting language.
When you use a scripting language like JS and Jquery, you have the chance to send the data via an AJAX request. Inside the AJAX request, you can define the method again. So, it won't rely on the HTML Form's method attribute.
Few resources you can follow:
https://api.jquery.com/jquery.ajax/
https://api.jquery.com/jquery.post/
The form tag gives support by giving several inbuilt default actions, but since you have defined a submit button and made a function to be executed onclick manually, so the form tag will only confuse the structure. So it's better to remove the form tag completely and you code will look like
<input type="text" name="name" id="name" >
<textarea name="text" id="message" placeholder="Write something to us"> </textarea>
<input type="button" onclick="return formSubmit();" value="Send">
<script>
function formSubmit(){
var name = document.getElementById("name").value;
var message = document.getElementById("message").value;
var dataString = 'name='+ name + '&message=' + message;
jQuery.ajax({
url: "submit.php",
data: dataString,
type: "PUT",
success: function(data){
$("#myForm").html(data);
},
error: function (){}
});
return true;
}
</script>
Actually method and action tags are useful when you are not using any ajax request.
➡️ Suppose you are not using the ajax request then what will happen?
Since your method is POST it'll append the form-data inside the body of the HTTP request.
Then the form-data is sent to the page specified in the action attribute.
But since you are now controlling the form submission manually through ajax. You can skip those attributes. On that case you can specify on your formSubmit method what to do when your submission is completed.
You can also prevent the form submission using preventDefault.
For example:
<form onSubmit="formSubmit(event);">
<button>submit</button>
</form>
function formSubmit(e) {
e.preventDefault();
// Now you can set where to go when your form is submitted successfully.
}

Web wordgame data saving in python

I have a word game as a web-page made in html, css and js.
User input his name in input form.
User presses "ready" button after playing.
Program sends the information about the session to the server.
Server saves this information in a file.
The information saves correctly, but after user presses "ready" button web page updates.
Is it possible to send the information to the server without updating the web-page?
<form method="GET" action="../cgi-bin/game.py">
<input type="submit" value = "Ready!" id="readyBut">
<input type="hidden" name="op" value="save"></input>
</form>
Yes it is possible with AJAX. Check out jQuery's $.ajax() method.
Specifically, if you want to send a GET request, you can also use the get() method.
Here's how it should look on the client side:
<form>
<input type="submit" value = "Ready!" id="readyBut">
<input type="hidden" name="op" value="save"></input>
</form>
<script>
$("readyButton").click(function(){
$.get("../cgi-bin/game.py",function(data,status){ // use whatever url is relevant
console.log(data); // data is whatever your python script returns.
});
});
</script>
Although if you want to send data to the script, I'd highly recommend using the $.post() method.

Prevent page reload on form submit

I am trying to submit a form using get method but I dont want the form to refresh or rather when it reloads I want to maintain the data. There seems to be lot of questions on similar lines but none that I tried helped. I am posting my code here:
<script type="text/javascript">
function formSubmit()
{
document.getElementById('form1').submit();
return false;
}
</script>
<form id = "form1" method = "GET">
<br> Query: <input name="query" id="query" type="text" size="50" value="">
<input type="button" name="search" value="Get News" onclick = "formSubmit()">
</form>
I am using python on the server side.
Thanks
The statement:
I am trying to submit a form using get method but I dont want the form to
refresh or rather when it reloads I want to maintain the data.
Implies to me that your end goal requires AJAX or at least some passing of data to the server and back. You will not be able to retain scope within Javascript over a page refresh without the use of something like cookies or passing data to/from the server. Having said that these are more akin to secondary storage mechanisms while you want to retain scope (or primary storage). To do this I would recommend AJAX.

jQuery not sending POST data

So I have a really simple form on a website that's entirely AJAX based for loading its pages. The only way for this form to work would be for it to do some AJAX magic as well, so I set about doing it. I had the form tested so I knew it all worked.
Here's the javascript for my form.
The variable "fullpath" just tells me what page is loaded at the moment, all of the pages are stored in the local "pages" directory.
It serializes the form and sends it to the server, with some debugging alerts.
$(document).ready(function() {
$("#regForm").submit(function(event) {
alert($(this).serialize());
$.post("pages/" + fullpath, $(this).serialize(), function(data){
alert(data);
});
return false;
});
});
Here's the form itself
<form name="input" id="regForm">
<div class="form-field"><label>Username</label> <input type="text" name="username"/></div>
<div class="form-field"><label>Password</label> <input type="password" name="password"/></div>
<div class="form-field"><label>Confirm Password</label> <input type="password" name="password2"/></div>
<div class="form-field"><label>Screen Name</label> <input type="text" name="screenname"/></div>
<div class="form-field"><label>Email Address</label> <input type="text" name="address"/></div>
<div class="form-field"><label>Group</label> <select name="usergroup">
<option value="0">Superuser</option>
<option value="1">Admin</option>
<option value="2">Moderator</option>
<option value="3">Advmember</option>
<option value="4">Member</option>
<option value="5">Guest</option>
</select> <br />
<label>Submit: </label><input type="submit" value="Submit" />
</div>
</form>
And here's some PHP I put at the beginning of the page
print_r($_POST);
So I fill the form with some bogus info, and I press submit. All of the data is displayed with the
alert($(this).serialize());
And then the call is successful and I see the loaded form with my
alert(data);
But, where I ask to print the $_POST array in PHP, this is all I get
Array ()
So jQuery is sending the data, it's getting the page back, but for some reason the POST variables aren't going through. Anyone care to lend a hand?
This works in a Fiddle.
Are you sure that fullpath is defined globally ? I don't see any other possible source of errors in your code.
Edit: I can see the actual problem from your comments: 301 redirects don't work through POST:
If the 301 status code is received in response to a request other than GET or HEAD, the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user, since this might change the conditions under which the request was issued.
You need remove this redirect thing, so "pages/" + fullpath directly points to the PHP script. This could also be a problem with your server configuration.
In case of Apache, you might also want to have a look at this SO question.
I packed your snippets together in an html-file and it worked for me so the problem has to be somewhere else in your code. (source: http://pastebin.com/y4Dfsepv)
You have not specified method="post" in your form. If you do not specify, it becomes method="get" by default. So there is no values in the $_POST, you can print_R($_GET) and you will see values there.
Change the below line from:
<form name="input" id="regForm">
to:
<form name="input" id="regForm" method="post">
Update:
Updating the answer as per the comment. The "pages/" + fullpath in $.post might be pointing to the wrong page, try alerting it and check server response in firebug. Make sure it is pointing to the page you want else use the full path to the php script like below:
$.post("http://localhost/pages/" + fullpath, $(this).serialize(), function(data)
you need to chance your direct link."pages/" + fullpath. That is a problem, ajax can't recognize your link when you post
** Editing because we've learned that there is a 301 Redirect code being returned by the server **
See this: https://mdk.fr/blog/post-data-lost-on-301-moved-permanently.html
301 Redirects lose contents of the POST. So jQuery is sending it along, but the server redirects it to the right location of the script without the POST data. You need to figure out where the right location of the script is and specify that in your jquery call to avoid the redirect.
You don't have method="POST" in your form.

Categories