Javascript not properly calling API - javascript

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

Related

After my input, my datas are receive as null

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')

sending text messages through twilio

i have an application that allows the user to send a text message by entering a phone number into the input field. but the text message is set to just say "hello". how can i allow the user to enter what they want the text message to say. heres the code
JS
app.get("/:data", function(req, resp){
var accountSid = '*******************'
var authToken = '*********************'
const client = require('twilio')(accountSid, authToken);
client.messages.create({
to: req.params.data,
from: '**********',
body: "Hello"
}, function(err, message) {
if(err) {
console.log(err);
} else {
console.log(message.sid);
}
});
HTML
<input type="text" placeholder="Enter your number" id="inputNum" />
<button id="submitNum">Enter</button>
<script>
submitNum.addEventListener("click", function(){
var inputNum = document.getElementById("inputNum");
var submitNum = document.getElementById("submitNum");
var phoneNumber = inputNum.value;
fetch(" https://*******************.com/"
+ phoneNumber).then((resp)=>{
console.log(resp);
});
});
Twilio developer evangelist here.
To allow your user to enter the message too, you need to add an extra field to your HTML form and then add that field to the API request too. I would also suggest not adding the phone number to the path of the URL, but to query parameters instead. So, taking your HTML first, I'd change it to this:
<input type="text" placeholder="Enter your number" id="inputNum" />
<textarea name="inputMessage" id="inputMessage"></textarea>
<button id="submitNum">Enter</button>
<script>
var inputNum = document.getElementById("inputNum");
var inputMessage = document.getElementById("inputMessage");
var submitNum = document.getElementById("submitNum");
submitNum.addEventListener("click", function(){
var phoneNumber = inputNum.value;
var message = inputMessage.value;
var query = "phoneNumnber=" + encodeURIComponent(phoneNumber);
query += "&message=" + encodeURIComponent(message);
fetch(" https://*******************.com/sendMessage?" + query).then((resp)=>{
console.log(resp);
});
});
</script>
Then, you'll need to update your server to use the message variable and the sendMessage endpoint. I also suggest you send a response back, so that your front end isn't left hanging. Like this:
app.get("/sendMessage", function(req, resp){
var accountSid = '*******************'
var authToken = '*********************'
const client = require('twilio')(accountSid, authToken);
client.messages.create({
to: req.params.data,
from: '**********',
body: req.params.message
}, function(err, message) {
if(err) {
console.log(err);
resp.setStatus(200).send();
} else {
console.log(message.sid);
resp.setStatus(500).send();
}
});
});
Let me know if that helps at all.

Using <Form>, jQuery, Sequelize and SQL to Login and route

My goal is to use the values of the IDs #username-l and #pwd-l in a html form when the user clicks the button submit, have it compare those values to values in a SQL database and if the values equal exactly the values in the database then route the user to a specified route (for now just /user is fine for testing). Currently it routes to /? with no errors which is not specified anywhere. The console shows the query is returning username = null and password = null. I have seeds in the DB called username = test password = test for testing. Any help is appreciated!
HTML:
<form id="login-form">
<div class="form-group">
<label for="username-l">Username:</label>
<input type="username" class="form-control" id="username-l" placeholder="Enter username">
</div>
<div class="form-group">
<label for="pwd-l">Password:</label>
<input type="password" class="form-control" id="pwd-l" placeholder="Enter password">
</div>
<button id="login-button" type="submit" class="btn btn-default">Login</button>
</form>
SEQUELIZE:
app.get("/api/users", function(req, res) {
db.User.findAll({
where:
{
username: req.body.username,
password: req.body.password
}
}).then(function(dbUser) {
// res.json(dbUser);
if (req.body.username === dbUser.username && req.body.password === dbUser.password) {
res.redirect("/users");
} else {
console.log("error");
}
});
});
LOGIN.JS:
$("#login-button").on('click', function() {
var username = $("#username-l").val().trim();
var password = $("#pwd-l").val().trim();
$.get("/api/users", function(data){
console.log(data);
if (username === data.username && username === data.password) {
reRoute();
} else {
console.log("that does not exist");
}
});
});
function getUser(userData) {
$.get("/api/users", userData).then(reRoute());
}
function reRoute() {
window.location.href = "/users";
}
First of all, you're doing a GET request, which, as much as I know HTTP, dosn't have body.
Second, I'm no expert in jQuery, nor I've ever used it, but a quick Google search showed that second parameter is passed as a query string, which is how GET is supposed to work. If you have any data to send, you send it via query string, not through request body.
Therefor, the problem you have is with the server side code, where you read username and password from body instead from query string. So in order for this to work, you need to extract username and password from query like this (I'm guessing you're using Express):
app.get("/api/users", function(req, res) {
const username = req.query.username;
const password = req.query.password;
// do the rest of the stuff with Sequelize and bussiness logic here
});
On the sidenote, you're full router callback has some bad things, like redundant checking if username and password match from the one retrieved from DB. You've already asked Sequelize to retrieve a row from the DB where username and password are the ones you recived from the frontend, and because of that, you don't need to check if instance's username and password matches the one you have. The thing you do need to check if the instance is null, because that means that there is no user with that username and password in your DB. So the "fixed" code should look something like this:
app.get("/api/users", function(req, res) {
const username = req.query.username;
const password = req.query.password;
db.User.findAll({
where: {
username,
password
}
}).then(function(dbUser) {
// res.json(dbUser);
if (dbUser != null) {
res.redirect("/users");
} else {
// you'd maybe like to set response status to 404
// also some user friendly error message could be good as response body
console.log("Error: user not found");
}
});
});
I hope you get the idea of the flow and where was your mistake.

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

Why is my newsletter form not working on Amazon CloudFront?

I am using HTML and using amazon EC2 (Linux free tier). I would like to use CloudFront, but my newsletter won't work. I am not an AWS expert, and I don't have a clue as to why it won't work on CloudFront.
My newsletter form looks like this:
<form id="subscribe" class="form" action="<?=$_SERVER['PHP_SELF']; ?>" method="post">
<div class="form-group form-inline">
<input size="15" type="text" class="form-control required" id="NewsletterName" name="NewsletterName" placeholder="Your name" />
<input size="25" type="email" class="form-control required" id="NewsletterEmail" name="NewsletterEmail" placeholder="your#email.com" />
<input type="submit" class="btn btn-default" value="SUBSCRIBE" />
<span id="response">
<? require_once('assets/mailchimp/inc/store-address.php'); if($_GET['submit']){ echo storeAddress(); } ?>
</span>
</div>
</form>
and my js file looks like this:
jQuery(document).ready(function() {
jQuery('#subscribe').submit(function() {
// update user interface
jQuery('#response').html('<span class="notice_message">Adding email address...</span>');
var name = jQuery('#NewsletterName').val().split(' ');
var fname = name[0];
var lname = name[1];
if ( fname == '' ) { fname=""; }
if ( lname == '' || lname === undefined) { lname=""; }
// Prepare query string and send AJAX request
jQuery.ajax({
url: 'assets/mailchimp/inc/store-address.php',
data: 'ajax=true&email=' + escape(jQuery('#NewsletterEmail').val()),
success: function(msg) {
if (msg.indexOf("Success") !=-1) {
jQuery('#response').html('<span class="success_message">Success! You are now
subscribed to our newsletter!</span>');
} else {
jQuery('#response').html('<span class="error_message">' + msg + '</span>');
}
}
});
return false;
});
});
and my php file looks like this:
<?php
function storeAddress(){
require_once('MCAPI.class.php'); // same directory as store-address.php
// grab an API Key from http://admin.mailchimp.com/account/api/
$api = new MCAPI('mymailchimpapi');
$merge_vars = Array(
'EMAIL' => $_GET['email'],
'FNAME' => $_GET['fname'],
'LNAME' => $_GET['lname']
);
// grab your List's Unique Id by going to http://admin.mailchimp.com/lists/
// Click the "settings" link for the list - the Unique Id is at the bottom of that page.
$list_id = "myuniqueid";
if($api->listSubscribe($list_id, $_GET['email'], $merge_vars , $_GET['emailtype']) === true) {
// It worked!
return 'Success! Check your inbox or spam folder for a message containing a
confirmation link.';
}else{
// An error ocurred, return error message
return '<b>Error:</b> ' . $api->errorMessage;
}
}
// If being called via ajax, autorun the function
if($_GET['ajax']){ echo storeAddress(); }
?>
The form works when I access it without using CloudFront, but I am worried of the server bandwidth that's why I want to use CloudFront. What happens is that when you click the submit button, the "adding email address" message will just appear for 1 second, and the email address entered is ignored.
Please make sure your CloudFront distribution is actually configured to handle POST/PUT requests. Take a look here for details: http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-values-specify.html#DownloadDistValuesAllowedHTTPMethods

Categories

Resources