I am trying to save a profile using Ajax to sent the data. I can save when I dont have image, but the problem is that the profile has an image and I would like to send it using the same Ajax function I am using to send the other information. If I don't do this, I have to create a different another Ajax function with 'PUT' request just to modify the document and save the image in it.
Is there some way to send image as Json along with the the other info such as name and email?
This is my HTML:
<input class="teamName" type="text" id="teamName" name="teamName" size="25" maxlength="60" value="Team Name">
<input class="companyName" type="text" id="companyName" name="companyName" size="25" maxlength= "60" value="Company Name">
<input class="teamDescription" type="text" id="teamDescription" name="teamDescription" size="25" maxlength= "60" value="Team Description">
<input class= "email" type="text" id="email" name="email" size="25" maxlength= "60" value="emails">
<input class="charityID" type="text" id="charityID" name="charityID" size ="25" maxlength="60">
<input class="upload-area" id="upload-area" type="file" size="150">
This is my function and I call using the 'greenButton' onclick method:
function createTeam(){
var _teamName= document.getElementById("teamName").value;
var _companyName =document.getElementById("companyName").value; //maybe not, tae it off.
var _charityID = document.getElementById("charityID").value;
var _teamDescription = document.getElementById("teamDescription").value;
var _profileImage = document.getElementById("upload-area").value; //PATH of the Image
if((_teamName.trim() === "") || (_companyName.trim() === "") || (_charityID.trim() === ""))
{
alert("You did not fill the team Name or companyName or Charity, Please enter with a name");
}else{
var sessionID = $.cookie("sessionID")
$.ajax({
type: "POST",
url: "http://xxx.xxx.x.xx:8085/team/?sessionID="+sessionID,
dataType:'json',
data:{
teamName: _teamName,
companyName:_companyName,
teamDescription:_teamDescription,
charityID:_charityID,
profileImage:_profileImage **//CAN I DO THIS, SEND AS JSON?**
},
success: function(msg) {
$.cookie("teamID",msg.teamID)
$.cookie("sessionID",sessionID)
alert("team supposedly saved")
}
});
}
}
And this is how I receive data in my NodeJs to save on my DataBase:
router.post('/', function (req, res){
//TEAM INFO
var sessionID = req.query.sessionID // to get variable form URL is "req.query"
var team = req.body;
var teamName = team.teamName;
var teamDescription = team.teamDescription;
var charityID = team.charityID;
var teamLink = team.teamLink;
var image = team.profileImage;
sessionOBJ.isAuthorized(sessionID, function(sessionID){
log.d("Checking session to save team", sessionID);
var adminID = sessionID.userID;
var newTeam = new teamModel({
teamName: teamName,
teamDescription: teamDescription,
teamAdminID: adminID,
teamLink: teamLink,
charityID: charityID,
image: {
data:fs.readFileSync(image),
contentType:image.type
}
});
newTeam.save(function(err, team){
if(err) return console.error(err);
res.send({"status" : "Created", "teamID" : team._id, "teamAdminID":team.teamAdminID });
log.d("Created Team ID", team._id)
log.d("XXXXXXX XXXXXX XXXXXXX Team Saved inside save method",team);
});//end save new team
});//end is Authorized
});
The code above is not working.
How can I send the image file using javascript and Ajax? Can I do this using the same Ajax request?
Thanks in advance.
Related
I am creating a form filling website it should return alert message if contact,email is not up to our standard.
But I am getting this error Uncaught ReferenceError: submitToAPI is not defined at HTMLButtonElement.onclick
var URL is I am passing these data to AWS API gateway and trigger a lambda function.
form html code
<h4>Name:</h4>
<input type="text" style="height:35px;" id="name-input" placeholder="Enter name here…" class="form-control" style="width:100%;" /><br/>
<h4>Company Name:</h4>
<input type="text" style="height:35px;" id="cname-input" placeholder="Enter name here…" class="form-control" style="width:100%;" /><br/>
<h4>Contact Number:</h4>
<input type="phone" style="height:35px;" id="phone-input" placeholder="Enter phone number" class="form-control" style="width:100%;"/><br/>
<h4>Email:</h4>
<input type="email" style="height:35px;" id="email-input" placeholder="Enter email here…" class="form-control" style="width:100%;"/><br/>4>
<div class="g-recaptcha" data-sitekey="6Lc7cVMUAAAAAM1yxf64wrmO8gvi8A1oQ_ead1ys" class="form-control" style="width:100%;"></div>
<button type="button" onClick="submitToAPI(event)" class="btn btn-lg" style="margin-top:20px;">Submit</button>
javascript
<script language="JavaScript" type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" >
function submitToAPI(e) {
e.preventDefault(e);
var URL = "https://abc1234.execute-api.us-east-1.amazonaws.com/01/contact";
var e_name = /[A-Za-z]{1}[A-Za-z]/;
if (!e_name.test($("#name-input").val())) {
alert ("Name can not less than 2 char");
return;
}
var e_cname = /[A-Za-z]{1}[A-Za-z]/;
if (!e_cname.test($("#cname-input").val())) {
alert ("Name can not less than 2 char");
return;
}
var e_phone = /[0-9]{10}/;
if (!e_phone.test($("#phone-input").val())) {
alert ("Please enter valid mobile number");
return;
}
if ($("#email-input").val()=="") {
alert ("Please enter your email id");
return;
}
var e_email = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,6})?$/;
if (!e_email.test($("#email-input").val())) {
alert ("Please enter valid email address");
return;
}
var e_name = $("#name-input").val();
var e_cname = $("#cname-input").val();
var e_phone = $("#phone-input").val();
var e_email = $("#email-input").val();
var data = {
name : e_name,
cname : e_cname,
phone : e_phone,
email : e_email,
};
$.ajax({
type: "POST",
url : "https://abc1234.execute-api.us-east-1.amazonaws.com/01/contact",
dataType: "json",
crossDomain: "true",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(data),
success: function () {
// clear form and show a success message
alert("Successfull");
document.getElementById("contact-form").reset();
location.reload();
},
error: function () {
// show an error message
alert("There is some issue with our servers please contact our landline for enquiry");
}});
}
</script>
You are using the script tag with a src attribute, your browser is only executing the remote JS (Jquery)
Create a new script tag without the src and add your code in this new block!
Correct way is to first load jQuery as your script is dependent on it.
<script language="JavaScript" type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" >
</script>
After that you can include your script
<script>
$(document).ready(function () {
function submitToAPI(e) {
// your code
}
});
</script>
Make sure jQuery is properly loaded into your page. Check network tab in dev console, make sure there is no "404".
$(document).ready(function () {
// This code is being loaded after jQuery has been initialized
});
I am trying to set up an email contact page on my heroku website using sendgrid. I have tried the code with the helper mailer and the one without; however, both do are not able to send an email to my email address. I added my sendgrid API key as a variable in my heroku app settings and also imported the username and password.
My email process starts when the user click on a button. I have an action to a post route within the form element, and I use body parser to retrieve the input values from the user (message, their email address, and their message). Within my post route, I call a function in my email.js file that wraps the code from sendgrid.
//My html using handlebars.
<div class = "mainDiv" id = "sectionAbout">
<h1 class="mainDivH1" id = "AboutMe">{{ ContactLi }}</h1>
<form action="/email" method="POST">
<label for="fullName">{{ formName }}</label> <br><br>
<input type="text" name="fullName">
<br>
<br>
<label for="subject">{{ formSubject }}</label> <br><br>
<input type="text" name="subject">
<br>
<br>
<label for="email">{{ formEmail }}</label> <br><br>
<input type="text" name="email">
<br>
<br>
<label for="message">{{ formMessage }}</label> <br><br>
<textarea rows="15" cols="80" type="text" name="message id="textbox"></textarea>
<br>
<br>
<button id="but" type="submit">Submit</button>
</form>
</div>
//The code for the POST route
var email = require('../mail/email');
router.post('/email', function(req, res){
var name = req.body.fullName;
var emSubject = req.body.subject;
var senderMail = req.body.email;
var message = name + " " + req.body.message;
var myEmail = 'examplee#yahoo.com';
email.send(emSubject, senderMail, message, function(){
res.redirect('/contact');
});
});
//email.js
var helper = require('sendgrid').mail
var sg = require('sendgrid')(process.env.SENDGRID_API_KEY);
var email = {
send: function(emSubject, senderMail, message, callback){
var from_email = new helper.Email(senderMail);
var to_email = new helper.Email('helper#yahoo.com');
var subject = emSubject;
var content = new helper.Content("text/plain", message);
var mail = new helper.Mail(from_email, subject, to_email, content);
var request = sg.emptyRequest({
method: 'POST',
path: '/v3/mail/send',
body: mail.toJSON()
});
console.dir("request");
console.dir(JSON.stringify(request, null, 4));
sg.API(request, function(error, response) {
if(error){
console.log(error);
}
console.log(response.statusCode)
console.log(response.body)
console.log(response.headers)
callback(error);
});
}
}
module.exports = email;
You mentioned that you added your Sendgrid API key as an env var, and imported your username and password. You should not have to do any of that. Just add the Sendgrid add-on to your Heroku account as follows:
heroku addons:create sendgrid:starter
i am trying to get value from text boxes in my views in asp.net using jquery. i have also used bootstrap in my project. Due to it jquery is not getting value. kindly anyone guide me how to get value in this case.
javascript:
function Validate()
{
var username = $("#username").attr('value');
var password = $("#password").attr('value');
var url = "/User/ValidateUser/";
alert(username);
$.ajax({ // function calling
url: url,
data: { userId: username, Password: password },
cache: false,
type: "POST",
success: function (data)
{
if (data == "1")
{
//alert("Valid user Id ");
}
else
{
alert("Invalid user Id ");
}
},
error: function (reponse)
{
alert("Invalid user ID");
}
});
}
html:
<input class="textbox" id="username" type="text" placeholder="Username">
<input class="textbox" id="password" type="password" placeholder="Password">
attr(key) gets what is in the markup. Not what the current value is. You should use val() when trying to get the value of an input. As demonstrated below.
$('button').on('click', function() {
console.log(
$('#test').attr('value'),
$('#test').val()
);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="test" value="Yo yo man" />
<button>Log Value</button>
Use .val() to get value from input , textarea elements.
Please refer :
http://api.jquery.com/val/
var username = $("#username").val();
var password = $("#password").val();
I'm new to S.O and javascript. I am working on a final year project for a e-commerce website and have ran into a dead end on saving data from a form into local storage. My code is below, i really don't see where i have gone wrong. all help is appreciated.
window.onload = function() {
// Check for LocalStorage support.
if (localStorage) {
// Populate the form fields
populateForm();
// Get the form
var form = document.getElementById("franchiseForm");
// Event listener for when the bookings form is submitted.
form.addEventListener("submit", function(e) {
saveData(form);
});
}
}
// Save the form data in LocalStorage.
function saveData() {
//fetch sava(data)
var fran_name = document.getElemenyById("fran_name");
var name = document.getElemenyById("name");
var address1 = document.getElemenyById("address1");
var address2 = document.getElemenyById("address2");
var city = document.getElemenyById("city");
var pcode = document.getElemenyById("pcode");
var phone = document.getElemenyById("phone");
//store the values
localStorage.setItem("fran_name", fran_name.value);
localStorage.setItem("name", name.value);
localStorage.setItem("address1", address1.value);
localStorage.setItem("address2", address2.value);
localStorage.setItem("city", city.value);
localStorage.setItem("pcode", pcode.value);
localStorage.setItem("phone", phone.value);
}
// Attempt to populate the form using data stored in LocalStorage.
function populateForm() {
// Fetch the input elements.
var fran_name = document.getElemenyById("fran_name");
var name = document.getElemenyById("name");
var address1 = document.getElemenyById("address1");
var address2 = document.getElemenyById("address2");
var city = document.getElemenyById("city");
var pcode = document.getElemenyById("pcode");
var phone = document.getElemenyById("phone");
//retrieve saved data and update the values of the form.
if (localStorage.getItem("fran_name") != null) {
name.value = localStorage.getItem("fran_name");
}
if (localStorage.getItem("name") != null) {
phone.value = localStorage.getItem("name");
}
if (localStorage.getItem("address1") != null) {
email.value = localStorage.getItem("address1");
}
if (localStorage.getItem("address2") != null) {
email.value = localStorage.getItem("address12");
}
if (localStorage.getItem("city") != null) {
email.value = localStorage.getItem("city");
}
if (localStorage.getItem("pcode") != null) {
email.value = localStorage.getItem("pcode");
}
if (localStorage.getItem("phone") != null) {
email.value = localStorage.getItem("phone");
}
}
window.onload = function(){
if (localstorage){
//populate the form fields
populateform(form);
}
}
<div id="section">
<form id="franchiseForm" action ="Order_confirmation.php" method="POST">
<div class="field">
<label for="fran_name">Franchise Name</label>
<input type="text" name="franchise_name" id="fran_name" placeholder="e.g One Delivery Leeds" pattern="[a-zA-Z]"
autofocus required tabindex="1">
<br>
<label for="name">Name</label>
<input type="text" name="franc_name" id="name" placeholder="Joe Blogs" required tabindex="2">
<br>
<label for="address"> Address</label>
<input type="text" name="franc_address" id="address1" placeholder="Address Line 1" tanindex="3">
<input type="text" id="address2" placeholder="Address Line 2" tabindex="4">
<input type="text" id="city" placeholder="Town/City" tabindex="5">
<input type="text" id="pcode" placeholder="Postcode" tabindex="6">
<br>
<label for="phone" > Phone Number</label>
<input type="tel" name="franc_phone" id="phone" placeholder="Customer service number" min="10" maxlength="11" pattern="[0-9]{3}[-][0-9]{4}[-][0-9]{4}"
required title="Please provide your customer service number in the following format: 000-0000-0000" tabindex="7">
</div>
<div class="field">
<input type="submit" id="submit" value="submit">
</div>
</form>
The main thing is, check your console for this error:
Uncaught ReferenceError: localstorage is not defined.
Change your code. It is localStorage and not localstorage. That's a capital S.
And a big mistake here. It is getElementById and not getElemenyById:
var fran_name = document.getElemenyById("fran_name");
var name = document.getElemenyById("name");
var address1 = document.getElemenyById("address1");
var address2 = document.getElemenyById("address2");
var city = document.getElemenyById("city");
var pcode = document.getElemenyById("pcode");
var phone = document.getElemenyById("phone");
You have too many mistakes! Elemeny != Element.
Looks like this is stopping your code from executing:
if (localStorage.getItem("address1") != null) {
email.value = localStorage.getItem("address1");
}
if (localStorage.getItem("address2") != null) {
email.value = localStorage.getItem("address12");
}
if (localStorage.getItem("city") != null) {
email.value = localStorage.getItem("city");
}
if (localStorage.getItem("pcode") != null) {
email.value = localStorage.getItem("pcode");
}
if (localStorage.getItem("phone") != null) {
email.value = localStorage.getItem("phone");
}
You don't have a variable named email. And moreover, you are trying to set the value of an undefined element variable email, which doesn't have a property named value, that prevents all your scripts from executing.
First of all, not in your code you use:
document.getElemenyById(...);
localstorage.setItem()
instead of (note the Elemeny vs. Element, s vs. S):
document.getElementById(...);
localStorage.setItem();
As for a full solution:
You can use various local storage to store this data in the browser.
You can do something like this when the page is about to reload:
window.onbeforeunload = function() {
var fran_name = document.getElementById("fran_name");
var name = document.getElementById("name");
// ...
localStorage.setItem("fran_name", fran_name.value);
localStorage.setItem("name", name.value);
// ...
}
localstorage works synchronously so this will work here.
At page load you can check:
window.onload = function() {
var name = localStorage.getItem(name);
if (name !== null) document.getElemenyById("name").value = name;
// ...
}
getItem will return null` if the data does not exist.
Use sessionStorage instead of localStorage if you want to store temporarily - until the browser is closed.
Here's a simplified version of your form, with complete working code. save it as a .html file:
<html>
<head>
<script type="text/javascript">
// For saving data:
window.onbeforeunload = function() {
var name = document.getElementById("name");
// ...
localStorage.setItem("name", name.value);
// ...
}
// For loading data:
window.onload = function() {
var name = localStorage.getItem(name);
if (name !== null) document.getElemenyById("name").value = name;
// ...
}
</script>
<title></title>
</head>
<body>
<div id="section">
<form id="franchiseForm" action="Order_confirmation.php" method="POST">
<div class="field">
<label for="name">Name</label>
<input type="text" name="franc_name" id="name" placeholder="Joe Blogs" required tabindex="2">
<br>
</div>
</form>
</div>
</body>
</html>
If you are able to use JQuery and JQuery Cookie, you can save the data in a cookie:
var frn = $(#fran_name).val();
$.cookie("fran_name", frn);
Then on pageload you get the cookie data and then insert it into the field:
$(document).ready(function(){
var cookie = $.cookie("fran_name");
$('#fran_name').val(cookie);
});
I am working with Parse for Javascript, and below is my dilema:
During the signup process, along with the username, and password, the first and last name of the user would have to recorded into parse. As of now, only the username and password is stored.
Below is the javascript signup function code:
SignUp: function(e) {
var self = this;
var username = this.$("#signup-username").val();
var password = this.$("#signup-password").val();
var first_name = this.$("#fname").val();
var last_name = this.$("#lname").val();
Parse.User.signUp(username, password, { ACL: new Parse.ACL() }, {
success: function(user) {
user.set("first_name", first_name);
user.set("last_name", last_name);
new ManageTodosView();
self.undelegateEvents();
delete self;
},
Below is the html form code (ask user to enter their information):
<form class="signup-form">
<h2>Sign Up</h2>
<div class="error" style="display:none"></div>
<input type="text" id="fname" placeholder="Please enter your First Name" />
<input type="text" id="lname" placeholder="Please enter your Last Name" />
<input type="email" id="signup-username" placeholder="Please enter your email" />
<input type="password" id="signup-password" placeholder="Create a Password" />
<button>Sign Up</button>
</form>
Any help would be greatly appreciated.
User.set won't save the changes you will need to call save once you set the first name and last name. Also you don't need to do this after calling signing up. Try the code below it should work.
SignUp: function(e) {
var self = this;
var username = this.$("#signup-username").val();
var password = this.$("#signup-password").val();
var first_name = this.$("#fname").val();
var last_name = this.$("#lname").val();
var user = new Parse.User();
user.set("username", username);
user.set("password", password);
user.set("first_name", first_name);
user.set("last_name", last_name);
user.signUp(null, {
success: function(user) {
new ManageTodosView();
self.undelegateEvents();
delete self;
}
}