I have a server running locally which has an in built rest api. To login through this api, we need to send username, password and organization as parameters to url localhost:8090/ehr/api/v1/login via POST method and server returns an auth token as response. when I try to do this directly without user input from form through the following code:
<html>
<body>
<script type="text/javascript">
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.write(this.responseText);
console.log(this.responseText);
}
};
xhttp.open("POST", "http://localhost:8090/ehr/api/v1/login", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("username=admin&password=admin&organization=123456");
</script>
</body>
</html>
It works perfectly fine and auth token is returned as json, but if I try to do the same through user form input via following code:
<html>
<body>
<form method="POST">
<input type="text" name="username" id="username" placeholder="Username">
<input type="password" name="password" id="password" placeholder="Password">
<input type="text" name="organization" id="organization" placeholder="Organization">
<button id="submit" onclick="login()">Let me in!</button>
<br><br>
</form>
<script type="text/javascript">
function login() {
var user=document.getElementById("username").value;
var pass = document.getElementById("password").value;
var org = document.getElementById("organization").value;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.write(this.responseText);
console.log(this.responseText);
}
};
xhttp.open("POST", "http://localhost:8090/ehr/api/v1/login", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
var param = "username="+user+"&password="+pass+"&organization="+org;
xhttp.send(param);
}
</script>
</body>
</html>
this code throws error
login.html:26 XHR failed loading: POST "http://localhost:8090/ehr/api/v1/login"
What is wrong with the second code and how to correct it?
send your params in this way
xhttp.send('username=user&password=pass&organization=org');
I figured it out myself, I just removed form tag from html and used simple input tags instead. This solved the problem maybe because forms on submission try to load a new page instead of staying on the same page, but the parameters were intended to get fetched from the original page. Which was not able to happen as new page got loaded every time submit button was clicked.
Related
The snippet shows my html and js. In my php controller I just print_r($_POST) but I only see the form data for myName I can't figure out how to access zzz
UPDATE: I added some code to make sure the send request is complete. However, if I don't submit the form the controller doesn't execute from just issuing the xhttp request. I still can't get any js data into php. I could create hidden inputs and fill those in from js and the submit but that seems ugly. can someone help?
function swagSend() {
event.preventDefault();
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "https://www.sustainablewestonma.org/wp-content/themes/twentytwelve-child/php/send_email.php", true);
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
console.log(xhttp.responseText);
}
}
var henry = "henry"
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("zzz=" + henry);
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("myForm").submit();
}
}
}
<form action="https://www.sustainablewestonma.org/wp-content/themes/twentytwelve-child/php/send_email.php" method="POST" id='myForm'>
<input type='text' name='myname'>
<button type='submit' value='submit' onClick=swagSend();>Submit</button>
</form>
If you are making an Ajax call, there is no reason to submit the form. remove it.
If you want the form data to be submitted in the Ajax call, you need to read the form input values and build up the list yourself.
function swagSend(event) {
event.preventDefault();
var xhttp = new XMLHttpRequest();
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.open("POST", "https://www.sustainablewestonma.org/wp-content/themes/twentytwelve-child/php/send_email.php", true);
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
console.log(xhttp.responseText);
}
}
var henry = "henry"
var name = encodeURIComponent(document.getElementById("myname").value)
xhttp.send("zzz=" + henry + '&myname=' + name);
}
<form action="https://www.sustainablewestonma.org/wp-content/themes/twentytwelve-child/php/send_email.php" method="POST" id='myForm'>
<input type='text' name='myname' id='myname'>
<button type='submit' value='submit' onClick="swagSend(event)">Submit</button>
</form>
you should only send with xhttp.send and not additionally with document.getElementById("myForm").submit();
I'd need some help with my HTTP request. Here's the setup:
A webpage load an image to a form and send it to a python server running bottle (with the form or a custom http request)
Bottle receive the file, give it as an input for a python script, receive the result and return it to the webpage
On bottle's website there's an example with a form: https://bottlepy.org/docs/dev/tutorial.html#file-uploads I've tried it and it works. Here's the code I used:
<html>
<head>
</head>
<body>
<form action="http://localhost:8080/solve" method="POST" enctype="multipart/form-data" norm="form" id='myForm'>
Select a file: <input type="file" name="upload"/>
<input type="submit" value="Start upload" />
</form>
</body>
</html>
In bottle I have:
#route('/solve', method='POST')
def solve():
file = request.files.get('upload')
name, ext = os.path.splitext(file.filename)
if ext not in ('.png','.jpg','.jpeg'):
return 'File extension not allowed.'
print(file.name)
resolved = sudoku.solve(file.file)
return str(resolved)
This "works", but the form redirects me to localhost:8080 and it's not what I want. I tried putting the target to a hidden iFrame, which prevent the redirection, but I don't manage to access the result in the body of the iFrame...
What I want: Make an HTTP request similar to the one made by the form. So I tried:
<html>
<head> </head>
<body>
<form enctype="multipart/form-data" norm="form" id="myForm">
Select a file:
<input id="fileInput" type="file" name="upload" accept="image/png, image/jpeg, image/jpg" />
<input type="submit" value="Start upload" />
<label class="button-upload" onclick="send()">Upload</label>
</form>
</body>
<script>
var _file = null;
function send() {
var file = document.getElementById("fileInput").files[0]
console.log(file)
var url = "http://localhost:8080/solve";
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader(
"Content-Type",
"multipart/form-data; boundary=---------------------------169461201884497922237853436"
);
var formData = new FormData();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
};
formData.append("upload", file);
xhr.send(formData);
}
</script>
</html>
I've checked with the developper tool in network and the request seems to be the same as the one sent by the form, though bottle can't find the file.
The file = request.files.get('upload') returns None and file = request.files returns <bottle.FormsDict object at 0x7ff437abf400> so there's something but I don't understand how to access it!
Any help would be greatly appreciated!
Your JavaScript code seems fine, except for where you set request headers with xhr.setRequestHeader. FormData handles multipart encoding for you, you don't need to set request headers manually. I just tried it, and it seems to be working fine with bottlepy.
Overall, change your send() function as follows:
function send() {
var file = document.getElementById("fileInput").files[0]
console.log(file)
var url = "http://localhost:8080/solve";
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
var formData = new FormData();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
};
formData.append("upload", file);
xhr.send(formData);
}
I am trying to build a very simple web service using PHP. But I am unable to get response from the PHP (which is sending the data in a JSON format). When I print my responseText using console.log(), it shows as empty string. PHP is accepting some data using get method and when I enter PHP file and query parameter through url, data is displayed. I am unable to bring this data back to my HTML file. Please help me. I tried reading lots of question on https://stackoverflow.com/ and i also referred to lots of code and videos but cant find any solution yet
This is my HTML and Javascript code:
<html>
<head>
<title>Agent Details</title>
<head>
<body>
<form method="get">
<h1>Enter Agent ID</h1>
<input name="userd" id="userid" type="text" placeholder="enter agent id"></input><br>
<input type="submit">
</form>
<div id="display">
</div>
<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(xhttp);
document.getElementById("display").innerHTML=xhttp.responseText;
}
};
xhttp.open("GET", "test.php", true);
xhttp.setRequestHeader("Content-Type", "application/json");
xhttp.send();
</script>
</body>
</html>
This is my PHP code:
<?php
$con = mysqli_connect("localhost","root","","raw");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_GET["userid"])){
$username=$_GET["userid"];
$query="SELECT * FROM agents WHERE agent_id='$username'";
$results=mysqli_query($con,$query);
$rows=mysqli_fetch_assoc($results);
$myJson=json_encode($rows);
header('Content-Type: application/json');
echo $myJson;
}
mysqli_close($con);
?>
Screenshots
This show when I directly access PHP file its echos output:
php running successfully
Here you can see that communication is happening between client and web-service since status is "200" and status message is "OK". But when I access PHP through Ajax, responseText is empty
response text shown as empty when used ajax call
You're not passing any parameters in your AJAX query: xhttp.open("GET", "test.php", true);. In the PHP example screenshot, you're passing userid as a GET parameter: test.php?userid=1.
First: You are not passing any params via AJAX in line:
xhttp.open("GET", "test.php", true);
Second: You are sending when the page starts, and does not have a value defined in the field, the correct manner would be create a function with, call it when the button is pressed (remove the SUBMIT value for TYPE, and replace it with BUTTON), then call a function, like this:
<html>
<head>
<title>Agent Details</title>
<head>
<body>
<form method="get">
<h1>Enter Agent ID</h1>
<input name="userd" id="userid" type="text" placeholder="enter agent id"></input><br>
<input type="button" onclick="ajax()" value="submit">
</form>
<div id="display">
</div>
<script>
function ajax(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(xhttp);
document.getElementById("display").innerHTML=xhttp.responseText;
}
};
xhttp.open("GET", "test.php?userd="+document.getElementById('userid').value, true);
xhttp.setRequestHeader("Content-Type", "application/json");
xhttp.send();
}
</script>
</body>
</html>
Hope it helps!
I am trying to post form data, an array to php file without page refresh. I am using ajax which doesn't seem to be working. Below is form syntax and ajax. Can somebody please help me? Thanks.
<form name="postcontent" id="postcontent">
function[]; //just for an example of data
<button type="button" id="submitform" onclick="posttophp" >Send</button>
<script>
function posttophp() {
var xhttp = new XMLHttpRequest();
xhttp1.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("submitform").innerHTML = this.responseText;
}
};
xhttp.open("POST", "options.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("
function_Options1[]=function[]")
}
</script>
In php, I store function_Options1[] in another variable and use further.
Two ideas to try:
Maybe the script should be placed before calling the function, but not sure about this.
Try onclick="posttophp();"
I've a JSP page which includes a checkbox, so when i try to submit the form using the conventional javascript way of document.forms[0].submit(); the form gets refreshed and the checkbox values are not getting retained.
Can anybody help me on how to send the form value using only AJAX. I don't need the way to send using JQuery.
This is the code I had used for sending using form submit:
function relatedAER(){
......
document.forms[0].literatureSelected.value = litNO + "&";
document.forms[0].opCode.value = "relatedAER";
document.forms[0].target='_self';
document.forms[0].action="<%=request.getContextPath()%>/litaer.do?selected="+selected;
document.forms[0].submit();
}
I hope next time, you'll put some effort, into creating even a simple code, and showing us instead of asking for a script.
Now, that bieng said: This will submit a username to a php file, called fetch.php
HTML
<input type='text' name='user' id='user' /><br/>
<input type='submit' name='submit' onclick='check()' />
<div id='output'></div>
Ajax:
function check(){
var xmlhttp;
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}else{
xmlhttp = ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState === 4 && xmlhttp.status === 200){
document.getElementById('output').innerHTML = xmlhttp.responseText;
}
}
get_user = document.getElementById('user').value;
param = "name="+get_user;
xmlhttp.open('POST','fetch.php', true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(param);
}
</script>