$.ajax() gives [object HTMLInputElement] instead of value - javascript

I have an $.ajax() request working properly and it's calling 3 ids. The only id with no issues is the name id. The clientId logs well on the console, but prints undefined on the table. The url is printing [object HTMLInputElement] on the table and on the console, logs like this<input class="form-control no-border" type="text" id="redirectUrl" name="url" placeholder="http://stuffpage/redirect/?id=1" required="">.I want to print the url that i am introducing on the input.
Can you tell me what is the problem?
$('#saveButton').on('click', function() {
var url = "http://stuffpage.com/redirect/redirect";
var name = $('#name').val();
console.log("name", name);
var clientId = $('#clientId').val();
console.log("clicentId", clientId);
var redirecUrl = $('#redirectUrl').val();
console.log("redirectUrl", redirectUrl);
var formData = new FormData();
formData.append('name', name);
formData.append('client_id', clientId);
formData.append('url', redirectUrl);
console.log('test')
$.ajax({
url: url + "/saveRedirect",
type: "POST",
dataType: "json",
data: formData,
contentType: false,
cache: false,
processData: false,
success: function(obj) {
var name, clientId, redirecUrl;
var rows = '';
for (i = 0; i < obj.length; i++) {
rows += "<tr class='lightgrey'><th>" + obj[i].name + "</th><td>" + obj[i].clientId + "</td><td>" + obj[i].url + "</td><td><img id='editButton' class='col-md-2 edit nopad' src='http://stuffpage.com/redirect/public/img/edit.svg'><img class='col-md-2 link nopad float-right' src='http://stuffpage.com/redirect/public/img/copy.svg'></td></td></tr>";
$("#table").append(rows);
console.log('sucess!');
}
},
error: function() {
console.log('error');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div class="col-md-12 marg-t-30 nopad">
<!--REGISTER NAME CLIENT ID URL-->
<div class="col-md-1 nopad">
<div class="rtitle">
<div class="roboto-condensed">name</div>
</div>
</div>
<div class="col-md-3 nopad" style="margin-right: 20px;">
<input class="form-control no-border" id="name" type="text" name="nameClient" placeholder="Insert name..." required="">
</div>
<div class="col-md-1 nopad">
<div class="rtitle">
<div class="roboto-condensed">client id</div>
</div>
</div>
<div class="col-md-3 nopad">
<select class="form-control no-border selectpicker" name='clientId' id='clientId' data-show-subtext="true" required="">
<?php echo $client_data;?>
</select>
</div>
<div class="col-md-3 nopad">
<button id="saveButton" class="save float-right">SAVE</button>
</div>
<div class="col-md-12 nopad marg-t-20">
<div class="col-md-1 nopad">
<div class="rtitle">
<div class="roboto-condensed">url</div>
</div>
</div>
<div class="col-md-11 nopad">
<input class="form-control no-border" type="text" id="redirectUrl" name="url" placeholder="http://stuffpage/redirect/?id=1" required="" value="">
</div>
</div>
</div>
<!--col-md-12-->

Looks like you have a typo:
var redirecUrl = $('#redirectUrl').val();
should be
var redirectUrl = $('#redirectUrl').val();

You can replace
var clientId = $('#clientId').val();
To
var clientId = $('#clientId option:selected').val();
And
var redirectUrl = $('#redirectUrl').val();

Related

How to store imported files through input in a list temporary and then pass the list to post request using Javascript or jQuery?

I want to use this list because before submitting I might remove a few and add more files to the list. When I use the input to get the files it has only the last imported files, not the previous ones but I want to preserve the previous ones as well cause I want to add or subtract images or pdf files to list before submission.
HTML Code:
//<form method="POST" id="medical_record_form" enctype="multipart/form-data" '>
<div class="card">
<div class="card-body">
<div class="row form-row">
<div class="col-12 col-md-12">
<div class="form-group">
<label>Title</label>
<input type="text" name="title" id="title" class="form-control">
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label>Medical Documents</label>
<div class="upload-img">
<div class="change-photo-btn">
<span><i class="fa fa-upload"></i> Upload File</span>
<input id="medical_documents" name="medical_documents"
type="file" multiple accept="image/*,.pdf"
onchange="readURL(this);" class="upload">
</div>
<small class="form-text text-muted">All Image Types Are Allowed, Plus
PDF Files</small>
</div>
</div>
<div class="upload-wrap" id="documets_wrapper">
<!-- the images preview goes here which is handled by javascript -->
</div>
</div>
</div>
</div>
</div>
<div class="submit-section">
<button type="submit" id="medical_submit_button" class="btn btn-primary submit-btn">Save
Changes</button>
</div>
</form>
Javascript code:
'''
// Fields
const medicalForm = document.getElementById('medical_record_form');
const title = document.getElementById('title');
const medicalDocuments = document.getElementById('medical_documents');
var filesList = [];
function readURL(input) {
if (input.files && input.files[0]) {
for (let i = 0; i < input.files.length; i++) {
filesList.push(event.target.files[i]); // not working
var tempHtml = '<div class="upload-images" id="image_' + i + '">' +
'<img src="' + URL.createObjectURL(event.target.files[i]) + '" alt="Upload Image">' +
'<i class="far fa-trash-alt"></i>' +
'</div>';
$('#documets_wrapper').append(tempHtml);
}
}
}
$("#medical_submit_button").on('click', function () {
medicalForm.addEventListener('submit', (e) => {
e.preventDefault();
const formData = new FormData();
formData.append('csrfmiddlewaretoken', theToken);
formData.append('title', title.value);
formData.append('medical_documents', filesList);
$.ajax({
type: 'POST',
url: addUrl,
contentType: false,
// contentType: 'multipart/form-data', // tried this one also
processData: false,
data: formData,
success: function (response) {
console.log('value of response');
console.log(response);
},
error: function (error) {
console.log('error: ', error);
},
cache: false,
contentType: false,
processData: false,
});
})
})
'''

using data posted by ajax to node js problem

I'm trying to update my template without refreshing the page by ajax .... and I used two arrays for saving data permanently on front side and I send these two arrays with post method and ajax to my node js... I have some other input in my template but I don't want to send them with ajax ... How to parse them beside
ajax post?
my server
const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const multer = require("multer");
const mongoose = require('mongoose');
const path = require("path");
const app = express();
var titlesList = [];
app.use(express.static("public"));
//if we wanna recive data from ajax we have to use this line
// var jsonParser = bodyParser.json();
// parse application/json
app.use(express.json());// add this line
app.use(bodyParser.urlencoded({ extended: false }));
var c = [];
var storage = multer.diskStorage({
destination:function(req,file,cb){
cb(null , "public/upload");
},
filename:function(req,file,cb){
cb(null , file.filename + '-' + Date.now() + path.extname(file.originalname));
}
});
var upload = multer ({
storage:storage
})
mongoose.connect("mongodb://localhost:27017/landingDb" , {useNewUrlParser : true} , { useUnifiedTopology: true } );
const courseSchema = new mongoose.Schema ({
courseTitle : String,
courseSubtitle : String,
coursreAuthor : String,
coursePrice : Number,
courseVideo : Object,
courseSpecs : Array,
courseTitles : Array,
courseValidation : Number,
courseTags : Array
});
const Courses = mongoose.model("Courses" ,courseSchema );
app.set("view engine", "ejs");
app.get("/cp" , function(req , res){
res.render("cp");
});
app.post("/cp" , upload.single("c_upload") , function(req , res){
var c_titles = [];
const c_specs = JSON.stringify(req.body.specs);
const file = req.file;
const c_title = req.body.c_title;
const c_subtitle = req.body.c_subtitle;
const c_creator = req.body.c_creator;
const c_price = req.body.c_price;
console.log(file);
console.log(JSON.stringify(req.body.titles));
console.log(JSON.stringify(req.body));
if(req.body.submitcp == "submitCp"){
console.log(file);
const courses = new Courses({
courseTitle:c_title,
courseSubtitle:c_subtitle,
courseAuthor : c_creator,
coursePrice : c_price,
courseVideo : file,
courseTitles : c_titles,
courseSpecs : c_specs,
courseValidation : 0
});
courses.save();
}
});
app.listen(3000, function () {
console.log("running");
});
my html
<%- include('header'); -%>
<div class="container-fluid">
<div class="row">
<div dir="rtl" class="col-md-6 cp_main_div">
<form action="/cp" enctype="multipart/form-data" class="titlesForm" id="form" method="post">
<div class="col-md-12">
<div class="form-group">
<label for="exampleInputEmail1">عنوان دوره</label>
<input name="c_title" type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="...">
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label for="exampleInputEmail1">توضیحات مختصر دوره</label>
<input name="c_subtitle" type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="...">
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label for="exampleInputEmail1">سازنده دوره</label>
<input name="c_creator" type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="...">
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label for="exampleInputEmail1">قیمت دوره</label>
<input name="c_price" type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="...">
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label for="exampleFormControlFile1">آپلود ویدیو معرفی</label>
<input name="c_upload" type="file" class="form-control-file videoup" id="fileupload">
</div>
</div>
<div class="col-md-12" >
<div class="c_preview_div">
<div class="video_play"></div>
<video class="c-preview-video">
<source src="assets/gm2.mp4" type="video/mp4">
Your browser does not support HTML video.
</video>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label for="exampleInputEmail1">نوع دوره</label>
<select name="c_type" class="form-control form-control-lg">
<option>وبینار</option>
<option>دوره آنلاین</option>
<option>دوره آفلاین</option>
<option>ورکشاپ</option>
<option>دوره فیزیکی</option>
</select>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label for="exampleInputEmail1">عنوان های دوره</label>
<input name="titlesInput" id="titlesInp" type="text" class="form-control cp_input_titles" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="...">
</div>
<button id="title_submit" name="addTitles" value="addtitles" type="clickspecs_submit" class="btn btn-primary mb-2 add_titles">+</button>
<div style="width: 100%; height: 100%;" id="showTitles">
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label for="exampleInputEmail1">مشخصات دوره</label>
<input name="specsInput" id="c_specs" type="text" class="form-control cp_input_titles" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="...">
</div>
<button id="specs_submit" name="addSpecs" value="addspecs" type="click" class="btn btn-primary mb-2 add_titles">+</button>
<div style="width: 100%; height: 100%;" id="showSpecs">
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label for="exampleInputEmail1">تگ ها</label>
<select name="c_type" class="form-control form-control-lg">
<option>وبینار</option>
<option>دوره آنلاین</option>
<option>دوره آفلاین</option>
<option>ورکشاپ</option>
<option>دوره فیزیکی</option>
</select>
</div>
</div>
<div class="col-md-12">
<button type="submit" name="submitcp" value="submitCp" id="submitpostCp" class="btn btn-primary btn-lg btn-block">send</button>
</div>
</div>
</form>
<!-- <iframe id="uploader_iframe" name="uploader_iframe" style="display: none;"></iframe> -->
</div>
</div>
</div>
</body>
<footer>
</footer>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous">
</script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous">
</script>
<script charset="utf-8" src="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/owl.carousel.min.js"></script>
<script type="text/javascript" charset="utf-8" src="script.js"></script>
<script type="text/javascript" charset="utf-8" src="sort.js"></script>
<script type="text/javascript" src="lightslider.js"></script>
</html>
my ajax call
var titlesLis = [];
var specsLis = [];
document.getElementById("form").addEventListener("submit", function (e) {
e.preventDefault();
e.stopPropagation();
//check what btn submit and push to item to array
if (e.submitter.id == "title_submit") {
var titlesInp = $(".cp_input_titles").val();
titlesLis.push(titlesInp);
}
//check what btn submit and push to item to array
if (e.submitter.id == "specs_submit") {
var specsInp = $("#c_specs").val();
specsLis.push(specsInp);
}
//check what btn submit and remove item from array
//check what btn submit and delete the item from view
if (e.submitter.id == "delete_specs") {
if(e.submitter.id >="0"){
specsLis.splice(e.submitter.id , 1);
}
$("#" + 'specs' + e.submitter.value).remove();
showspecItems();
}
//check what btn submit and remove item from array
//check what btn submit and delete the item from view
if (e.submitter.id == "delete_titles") {
if(e.submitter.id >="0"){
titlesLis.splice(e.submitter.id , 1);
}
$("#" + 'titles' + e.submitter.value).remove();
showtitleItems();
}
var data = {};
data.titles = titlesLis;
data.specs = specsLis;
//ajax call
$.ajax({
type: 'post',
url: '/cp',
data: JSON.stringify(data),
contentType: 'application/json',
xhrFields: {
withCredentials: false
},
headers: {
},
success: function (data) {
console.log('Success');
console.log(data);
//check what btn submit and delete the item from view
if (e.submitter.id == "title_submit") {
showtitleItems();
}
if (e.submitter.id == "specs_submit") {
showspecItems();
}
},
error: function () {
console.log('We are sorry but our servers are having an issue right now');
}
})
function showtitleItems() {
$("#showTitles").empty();
for (var i = 0; titlesLis.length > i; i++) {
$("#showTitles").append('<div id="' + 'titles' + i + '" class="TSShow titlesShow"><button name="deleteTitles" value="' + i + '" type="submit" id="delete_titles">-</button><h4>' + titlesLis[i] + '</h4></div>');
}
}
function showspecItems() {
$("#showSpecs").empty();
for (var i = 0; specsLis.length > i; i++) {
$("#showSpecs").append('<div id="' + 'specs' + i + '" class="TSShow specsShow"><button name="deleteSpecs" value="' + i + '" type="submitz" id="delete_specs">-</button><h4>' + specsLis[i] + '</h4></div>');
}
}
})

Javascript function in vapor 3 leaf - Help Need

I have a Javascript function in a leaf page using Vapor 3 the function should trigger a post to an api to save a customers card detials and return a token representing that card. I would normally do this in swift on our vapor server but to be PCI complient we are not allowed to take the customers credit card detials onto our server they must go directly to Sum Up (payment provider) I have no experiance with javascript and after lots of googling this it the fucntion I came up with.
<script>
function savecard() {
var name = document.getElementById("nameonCard").value
var cardNo = document.getElementById("cardNumber").value
var expiry_year = document.getElementById("expiryMonth").value
var expiry_month = document.getElementById("expiryYear").value
var cvv = document.getElementById("cvc").value
var body = `{"type":"card","card":{"name":"${name}","number":"${cardNo}", "expiry_month": "${expiry_month}", "expiry_year": "${expiry_year}","cvv": "${cvv}"}}`
return fetch("https://api.sumup.com/v0.1/customers/" + #(sumCustId) + "/payment-instruments", {
method: "POST"
headers: {
"Authorization": "Basic " + #(auth),
"Content-Type": "application/json"
},
data: body,
})
.then(function(response){
document.getElementById("response").value = response.text()
return response.text();
})
.then(function(data){
console.log(data)//text version
var data_obj = JSON.parse(data);
document.getElementById("data_obj").value = data_obj
return data_obj
})
}
</script>
I don't appear to be getting anything back but I'm not sure where I am going wrong, any help is much appreciated.
Here is the entire leaf page.
<!doctype html>
<html lang="en">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<title>Pay for Membership</title>
<body>
<div class="card bg-dark text-white h-100">
<img class="card-img bg-dark img-fluid" src="https://images.unsplash.com/photo-1575151772039-542722abbf63?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format" alt="Card image">
<div class="card-img-overlay">
<div class="card-deck">
<div class="card bg-transparent border-warning align-self-start ">
<div class="card-header">
<h4 class="card-title text-center">Order Summary</h4>
</div>
<div class="card-body">
<ul>
#for(sum in orderSum){
#if(isLast == false){
<li class="list-group-item bg-transparent d-flex justify-content-between align-items-centert">#noam(sum)
<span class="badge badge-info badge-pill text-right align-self-center">#am(sum)</span>
</li>
}
}
</ul>
</div>
<div class="card-footer text-center">
#for(sum in orderSum){
#if(isLast){
<h5>#(sum)</h5>
}
}
</div>
</div>
<div class="card bg-dark border-warning">
<div class="card-header">
<h4 class="card-title">Payment Details</h4>
</div>
<div class="card-body">
<form method="post" action="/completedsumupmember" id="paymentForm">
<div class="row form-group" hidden>
<input type="number" class="form-control" id="amount" name="amount" value =#(amount) hidden>
<input type="text" class="form-control" id="currency" name="currency" value =#(currency) hidden>
<input type="text" class="form-control" id="orderId" name="orderId" value =#(orderId) hidden>
<input type="text" class="form-control" id="desc" name="desc" value =#(desc) hidden>
<input type="text" class="form-control" id="type" name="type" value =#(type) hidden>
<input type="text" class="form-control" id="orgId" name="orgId" value =#(orgId) hidden>
<input type="text" class="form-control" id="payToEmail" name="payToEmail" value =#(payToEmail) hidden>
<input type="text" class="form-control" id="auth" name="auth" value =#(auth) hidden>
<input type="hidden" class="form-control" id="response" name="response" value ="" hidden>
<input type="hidden" class="form-control" id="data_obj" name="data_obj" value ="" hidden>
<input type="text" class="form-control" id="customerId" name="customerId" value =#(sumCustId) hidden>
</div>
<div class="row form-group">
<div class = "col-md">
<label for="nameonCard">Name on the Card</label>
<input type="text" class="form-control" id="nameonCard" name="nameonCard" placeholder="John Smith" required>
</div>
</div>
<div class ="row form-group">
<div class ="col-lg">
<label for="cardNumber">Card Number</label>
<input type="number" class="form-control" id="cardNumber" name="cardNumber" placeholder="1111 2222 3333 4444" required>
</div>
</div>
<div class = "row form-group">
<div class = "col-md">
<label for="expiryMonth">Expriy Month</label>
<input type="text" class="form-control" id="expiryMonth" name="expiryMonth" placeholder="mm" required>
</div>
<div class = "col-md">
<label for="expiry">Expriy Year</label>
<input type="text" class="form-control" id="expiryYear" name="expiryYear" placeholder="yy" required>
</div>
<div class = "col-md">
<label for="cvc">CVV</label>
<input type="text" class="form-control" id="cvc" name="cvc" placeholder="000" required>
</div>
</div>
<div class="card-footer text-center">
<button class="btn btn-warning btn-block" type="submit" onclick="savecard()">Pay Now</button>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script>
function savecard() {
console.log('do something ')
var name = document.getElementById("nameonCard").value
var cardNo = document.getElementById("cardNumber").value
var expiry_year = document.getElementById("expiryMonth").value
var expiry_month = document.getElementById("expiryYear").value
var cvv = document.getElementById("cvc").value
var body = `{"type":"card","card":{"name":"${name}","number":"${cardNo}", "expiry_month": "${expiry_month}", "expiry_year": "${expiry_year}","cvv": "${cvv}"}}`
return fetch("https://api.sumup.com/v0.1/customers/" + #(sumCustId) + "/payment-instruments", {
method: "POST"
headers: {
"Authorization": "Basic " + #(auth),
"Content-Type": "application/json"
},
data: body,
})
.then(function(response){
document.getElementById("response").value = response.text()
return response.text();
})
.then(function(data){
console.log(data)//text version
var data_obj = JSON.parse(data);
document.getElementById("data_obj").value = data_obj
return data_obj
})
}
</script>
</body>
</html>
I have finally managed to get a function that works, which is below.
<script>
function savecard() {
let customerId = document.getElementById("customerId").value;
let url = "https://api.sumup.com/v0.1/customers/" + customerId + "/payment-instruments"
let auth = " Basic " + document.getElementById("auth").value;
alert(auth);
let cardBody = {
type:"card",
card: {
name: document.getElementById("nameonCard").value,
cardNo: document.getElementById("cardNumber").value,
expiry_year: document.getElementById("expiryMonth").value,
expiry_month: document.getElementById("expiryYear").value,
cvv: document.getElementById("cvc").value
}
};
alert(cardBody.card.name);
let options = {
//mode: 'no-cors',
method: 'POST',
body: JSON.stringify(cardBody),
headers: {
'Content-Type': 'application/json',
'Authorization': auth
}
}
fetch(url, options)
.then(res => res.json())
.then(res => alert(res))
.catch(err => alert(`Error with message: ${err}`));;
}
</script>
However I am now getting an error in the catch
SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data
Seems like this is a simple typo, but I've been looking at it to long to see what it is.
In the end this worked. I thin by placing it in the head of the leaf file and removing any leaf tags fixed the issues. Instead of using leaf tags I added hidden form inputs with the values set by the leaf tag then accessed that value in the function.
<script>
function savecard() {
let customerId = document.getElementById("customerId").value; // for testing hard code value in form
let url = "https://api.sumup.com/v0.1/customers/" + customerId + "/payment-instruments"
let auth = " Basic " + document.getElementById("auth").value; // for testing hard code value in form
let cardBody = {
type:"card",
card: {
name: document.getElementById("nameonCard").value,
cardNo: document.getElementById("cardNumber").value,
expiry_year: document.getElementById("expiryMonth").value,
expiry_month: document.getElementById("expiryYear").value,
cvv: document.getElementById("cvc").value
}
};
let headers = {
'Authorization': auth,
'Content-Type': 'application/json'
}
let options = {
//mode: 'no-cors',
method: 'POST',
body: JSON.stringify(cardBody), //
headers: headers
}
fetch(url, options)
.then(res => res.json())
var token = res.token
document.getElementById("token").value = token
.then(res => console.log(res))
.catch(err => alert(`Error with message: ${err}`));;
document.getElementById("paymentForm").submit()
}
</script>
Hopefully that helps someone.

Save multiple dynamically added file in mongoose

I'm using Ajax to add (and remove) multiple fields in a form, and then submitting them to mongoose to save them. Unfortunatelly I'm able to retrieve and save only 1 array, missing completely the dinamically added ones.
HTML: Here's a form with a form-group visible, where I inizialise the array using name attributes,and a form-group template that I dinamically populate with Ajax
<form id="productAdd" class="form-horizontal" method="post" enctype="multipart/form-data" action="?_csrf={{csrfToken}}">
<section class="panel">
<div class="panel-body">
<div class="form-group" data-option-index="1">
<label class="col-md-3 control-label" for="optionType">Type</label>
<div class="col-md-1">
<select class="form-control" name="options[0][optionType]">
<option value="grams">Gr.</option>
</select>
</div>
<label class="col-md-1 control-label" for="value">Value</label>
<div class="col-md-1">
<input type="text" class="form-control" name="options[0][optionValue]">
</div>
<label class="col-md-1 control-label" for="price">Price</label>
<div class="col-md-1">
<input type="text" class="form-control" name="options[0][optionPrice]">
</div>
<div class="col-md-1">
<button type="button" class="btn btn-default addButton"><i class="fa fa-plus"></i></button>
</div>
</div>
<div class="form-group hide" id="optionTemplate">
<label class="col-md-3 control-label" for="optionType">Type</label>
<div class="col-md-1">
<select class="form-control" name="optionType">
<option value="grams">Gr.</option>
</select>
</div>
<label class="col-md-1 control-label" for="value">Value</label>
<div class="col-md-1">
<input type="text" class="form-control" name="optionValue">
</div>
<label class="col-md-1 control-label" for="price">Price</label>
<div class="col-md-1">
<input type="text" class="form-control" name="optionPrice">
</div>
<div class="col-md-1">
<button type="button" class="btn btn-default removeButton"><i class="fa fa-minus"></i></button>
</div>
</div>
</div>
<footer class="panel-footer">
<div class="row">
<div class="col-sm-9 col-sm-offset-3">
<input type="hidden" name="_csrf" value="{{csrfToken}}">
<button class="btn btn-primary">Submit</button>
<button type="reset" class="btn btn-default">Reset</button>
</div>
</div>
</footer>
</section>
</form>
AJAX: I use this to add rows or remove them, each with 3 inputs. Before submitting the form I use .serialize() to get the arrays by their names
$(document).ready(function() {
var optionIndex = $(".form-group[data-option-index]").length;
$('#productAdd').submit(function(e) { // add product submit function
e.preventDefault();
$(this).ajaxSubmit({
contentType: 'application/json',
data: $('form[name="productAdd"]').serialize(),
error: function(xhr) {
console.log('Error: ' + xhr.status + ' ---- ' + xhr.responseText);
},
success: function(response) {
if (typeof response.redirect === 'string')
window.location = response.redirect;
}
});
return false;
})
// Add button click handler
.on('click', '.addButton', function() {
optionIndex++;
var $template = $('#optionTemplate'),
$clone = $template
.clone()
.removeClass('hide')
.removeAttr('id')
.attr('data-option-index', optionIndex)
.insertBefore($template);
// Update the name attributes
$clone
.find('[name="optionType"]').attr('name', 'options[' + optionIndex + '].optionType').end()
.find('[name="optionValue"]').attr('name', 'options[' + optionIndex + '].optionValue').end()
.find('[name="optionPrice"]').attr('name', 'options[' + optionIndex + '].optionPrice').end();
})
// Remove button click handler
.on('click', '.removeButton', function() {
var $row = $(this).parents('.form-group'),
index = $row.attr('data-option-index');
// Remove fields
$row.find('[name="options[' + index + '].title"]').remove();
$row.find('[name="options[' + index + '].isbn"]').remove();
$row.find('[name="options[' + index + '].price"]').remove();
// Remove element containing the fields
$row.remove();
});
});
NODEJS: Here's my nodejs route, I use multer for managing file upload. I've a foreach should manage the inputs from the form, but it just see the first element.
router.post('/shop/products/add', [isLoggedIn, multer({dest: './public/images/products/'}).single('productPhoto')], function(req, res, next) {
var newProduct = new Product();
newProduct.imagePath = req.file.filename;
newProduct.title = req.body.title;
newProduct.description = req.body.description;
newProduct.price = req.body.price;
newProduct.save()
.then(function (product) {
console.log(req.body.options);
req.body.options.forEach(function (option) {
var newOption = new ProductOption();
newOption.type = option.optionType;
newOption.value = option.optionValue;
newOption.price = option.optionPrice;
newOption.product = product;
newOption.save();
});
})
.then(function (options) {
req.flash('success', 'Product uploaded correctly.');
res.send({redirect: '/user/shop/products/add'});
})
.catch(function (err) {
console.log('Error ' + err.code + ': ', err.message);
res.status(500).send('Failed to save the newAddress to DB: ' + err);
});
});
It was a simple mistake, I named the fields dinamically added, differently from the static ones.
this code
.find('[name="optionType"]').attr('name', 'options[' + optionIndex + '].optionType').end()
should be like this
.find('[name="optionType"]').attr('name', 'options[' + optionIndex + '][optionType]').end()

How to get the file value in Jquery and pass value in AJAX [duplicate]

This question already has answers here:
Uploading both data and files in one form using Ajax?
(13 answers)
Closed 6 years ago.
Here I want insert the values in Database here normal value like name, email, area... This value getting and after that value passed in next through AJAX and doing insertion part but while file uploading I can't get consloe.log(file); I am getting like this C:\fakepath\Penguins.jpg I don't know how to resolve this,i want get the file value and pass in next page thrugh AJAX and move to tmp folder how can do.
function add_menu() {
var name = $("#name").val();
var address = $("#address").val();
var area = $("#area").val();
var file = $("#file").val();
var gender = $("input[name=gender]:checked").val();
var checkValues = $('input[name=fecility]:checked').map(function() {
return $(this).val();
}).get();
if (name == '') {
$("#span-error").html(' Fill Menu Name. ');
} else if (gender == '') {
$("#span-error").html(' Select Gender. ');
} else if (area == '') {
$("#span-error").html(' Fill area. ');
} else if (checkValues == '') {
$("#span-error").html(' Select Fecilities. ');
} else {
$.ajax({
type: "POST",
url: "ajax_add_menu.php",
data: "name=" + name + "&area=" + area + "&address=" + address + "&gender=" + gender + "&checkbox=" + checkValues,
success: function(data) { // alert(data);
if (data == "success") {
window.location = 'pg_details.php';
}
}
});
}
}
<form class="form-horizontal" role="form" id="formid" method="post" enctype="multipart/form-data">
<div class="form-group">
<label class="col-sm-2 control-label">Name<span class="require">*</span>
</label>
<div class="col-sm-8">
<input type="text" class="form-control" placeholder="Name" name="name" id="name">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Area<span class="require">*</span>
</label>
<div class="col-sm-8">
<input type="text" class="form-control" placeholder="Area" name="area" id="area">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Address<span class="require">*</span>
</label>
<div class="col-sm-8">
<textarea class="form-control" placeholder="Enter Address" name="address" id="address" style="min-height:100px;"></textarea>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Room Standereds<span class="require">*</span>
</label>
<div class="col-sm-8" style="margin-top:10px">
<?php $sqlf="SELECT * FROM pg_fecilitys" ; $resultf=m ysql_query($sqlf); while($rowf=m ysql_fetch_array($resultf)) { echo '<input type="checkbox" id="fecility" name="fecility" value="'.$rowf[ "f_id"]. '" required style="margin: 0px 2px 0px 18px;">'.$rowf[
"f_name"]; } ?>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Gender<span class="require">*</span>
</label>
<div class="col-sm-8">
<label class="radio-inline">
<input type="radio" id="gender" name="gender" value="male">Male</label>
<label class="radio-inline">
<input type="radio" id="gender" name="gender" value="female">Female</label>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">PG Image<span class="require">*</span>
</label>
<div class="col-sm-8">
<input type="file" class="form-control" placeholder="PG Image" name="file" id="file">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<div class="tcb">
<label>
<span id="span-error" style="color:#f00;"></span>
</label>
</div>
</div>
</div>
<div class="form-actions">
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="button" class="btn btn-primary" onclick="add_menu()">Submit</button>
<!-- <button type="submit" class="btn">Cancel</button> -->
</div>
</div>
</div>
</form>
If you want value of the file, use - var file = $("#file").val(); ,
But if you want file then use - var file = $("#file").get(0).files[0];
Also if you want to pass file with ajax, then use jquery FormData() like:
function add_menu() {
var name = $("#name").val();
var address = $("#address").val();
var area = $("#area").val();
var file = $("#file").val();
var gender = $("input[name=gender]:checked").val();
fd = new FormData();
fd.append('file', $("#file").get(0).files[0]);
fd.append('name ', name );
fd.append('address', address);
fd.append('area', area);
fd.append('gender', gender);
// remaining codes - checking and ajax
////
$.ajax({
type: "POST",
url: "ajax_add_menu.php",
data: fd,
success: function(data) { // alert(data);
if (data == "success") {
window.location = 'pg_details.php';
}
}
});
Try to using form data object instead of string
data: new FormData('#formid'),
Replace this with above line
data: "name=" + name + "&area=" + area + "&address=" + address + "&gender=" + gender + "&checkbox=" + checkValues,
You could not upload file via ajax like this you need metadata, instead of json object, you can code ajax like below:-
// have a look..
formdata= new FormData($('#formid')[0]);
// to console data you do it with just get method on form data like
console.log(formdata.get('file')); // for file
console.log(formdata.get('name')); // name will be displayed
$.ajax ( {
method : 'POST',
url : 'ajax_add_menu.php',
data : formdata,
cache : false,
processData: false,
contentType: false,
success : function ( data, textStatus, jqXHR ) {
// do what ever in your success in code
},
error : function ( jqXHR, textStatus, errorThrown ) {
// do what ever in failure
}
} );

Categories

Resources