After my input, my datas are receive as null - javascript

i'm creating a form to a simple study, but is not working correctly, my form sends the values but my backend flask show with null, i tested the backend with insomnia it is okay, help please
My HTML,JS
<form name="myForm" method="POST">
<p><label for="first_name">First Name:</label>
<input type="text" name="first_name" id="fname"></p>
<p><label for="last_name">Last Name:</label>
<input type="text" name="last_name" id="lname"></p>
<input value="Submit" type="submit" onclick="create_send_Json()">
</form>
<script>
function create_send_Json() {
// get name
var fname = document.forms["myForm"]["fname"].value;
var lname = document.forms["myForm"]["lname"].value;
// make JSON
data = { "fname": fname, "lname": lname };
var jsonData = JSON.stringify(data);
// Send data
var xhr = new XMLHttpRequest();
var url = 'http://localhost:5000/contact';
xhr.open("POST", url);
xhr.setRequestHeader("Content-Type", "application/json");
console.log(jsonData);
xhr.send(jsonData);
return false;
}
</script>
My Flask
#app.route('/contact', methods=['POST','GET'])
def login():
if request.method == 'POST':
data = request.json
print (data)
return jsonify(data)
else:
return render_template('contact.html')

Related

cant read post request response using javscript

I have an html form. The form sends login request to server. The html response from server is put in an iframe.
$(document).ready(function(){
$("#submit").click(function(event){
$("#dummyframe").on('load',function() {
var myiframe = $("#dummyframe").val();
var iframedocument = myiframe.contentDocument;
var response = iframedocument.queryselector("pre");
var errormessage = '{"code":500,"message":"入力項目に誤りがあります","data":{}}';
if (response == errormessage ){
alert('wrong password');
}
else {
alert('password is ok');
}
});
});
});
<iframe name="dummyframe" id="dummyframe" style="display: none;"></iframe>
<form method="post" target="dummyframe" action="https://kintai.jinjer.biz/v1/sign_in">
<input name="company_code" type="hidden" value="1234" />
<input name="email" type="hidden" value="1234" />
<input name="password" type="hidden" value="1234" />
<input type="submit" value= "submit" id= "submit" />
</form>
I want to read response from the server to validate password. If I get error message from server, I want to alert "wrong password" in my html page. Am I missing something? It doesn't work. The code doesn't seem incorrect. Your help is greatly appreciated.
You need to change your script to below:
$(document).ready(function(){
$("#submit").click(function(event){
$("#dummyframe").on('load',function() {
var myiframe = $("#dummyframe");
var iframedocument = myiframe.contentDocument;
if (iframedocument.document) iframedocument = iframedocument.document;
var response = iframedocument.queryselector("pre").innerHTML;
var errormessage = '{"code":500,"message":"入力項目に誤りがあります","data":{}}';
if (response == errormessage ){
alert('wrong password');
}
else {
alert('password is ok');
}
});
});
});

Javascript not properly calling API

I am trying to have my website call my login API, which I have tested from a separate app, and through Postman, and it runs fine. However when I run it through my website, it is not calling the API with the actual values inside the html input item.
Below is my HTML of my attributes:
<div class="container">
<label for="uname"><b>Username</b></label>
<input id= "username" type="text" placeholder="Enter Username" name="uname" required>
<label for="psw"><b>Password</b></label>
<input id= "password" type="password" placeholder="Enter Password" name="psw" required>
<button id="loginButton" type="button" class=""">login</button>
<label>
<input type="checkbox" checked="checked" name="remember"> Remember me
</label>
</div>
Below is my code for my website API call:
<script type="text/javascript">
document.getElementById("loginButton").onclick = function () {
var xhttp = new XMLHttpRequest();
console.log("login button clicked");
var usr = document.getElementById("username").value;
var psw = document.getElementById("password").value;
console.log(usr);
console.log(psw);
xhttp.open("GET", "http://serverAddress/checkHash/"+usr+"/"+psw+"/", true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send();
var response = (xhttp.responseText);
console.log("user logged in");
console.log("the response is:" + response);
//var value = (usr.concat(psw));
//console.log('concat value of both usr and psw is:');
//console.log(value);
if(response != "no") {
//this means the credentials are right
localStorage.setItem("session", usr);
location.href = "userSearch.php";
} else {
window.alert("Incorrect credentials");
}
};
</script>
Below is my Server code:
app.post('/createPhysician/', function(req, res) {
console.log("below is the req body for createPhysician");
console.log(req.body);
var createPromise = interact.createPhysician(
req.body.firstName,
req.body.lastName,
req.body.yearNum,
req.body.position,
req.body.isAttending,
req.body.highRiskTrained);
createPromise.then(function(createResponse) {
res.json("successful"); // returns the physicianID for the createUsers
}).catch(function(err) {
console.log(err);
console.log(req.body);
res.json("Terrible job you botched it");
});
});
Below is my interact sql file:
createPhysician: function(
firstName,
lastName,
yearNum,
position,
isAttending,
highRiskTrained) {
var qry = "insert into Physician (firstName, lastName, yearNum, position, isAttending, highRiskTrained) values ('"+firstName+"', '"+lastName+"', "+yearNum+", '"+position+"', "+isAttending+", "+highRiskTrained+");";
console.log("below is query ran in DBINteract");
console.log(qry);
return runQuery(qry);
}
the error I am getting is as follows:
below is the username given to server.js
[object HTMLInputElement]
below is the value of pass from app
[object HTMLInputElement]
below is the value from server side
TypeError: Cannot read property 'password' of undefined

ajax request function does not work when its called

<script type="text/javascript"src="prototype.js"></script>
<script type="text/javascript">
//<![CDATA[
document.observe("dom:loaded", function() {
function sendRequest() {
var oform = document.forms[0];
var sBody = getRequestBody(oform);
var oOptions = {
method: "post",
parameters: sBody,
onSuccess: function (oXHR, oJson) {
saveResult(oXHR.responseText);
},
onFailure: function (oXHR, oJson) {
saveResult("An error occurred: " + oXHR.statusText);
}
};
var oRequest = new Ajax.Request("edit_status.php", oOptions);
}
function saveResult(sMessage) {
var divStatus = document.getElementById("divStatus");
divStatus.innerHTML = "Request completed: " + sMessage;
}
});
//]]>
</script>
I am new to ajax. i have a project at hand that really need a lot of ajax functionality. I am following this above code from a book i bought. when i copy this code on my local server, the ajax.request function is not working when i click the submit button. It takes me straight to the php page. Please can someone help me look at this?
**
<form method="post" action="SaveCustomer.php"
onsubmit="sendRequest(); return false">
<p>Enter customer information to be saved:</p>
<p>Customer Name: <input type="text" name="txtName" value="" /><br />
Address: <input type="text" name="txtAddress" value="" /><br />
City: <input type="text" name="txtCity" value="" /><br />
State: <input type="text" name="txtState" value="" /><br />
Zip Code: <input type="text" name="txtZipCode" value="" /><br />
Phone: <input type="text" name="txtPhone" value="" /><br />
E-mail: <input type="text" name="txtEmail" value="" /></p>
</form>
<div id="divStatus"></div>
**
**
header("Content-Type: text/plain");
//get information
$sName = $_POST["txtName"];
$sAddress = $_POST["txtAddress"];
$sCity = $_POST["txtCity"];
$sState = $_POST["txtState"];
$sZipCode = $_POST["txtZipCode"];
$sPhone = $_POST["txtPhone"];
$sEmail = $_POST["txtEmail"];
//status message
$sStatus = "";
//database information
$sDBServer = "localhost";
$sDBName = "ajax";
$sDBUsername = "root";
$sDBPassword = "";
//create the SQL query string
$sSQL = "Insert into Customers(Name,Address,City,State,Zip,Phone,`Email`) ".
" values ('$sName','$sAddress','$sCity','$sState', '$sZipCode'".
", '$sPhone', '$sEmail')";
$oLink = mysql_connect($sDBServer,$sDBUsername,$sDBPassword);
#mysql_select_db($sDBName) or $sStatus = "Unable to open database";
if ($sStatus == "") {
if(mysql_query($sSQL)) {
$sStatus = "Added customer; customer ID is ".mysql_insert_id();
} else {
$sStatus = "An error occurred while inserting; customer not saved.";
}
}
mysql_close($oLink);
echo $sStatus;
?>
**
you arent firing the ajax i see you define the options but thats it try
using jquery u can wait for form submission
$('your form').on('submit', function(event){
event.preventDefault();
$.ajax({
url:'your url',
type:'post',
data:'your data',
success:function(data, jxhr){
//your success function
},
error:function(){}
});
});
the e.preventDefault() prevents the synchronous submission from firing default methods
looking at your code the sendRequest() can be changed to sendRequest(event) then add the event.preventDefault. I always have issues with return false

Validation in Ajax From

This is my form in the view..
SendCall is the method in controller to sending email..
#using (Html.BeginForm("SendCall", "Home", FormMethod.Post, new { id = "email-form" }))
{
<label>Name</label>
<input type="text" id="name" value=""/><span class="require"> *</span>
<label>Email:</label>
<input id="Email" type="text" />
<input type="submit" value="Submit" >
}
This is the action code..
[HttpPost]
public ActionResult SendCall(string Date, string Phone, string Name, string Email)
{
string username = "xxxxxx#gmail.com";
string password = "********";
NetworkCredential loginInfo = new NetworkCredential(username, password);
MailMessage msg = new MailMessage();
SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587);
smtpClient.EnableSsl = true;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = loginInfo;
string message = Name + Email; //I have shortened this line.
try
{
msg.From = new MailAddress("yourname#gmail.com", "My Website");
msg.To.Add(new MailAddress("email#gmail.com"));
msg.Subject = "Contact Message";
msg.Body = message;
msg.IsBodyHtml = true;
smtpClient.Send(msg);
return Content("Your message was sent successfully!");
}
catch (Exception)
{
return Content("There was an error... please try again.");
}
}
Can anyone suggest me how to validate this form? By adding some code in ajax code? I want client side validation and not with unobtrusive..

How to ajax POST to php

I can't seem to figure out how to use ajax to post. I made a silly form to try it out and even after having cut it all the way down to just two values, still can't get anything to work. My html is this:
<html>
<head>
<script type="text/javascript" src="j.js"></script>
<title>Test this<
<body>/title>
</head>
<form name="testForm" onsubmit="postStuff()" method="post">
First Name: <input type="text" name="fname" id="fname" /><br />
Last Name: <input type="text" name="lname" id="lname" /><br />
<input type="submit" value="Submit Form" />
</form>
<div id="status"></div>
</body>
</html>
Then, my external javascript is just a single function so far:
function postStuff(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "processForm.php";
var fn = document.getElementById("fname").value;
var ln = document.getElementById("lname").value;
var vars = "firstname="+fn+"&lastname="+ln;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("status").innerHTML = "processing...";
}
While my php just echoes the stuff back:
<?php
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
echo $firstname ." - ". $lastname ."<br />";
?>
I can't find anything wrong in firebug or in chrome's toolsy thingies..
Can anybody who me what I'm doing wrong?
The whole problem is caused by the fact that you are both submitting the form and performing an AJAX call! status is for sure updated, but in the same moment the page is refreshed (notice that the <input>-values disappear)
Simply avoid the form submit by altering the markup,
<form name="testForm" action="" method="">
First Name: <input type="text" name="fname" id="fname" /><br />
Last Name: <input type="text" name="lname" id="lname" /><br />
<input type="button" value="Submit Form" onclick="postStuff();" />
and your code works. Or dont use a form at all. It is to no use when you are AJAXing anyway.
update
I reproduced the whole scenario before answering :
xhr.html
<html>
<head>
<title>Test this</title>
</head>
<body>
<form name="testForm" action="" method="">
First Name: <input type="text" name="fname" id="fname" /><br />
Last Name: <input type="text" name="lname" id="lname" /><br />
<input type="button" value="Submit Form" onclick="postStuff();" />
</form>
<div id="status"></div>
<script>
function postStuff(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "xhr.php";
var fn = document.getElementById("fname").value;
var ln = document.getElementById("lname").value;
var vars = "firstname="+fn+"&lastname="+ln;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
console.log(hr);
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("status").innerHTML = "processing...";
}
</script>
</body>
</html>
xhr.php
<?php
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
echo $firstname ." - ". $lastname ."<br />";
?>
Make the:
<form name="testForm" onsubmit="postStuff()" method="post">
First Name: <input type="text" name="fname" id="fname" /> <br />
Last Name: <input type="text" name="lname" id="lname" /> <br />
<input type="submit" value="Submit Form" />
</form>
into a button tag:
<form name="testForm">
First Name: <input type="text" name="fname" id="fname" /> <br />
Last Name: <input type="text" name="lname" id="lname" /> <br />
<button type="button" onclick="postStuff();">Submit Form!</button>
</form>
The page refreshes from the form submit as far as I can see. You don't need to use a form if you're using ajax.
Also read: Why is using onClick() in HTML a bad practice? since you're enclosing the post in a function anyway.
EDIT: I just noticed your title and head tags are broken in the source you've put up.
Here's how I do it:
In your html file put <SCRIPT type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.js"></SCRIPT>
Then you can call this function that will call (in my case) queryDB.php script.
function queryDB(db,query,doAfter){
$.ajax({
type: 'POST',
data: { host: "localhost",
port: "5432",
db: db,
usr: "guest",
pass: "guest",
statemnt: query
},
url: 'scripts/php/queryDB.php',
dataType: 'json',
async: false,
success: function(result){
// call the function that handles the response/results
doAfterQuery_maps(result,doAfter);
},
error: function(){
window.alert("Wrong query 'queryDB.php': " + query);
}
});
};
Send post to test.php in the same hierarchy and accept the result in html variable
$.ajax(
{
type: "POST",
url: "test.php",
data: {'test': test, 'name': 0, 'asdf': 'asdf'},
success: function(html)
{
alert(html);
}
});
In PHP of the recipient, specify it as follows
<?php
echo "come here";
echo $_POST['test'];
?>
Directory structure
$ tree
.
├── a.php
└── test.php
reference
https://off.tokyo/blog/ajax%E3%81%A7post%E3%82%92%E5%8F%97%E3%81%91%E5%8F%96%E3%82%8B%E6%96%B9%E6%B3%95/
Perhaps it's best for you to use a library like jquery and then you can do something like : $('form').submit(function(){$.post('detinatnion', $('form').serialize());});
but to answer your question since you have a reason for using pure js then:
<form method="post" action="pathToFileForJsFallback.">
First name: <input type="text" id="fname" name="fname" /> <br />
last name: <input type="text" id="lname" name="lname" /> <br />
<input type="submit" value="Submit Form" />
<div id="status"></div>
</form>
JS:
function postStuff(){
var activexmodes=["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"] //activeX versions to check for in IE
if (window.ActiveXObject){ //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken)
for (var i=0; i<activexmodes.length; i++){
try{
mypostrequest = new ActiveXObject(activexmodes[i]);
}
catch(e){
//suppress error
}
}
}
else if (window.XMLHttpRequest) // if Mozilla, Safari etc
mypostrequest = new XMLHttpRequest();
else
return false;
mypostrequest.onreadystatechange=function(){
if (mypostrequest.readyState==4){
if (mypostrequest.status==200 || window.location.href.indexOf("http")==-1){
document.getElementById("result").innerHTML=mypostrequest.responseText;
}
else{
alert("An error has occured making the request");
}
}
}
var fname=encodeURIComponent(document.getElementById("fname").value);
var lname=encodeURIComponent(document.getElementById("lname").value);
var parameters="fname="+fname+"&lname="+lname;
mypostrequest.open("POST", "destination.php", true);
mypostrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
mypostrequest.send(parameters);
}
Again my recommendation to you is to learn js with a library like jquery, because by the time you learn how to do these stuff, these libraries, hardware and everything will be so fast that javascript code like this will become useless for practical every day use.
u need to return false at the end of the function.
function postStuff(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "processForm.php";
var fn = document.getElementById("fname").value;
var ln = document.getElementById("lname").value;
var vars = "firstname="+fn+"&lastname="+ln;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("status").innerHTML = "processing...";
return false;
}

Categories

Resources