$_POST not populating after fetch - javascript

I have spent hours chasing this and hope someone has a simple answer. I am using fetch to execute a routine. The server does not seem to populate the post values. I simplified the code to try and isolate it. A simple html form makes js request which issues a fetch including post of username and pwd. The values get passed to the server but the target php page has the $_POST array empty. Code follows. Any ideas?
web page initiating the request
***
<html>
<head>
<script src="/js/2.js"></script>
</head>
<body>
<h1>Who are you?</h1>
<form action="" method=POST>
<label>User Name</label>
<input id=username type=text autocomplete='username' name=username>
<label>Password</label>
<input id=pwd type=password autocomplete='current-password' name=pwd>
<input type=submit value="log in" onclick="login();">
</form>
</body>
</html>***
javascript fetching the response from the php page
***
async function login(){
let content = "username=buddy&pwd=xxxxxxxxx";
let response = await fetch("http://example.com/lib/2.php",{method: "POST", body: content });
var text = await response.text();
if(text == 1){
window.open("http://example.com", "_self");
}else{
alert(text);
}
}***
**php page where post does not populate**
***
<?php
echo "user name is ".$_POST['username'];
?>***

UPDATE: It turns out there was nothing wrong with the code in the first place. The introduction of formdata working was a fluke. On further testing, it failed as well. In fact, execution of the code sometimes worked and sometimes did not. I traced the problem down to the user of session_start. I need to do more research on the use of session_start so I am not sure why it causes the problem but I suspect that the $_POST is being associated with the session id and some of the time the session ids match and the post is visible and in other cases the session ids are different and the post is missing.

Related

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.

Sending AJAX POST to PHP is not working?

I swear this was working properly earlier, but now it's not so I clearly messed something up.
I'm making a form where the inputted info gets AJAX posted to my PHP file, which just outputs the username and password. Right now I even hardcoded the data being sent to just a string and the php file just printing that for testing purposes. However, when I click submit, it doesn't go to my loginProcess.php page, but it just stays on the page and prints to the console "hello","success", and "test", which indicates it went through the full Process() function.
My url is correct and in the same directory as the index.html file. I've tried different things such as using $.post() or making the submit button a type="input". If you see the form line I commented out before the non-commented one, that's me trying to send the data directly without going through ajax and it works fine and outputs the loginProcess.php (however my project requires going through ajax). Anyone know what's going on?
Here's my html file:
<!DOCTYPE html>
<html>
<head>
<!-- <script src="frontEnd.js"></script> -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<title>Login System</title>
</head>
<style>
</style>
<body>
<center>
<p><b>LOGIN SYSTEM</b></p>
<!-- <form id="login" action ="loginProcess.php" method="post"> -->
<form name = "loginform">
UCID:<br>
<input type="text" name="username"><br>
Password:<br>
<input type="password" name="password"><br><br>
<button type="button" onclick = "Process()">Submit</button>
</form>
</center>
</body>
<script>
function Process() {
console.log("hello")
var ucid = document.loginform.username.value;
var pw = document.loginform.password.value;
$.ajax({
type:"POST",
url: "loginProcess.php",
data: "ajaxUCID=TESTUSERNAME",
success: function(){
console.log("success")
},
error: function(){
console.log("error")
}
});
// $.post("loginProcess.php",{ajaxUCID:"TESTUSERNAME"});
console.log("test")
}
</script>
Here's my loginProcess.php file:
<!DOCTYPE html>
<html>
<head><title>process</title></head>
<body>
<?php
$ucidPHP = $_POST["ajaxUCID"];
echo "Username is ".$ucidPHP;
// $pwPHP = $_POST["ajaxPW"];
// echo "Password is ".$pwPHP;
?>
</body>
</html>
Try this -
<script>
function Process() {
var ucid = document.loginform.username.value;
var pw = document.loginform.password.value;
$.ajax({
type:"POST",
url: "loginProcess.php",
data: {ajaxUCID:TESTUSERNAME},
success: function(){
console.log("success")
},
error: function(){
console.log("error")
}
});
}
</script>
Hope this will work for you.
When you click on your network tab of Google chrome or equivalent of the other browser and then send your Ajax request to observe your packet delivered what result do you have ?
If you have a packet with an error can you tell us witch one, and if you receive a good header (without errors) , check the information inside it to see if it throws correct informations, like the data form in your Ajax post.
After that if the information are correct and the data structure is correct, to test, I usually do the following code to test the entire post received :
if(isset($_POST)){
var_dump($_POST); // this will show all posts received
}
Let me know if it works for you ;)
I don't get your problem, the code is working with me and returning the result successfully.
I think you mean that why the returned results doesn't show on the same page of the form.
Here is the correct code and below it is the explanation
index.php
<!DOCTYPE html>
<html>
<head>
<!-- <script src="frontEnd.js"></script> -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<title>Login System</title>
</head>
<style>
</style>
<body>
<center>
<p><b>LOGIN SYSTEM</b></p>
<!-- <form id="login" action ="loginProcess.php" method="post"> -->
<form name = "loginform">
UCID:<br>
<input type="text" name="username"><br>
Password:<br>
<input type="password" name="password"><br><br>
<button type="button" onclick = "Process()">Submit</button>
</form>
<div id="responseFromServer"></div>
</center>
</body>
<script>
function Process() {
console.log("hello")
var ucid = document.loginform.username.value;
var pw = document.loginform.password.value;
$.ajax({
type:"POST",
url: "loginProcess.php",
data: {"ajaxUCID":ucid},
success: function(response){
document.getElementById("responseFromServer").innerHTML = response;
console.log("success")
},
error: function(){
console.log("error")
}
});
// $.post("loginProcess.php",{ajaxUCID:"TESTUSERNAME"});
console.log("test")
}
</script>
the code you provided was actually working properly, its just you didn't pick the result to display it on your page.
that was done by adding a div where I will place the response.
<div id="responseFromServer"></div>
and in the success callback of the ajax call, I just catched the response sent back from the server and placed it right inside the div, like so:
document.getElementById("responseFromServer").innerHTML = response;
That should work
Update#1:
He wanted to redirect to the php page.
in plain English, you should use ajax requests when you want to work with the server, send requests or get results without reloading the page, you can read more here Getting Starting with AJAX
AJAX stands for Asynchronous JavaScript And XML. In a nutshell, it is the use of the XMLHttpRequest object to communicate with servers. It can send and receive information in various formats, including JSON, XML, HTML, and text files. AJAX’s most appealing characteristic is its "asynchronous" nature, which means it can communicate with the server, exchange data, and update the page without having to refresh the page.
so in your case that you want to redirect the user, you don't really want to use ajax in this case you can simply do that with plain html form tag.
a form tag can have multiple attributes, here we are concerned with 2 :
action
method
Here is how you can update the code to get to your results
first: the form part:
<form name = "loginform" method="POST" action="loginProcess.php">
UCID:<br>
<input type="text" name="ajaxUCID"><br>
Password:<br>
<input type="password" name="password"><br><br>
<button type="submit" >Submit</button>
</form>
I've added 2 attributes, which are:
method: I set it to POST, because this is the http request type which you accept on your server [your PHP file you used $_POST].
action: I set it to the relative path of the file which should recieve your request, in our case its "loginProcess.php"
Then I changed the name of the input where we enter the username or UCID to be the same as the one you are receiving in your PHP file.
in your php you were accepting a request parameter $_POST["ajaxUCID"] this means that you are accepting a POST request and you want a parameter called ajaxUCID , that must be the name of the input. this is why I did that <input type="text" name="ajaxUCID">
I have also stopped the onClick action on the button to prevent the ajax request, also I have changed its type to "submit" so that once its clicked, it will automatically submit the form for you.
I hope that helped now, if you need furthur help, leave a comment

Getting around CORS with embedded google forms

I'm trying to send form data to google via an embedded form.
I found this post that seems to answer my question but I'm getting CORS errors. Is there a way to solve this?
Other posts seem to say that CORS isn't an issue but I'm getting the errors.
Here is my code:
-JS-
function ajax_post() {
var field1 = $('#email').val();
$.ajax({
url: "https://docs.google.com/forms/d/e/xxxxxxxxxxxxxxxxxxxxxx/formResponse",
data: {"entry.xxxxxxxxxx": field1},
type: "POST",
dataType: "xml",
statusCode: {
0: function() {
//Success message
},
200: function() {
//Success Message
}
}
});
}
-HTML-
<form id="emailForm" target="_self" onsubmit="" action="javascript: ajax_post()">
<input id="email" type="text" autocomplete="off" tabindex="0" name="entry.xxxxxxxxxx" required>
<button id="send" type="submit">Submit</button>
</form>
The “No 'Access-Control-Allow-Origin' header is present on the requested resource” message indicates that responses from https://docs.google.com/forms/d/e/xxxx/formResponse URLs currently don’t include the Access-Control-Allow-Origin response header, so browsers won’t allow your frontend JavaScript code to access the response.
Given that, from your frontend code there’s no way you can tell if the POST request succeeds or not. But barring any other problems, it seems like the request will always succeed. If the request doesn’t reach the server at all (due to some network error) then you’ll hit a different failure condition that is observable from your frontend code so you can actually catch it.
So the way you know the request has successfully reached the server is just that you don’t get any other failure that’s observable from your frontend code.
I've found that it's actually easier to just POST the form with a hidden iframe as its target, and capture that iframe reload when the response is submitted.
For example, if this is your form:
<form id="my-form" target="my-response-iframe" action="https://docs.google.com/forms/u/1/d/e/<YOUR-ID>/formResponse" method="post">
<input type="text" name="entry.12345678" value="" required>
<input type="submit">
</form>
Then include an iframe on the same page, with the same id AND name you put as target in the form:
<iframe id="my-response-iframe" name="my-response-iframe"></iframe>
When the form is submitted, it should reload that iframe with the "Your response has been recorded." page from Google. We can catch that reload with JavaScript, so include this after your form and iframe:
<script type="text/javascript">
// set the target on the form to point to a hidden iframe
// some browsers need the target set via JavaScript, no idea why...
document.getElementById('my-form').target = 'my-response-iframe';
// detect when the iframe reloads
var iframe = document.getElementById('my-response-iframe');
if (iframe) {
iframe.onload = function () {
// now you can do stuff, such as displaying a message or redirecting to a new page.
}
}
</script>
You can't check whether the response was submitted correctly because you can't inspect the contents of a cross-origin iframe (that'd be a huge security risk), so just assume that if this iframe reloads, the response was ok.
You can hide the iframe with the following CSS:
visibility: hidden
height: 1px;
Much cleaner if you ask me, with no console errors or failed requests.

Sending form data to HTML Page and Retrieving it with Javascript without any PHP/Python

I've read a few articles and a question thread on sending form data to another html page, but the solutions didn't solve the issue for me.
Basically, I have a form with a bunch of data:
<form id="registration" name="registration" action="register.html" method="POST">
In register.html, I tried accessing an input text field with id and name as "username" with this:
var x = document.getElementById("registration").elements.namedItem("username").value;
The console stated that it cannot read property of null. How can I access these values with Javascript only? Frameworks are fine but not PHP /Python.
I'm sure that none of this can be safe, so use caution.
If you don't care about the info being super obvious, then you can make the action of the the form the new page you want, and the method can be 'GET'.
EDIT: I should mention this will go through the url, as such
domain.com?someKey=someValue&someOtherKey=someOtherValue
On the new page, you can parse the url for the query string for everything.
You can grab that stuff out of the 'href' property from the location.
window.location.href
// * Credit for this puppy goes to theharls, nice and fast
var params = window.location.search.slice(1).split("&");
//=> ["say=Hi", "to=Mom"]
Another option on (modern ?) browsers is Local Storage.
Use javascript to to set things like,
localStorage.setItem('foo', 'bar');
Great reference for local storage here.
https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
I ran into something like this the other day. Turns out you can just get the values with jQuery.
var userName = $("input[type=text][name=username]").val();
Just put it into a function that's called in the form's onsubmit.
<script>
function getFormData() {
var userName = $("input[type=text][name=username]").val();
// Do what you want with the data
return true;
}
</script>
<form id="registration" name="registration" action="register.html" onsubmit="return getFormData();" method="POST">
<input type="text" name="username" />
</form>
However, this doesn't keep the data when you load the next page. To do that, just commit the value into sessionStorage.
function saveFormData() {
var userName = $("input[type=text][name=username]").val();
sessionStorage.setItem("user", userName);
return true;
}
And then on the next page (the one you're calling resgister.html) you can use this code to retrieve it.
var userName = sessionStorage.getItem("user");
I hope this helps!
A webpage can't receive POST data. Send it using method="GET" instead, then retrieve it on the target page using JS as follows:
<script>
var params = window.location.search.slice(1).split("&");
// params is ["say=Hi", "to=Mom"]
</script>
You can easily target the selectors by querySelector. The value will no longer be null.
<form id="registration" name="registration" action="register.html" method="POST">
<input type="text" class="username" value="abcdefg">
</form>
<script>
var x = document.querySelector("#registration .username").value;
//check your code in devtools
console.log(x);
</script>
jsfiddle

Delays/inconsistencies in AJAX refresh

I've been working on a web app that allows users to submit content and have that content, and today I've been seeing some unexpected results without making any significant changes.
The basic functionality of the app is that the user submits some POST data from a form on a web page index.php, whereupon a PHP script submit.php is run to add the data to a table in a database. Meanwhile, a Jquery function on index.php is refreshing the contents of a div with rows selected from the table by means of a script load.php, and the function is called once per second.
The problem is that today, suddenly, I'm seeing long (10-20 minute) delays between when the data is added to the table and when it shows up in the Jquery-refreshed div. Moreover, the div flickers back and forth between its existing contents and the new data set with the added values, as if it were alternating between the realtime results of load.php and a previous call to the same script.
I've checked the MySQL database before and after submit.php is called and I've verified that the data is being added instantaneously once it's submitted, so the problem has something to do with how the load.php script is called from Jquery.
This just started today. Strangely, I've been seeing this same behavior with another AJAX app that I built earlier to test the same I/O mechanism, and I haven't touched that app's code in over a week. My system administrator says there haven't been any changes to the server that would account for this.
I've posted all the code to provide all necessary information, but I think the problem is either in load.php or the javascript updateMyContent() in index.php.
index.php
<script language="JavaScript">
setInterval("updateMyContent();",1000);
$(function(){
updateMyContent=function(){
$('#refreshData').load("./module/load.php").fadeIn("slow");
}
});
</script>
<script language="JavaScript">
$(document).ready(function(){
$('#submitForm').on('submit',function(e){
$.ajax({
url:'./module/submit.php',
data:$('#submitForm').serialize(),
type:'POST',
success:function(data){
console.log(data);
$("#success").show().fadeOut(5000);
$('#textID').val('');
},
error:function(data){
$("#error").show().fadeOut(5000);
}
});
e.preventDefault();
});
});
</script>
<div style="float: right;
top: 0;
" id="submitDiv">
<form id="submitForm" action="" method="post">
<textarea id="textID" type="text" name="content" rows=5></textarea>
<input type="submit" value="send" name="submit"/>
</form>
<br>
<span id="error" style="display: none; color:#F00">error</span>
<span id="success" style="display:none; color:#0C0">success</span>
</div>
<div style="float: center;" id="refreshData"></div>
submit.php
<?php
if(isset($_POST['content']))
{
$content=$_POST['content'];
$dsn="mysql:host=someserver.net;dbname=thisdb;charset=utf8";
$db=new PDO($dsn,'thisdb','password');
$insertSQL="insert into submission (content) values (?)";
$stmt=$db->prepare($insertSQL);
$stmt->execute(array($content));
}
else
{
echo "FAIL!";
}
?>
load.php
<?php
try
{
$dsn="mysql:host=someserver.net;dbname=thisdb;charset=utf8";
$db=new PDO($dsn,'thisdb','password');
$PDOsql="select * from submission order by id desc";
$stmt=$db->query($PDOsql);
foreach($stmt->fetchAll(PDO::FETCH_ASSOC) as $resultRow)
{
printf("%s<br>",$resultRow["ID"]);
printf("%s<br>",htmlspecialchars($resultRow["content"]));
$stmt->closeCursor();
}
}
catch(PDOException $ex)
{
echo "an error occurred! ".$ex->getMessage();
}
?>
The issue with it taking so long to return the Ajax response is probably that the table submissions has grown. Rather than each second loading all the submissions, append only new submissions to the div. I.e. keep track of the last id received and use this in the query so the where clause is limited.
Moreover, the div flickers back and forth between its existing contents and the new data set with the added values, as if it were alternating between the realtime results of load.php and a previous call to the same script.
Ajax response can be cached by the browser just like anything else. To prevent that, you can:
Put no-cache headers in the page that processes the request to prevent browser caching of the Ajax responses. IE is particularly stubborn and will require the most forceful headers.
Add a parameter to your Ajax request that is a random number, to make every request unique.
Tell JQuery to prevent caching (it just does #2 for you). Use $.ajaxSetup ({ cache: false }); or add the cache: false, attribute to each call to $.ajax

Categories