Ajax, how to get data from an HTML form - javascript

I'm driving myself crazy with Ajax at the moment, there is something that im not getting.
I want a user to input their password, then their new password twice, but i want to use Ajax to send that data to a PHP script to check it and to store the new password in the database if needed.
I just don't understand how to get the data from the HTML form to the Ajax script. Everywhere i look on the internet the information just seems to confuse me that little but more, this always seems to be the case when trying to find help with Java related product i feel.
So heres teh Ajax:
ajaxRequest.onreadystatechange = function()
{
if(ajaxRequest.readyState == 4){
//document.myForm.time.value = ajaxRequest.responseText;
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
var queryString = "?oldpass=" + oldpass + "&newpass=" + newpass + "&newpassretype=" + newpassretype;
ajaxRequest.open("post", "serverTime.php", true);
ajaxRequest.send(queryString); //Would use this to send post data (passwords) to the script
I have missed out all the broswer specific stuff because im sure you've seen it all before.
<form>
<input type="password" name="oldpass" id="oldpass" />
<input type="password" name="newpass" id="newpass" />
<input type="password" name="newpassretype" id="newpassretype" />
<input type="submit" onclick="ajaxFunction('oldpass', 'newpass', 'newpassretype')" name="button2" id="button2" value="Change Password" />
<div id="txtHint"></div></form>
I think i miss something here, but i haven't got a clue what it is! ANy ideas?
thanks for your time and i hope this isn't something silly.

Just change this one line and it will work...
var queryString = "?oldpass=" + document.forms[0]["oldpass"].value +
"&newpass=" + document.forms[0]["newpass"].value +
"&newpassretype=" + document.forms[0]["newpassretype"].value;
2 things though...
You're passing the password and the confirmation in the URL. That's not needed as you should check that they're the same at client side, rather than send them to be checked at server side.
You shouldn't send password information in a URL as it's the easiest thing in the world to capture.

You have hard coded strings that you are passing to ajaxFunction, you need to use DOM to access the form fields and get their values. You also need to run encodeURIComponent over them to make them safe to drop into the query string.

Related

Reload url with variable from form field PHP/HTML/Javascript [duplicate]

Consider this form:
<form action="http://www.blabla.com?a=1&b=2" method="GET">
<input type="hidden" name="c" value="3" />
</form>
When submitting this GET form, the parameters a and b are disappearing.
Is there a reason for that?
Is there a way of avoiding this behaviour?
Isn't that what hidden parameters are for to start with...?
<form action="http://www.example.com" method="GET">
<input type="hidden" name="a" value="1" />
<input type="hidden" name="b" value="2" />
<input type="hidden" name="c" value="3" />
<input type="submit" />
</form>
I wouldn't count on any browser retaining any existing query string in the action URL.
As the specifications (RFC1866, page 46; HTML 4.x section 17.13.3) state:
If the method is "get" and the action is an HTTP URI, the user agent takes the value of action, appends a `?' to it, then appends the form data set, encoded using the "application/x-www-form-urlencoded" content type.
Maybe one could percent-encode the action-URL to embed the question mark and the parameters, and then cross one's fingers to hope all browsers would leave that URL as it (and validate that the server understands it too). But I'd never rely on that.
By the way: it's not different for non-hidden form fields. For POST the action URL could hold a query string though.
In HTML5, this is per-spec behaviour.
See Association of controls and forms - Form submission algorithm.
Look at "4.10.22.3 Form submission algorithm", step 17. In the case of a GET form to an http/s URI with a query string:
Let destination be a new URL that is equal to the action except that
its <query> component is replaced by query (adding a U+003F QUESTION
MARK character (?) if appropriate).
So, your browser will trash the existing "?..." part of your URI and replace it with a new one based on your form.
In HTML 4.01, the spec produces invalid URIs - most browsers didn't actually do this though...
See Forms - Processing form data, step four - the URI will have a ? appended, even if it already contains one.
What you can do is using a simple foreach on the table containing the GET information. For example in PHP :
foreach ($_GET as $key => $value) {
$key = htmlspecialchars($key);
$value = htmlspecialchars($value);
echo "<input type='hidden' name='$key' value='$value'/>";
}
As the GET values are coming from the user, we should escape them before printing on screen.
You should include the two items (a and b) as hidden input elements as well as C.
I had a very similar problem where for the form action, I had something like:
<form action="http://www.example.com/?q=content/something" method="GET">
<input type="submit" value="Go away..." />
</form>
The button would get the user to the site, but the query info disappeared so the user landed on the home page rather than the desired content page. The solution in my case was to find out how to code the URL without the query that would get the user to the desired page. In this case my target was a Drupal site, so as it turned out /content/something also worked. I also could have used a node number (i.e. /node/123).
If you need workaround, as this form can be placed in 3rd party systems, you can use Apache mod_rewrite like this:
RewriteRule ^dummy.link$ index.php?a=1&b=2 [QSA,L]
then your new form will look like this:
<form ... action="http:/www.blabla.com/dummy.link" method="GET">
<input type="hidden" name="c" value="3" />
</form>
and Apache will append 3rd parameter to query
When the original query has array, for php:
foreach (explode("\n", http_build_query($query, '', "\n")) as $keyValue) {
[$key, $value] = explode('=', $keyValue, 2);
$key = htmlspecialchars(urldecode($key), ENT_COMPAT | ENT_HTML5);
$value = htmlspecialchars(urldecode($value), ENT_COMPAT | ENT_HTML5);
echo '<input type="hidden" name="' . $key . '" value="' . $value . '"' . "/>\n";
}
To answer your first question yes the browser does that and the reason is
that the browser does not care about existing parameters in the action URL
so it removes them completely
and to prevent this from happening use this JavaScript function that I wrote
using jQuery in:
function addQueryStringAsHidden(form){
if (form.attr("action") === undefined){
throw "form does not have action attribute"
}
let url = form.attr("action");
if (url.includes("?") === false) return false;
let index = url.indexOf("?");
let action = url.slice(0, index)
let params = url.slice(index);
url = new URLSearchParams(params);
for (param of url.keys()){
let paramValue = url.get(param);
let attrObject = {"type":"hidden", "name":param, "value":paramValue};
let hidden = $("<input>").attr(attrObject);
form.append(hidden);
}
form.attr("action", action)
}
My observation
when method is GET and form is submitted, hidden input element was sent as query parmater. Old params in action url were wiped out. So basically in this case, form data is replacing query string in action url
When method is POST, and form is submitted, Query parameters in action url were intact (req.query) and input element data was sent as form data (req.body)
So short story long, if you want to pass query params as well as form data, use method attribute as "POST"
This is in response to the above post by Efx:
If the URL already contains the var you want to change, then it is added yet again as a hidden field.
Here is a modification of that code as to prevent duplicating vars in the URL:
foreach ($_GET as $key => $value) {
if ($key != "my_key") {
echo("<input type='hidden' name='$key' value='$value'/>");
}
}
Your construction is illegal. You cannot include parameters in the action value of a form. What happens if you try this is going to depend on quirks of the browser. I wouldn't be surprised if it worked with one browser and not another. Even if it appeared to work, I would not rely on it, because the next version of the browser might change the behavior.
"But lets say I have parameters in query string and in hidden inputs, what can I do?" What you can do is fix the error. Not to be snide, but this is a little like asking, "But lets say my URL uses percent signs instead of slashes, what can I do?" The only possible answer is, you can fix the URL.
I usually write something like this:
foreach($_GET as $key=>$content){
echo "<input type='hidden' name='$key' value='$content'/>";
}
This is working, but don't forget to sanitize your inputs against XSS attacks!
<form ... action="http:/www.blabla.com?a=1&b=2" method ="POST">
<input type="hidden" name="c" value="3" />
</form>
change the request method to' POST' instead of 'GET'.

How do I remove the query-string from my URL redirect

So i made this script below so that someone can enter an order ID and it would redirect to the following http://domain.tld/order/254441.
but it give me a query-string of ?webid=254441 at the end the URL. How do I remove this?
function urlRedirect(){
var action_src = "/orders/" + document.getElementsByName("webid")[0].value;
var form_url = document.getElementById('form_url');
form_url.action = action_src ;
}
<p>Search by ID</p>
<form id="form_url" onsubmit="urlRedirect()"><input name="webid" type="text" /> <input type="submit" value="Search" /></form>
And if anyone has suggestions on making the code better that would be great! :)
Thanks.
Change the method of your form to "POST".
<form id="form_url" onsubmit="urlRedirect()" method="POST">
HTTP POST requests supply additional data from the client (browser) to the server in the message body. In contrast, GET requests include all required data in the URL. When the method is GET, all form data is encoded into the URL, appended to the action URL as query string parameters. With POST, form data appears within the message body of the HTTP request.
See the documentation.

URL path gets converted to query string on jquery

I am trying to get a button to load a new html page in a website I am building with jinja2. The button action in jquery is as follows:
HTML
<input id="str_A" class="form-control-custom" name="str_A" size="30" type="text" placeholder="1st String" />
<input id="str_B" class="form-control-custom" name="str_B" size="30" type="text" placeholder="2nd String" />
<button id="calcdynamic" class="btn btn-lg btn-outline-success">Calculate Edit Distance</button>
JQUERY
$("#calcdynamic").click(function(){
var str_A = $("#str_A").val();
var str_B = $("#str_B").val();
var url1 = "dynamic/"+str_A+"/"+str_B;
window.location. = url1;
});
Now, here's the problem:
I need to pass data in the url path like http://127.0.0.1:5000/dynamic/sgsdgdgsdgd/sdgsdg, not as a query string as http://127.0.0.1:5000/dynamic/?str_A=sgsdgdgsdgd&str_B=sdgsdg. However when I try to reach the url through the jquery call method, I am sent to the query string link, which is a redirectment to the same page I am in at the moment, http://127.0.0.1:5000/dynamic/.
I use flask server (python) and it is configured to redirect like this:
#app.route('/dynamic/')
#app.route('/dynamic/<str_A>/<str_B>')
def dynamic(str_A=None, str_B=None):
At first, I thought this was a problem with flask server, but if I manually type in the URL http://127.0.0.1:5000/dynamic/sgsdgdgsdgd/sdgsdg it works fine.
Can anybody help please, it looks like a simple thing, but I haven't been able to figure out why it happens so far.

HTML: Form Post adds escape slashes

I'm trying to pass an Object to the server with html post. I've already serialized the object and verified that there were no errors in that process. After I hit the submit button I receive a json string with several escape slashes and I don't know why or how I can prevent that from happening. I'm using node.js and the express module.
This is a snippet of the output I get.
{"obj":"{\"nodes\":[{\"id\":0,\"role\":\"sensor\",\"spy\":false,\"correctData\":true,\"port\":8000,\"requiresData\":[],\"connectedTo\":[]},<
HTML:Post
<form action="/result" method="post" enctype="json" autocomplete="off">
<input id="obj" name="obj" required>
<button type="button" name="action" value="getResult"
onclick="generateJSON(true)">generateJSON </button>
<button>Generiere Knoten</button>
</form>
Javascript:
function generateJSON(loaded){
if(loaded) {
var stuff = {nodes: localData, edges: localEdges};
stuff = JSON.stringify(stuff);
console.log("Result?:" + stuff);
$('#obj').val(stuff);
}
}
It should be noted that the json string presented in that input field looks perfectly fine. Snippet:
{"nodes":[{"id":0,"role":"sensor","spy":false,"correctData":true,"port":8000,"requiresData":[],"connectedTo":[]},
I found this answer which helped me initially since I made the same mistake but somehow I'm still missing something.
Edit: Found a solution
I found a way to delete those backslashes and thus got a working json again. Leslie pointed me in the right direction - thanks again. I'm still unsure why this happens in the first place.
myJSONString = myJSONString.replace(/\\/g, "");

custom search bar on my custom homepage

I need to constantly search files such as smss.exe at http://www.winpatrol.com/db/pluscloud/.
Is there a way I can make a customized searchbar on my custom homepage that will do this for me?
So if I type smss into the search bar it will take me to http://www.winpatrol.com/db/pluscloud/smss.html
I tried in pure HTML with GET requests and can't find a way to do it. I was thinking maybe there is a Javascript way or something.
Something like this is pure Javascript and will work, but if the user enters a non-existent page on that site, it will just lead to their not found page.
You could use server side PHP or something similar to achieve this in a better way.
Here is the JS solution with little error checking:
<form onsubmit="return redirect()">
<input id="search_form_input" type="text" name="query" />
<input type="submit" value="Search" />
</form>
<script type="text/javascript">
function redirect()
{
var query = document.getElementById('search_form_input').value;
if (query != '') {
window.location = 'http://www.winpatrol.com/db/pluscloud/' + query + '.html';
}
return false;
}
</script>
Google custom search is what you're probably looking for.

Categories