Javascript function in vapor 3 leaf - Help Need - javascript

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.

Related

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

Form in ajax post method sends empty object

I have a webform with several fields I want to capture in an object and send it to a controller method. The form has this code:
<div class="panel-footer">
#using (Html.BeginForm("NuevaOpcion", "Home", FormMethod.Post, new { #id = "frm_nueva_opcion" })) {
#Html.HiddenFor(m => m.Id)
<div class="row">
<div class="col-md-6">
<div class="form-group" style="margin-bottom: .7em;margin-top: .7em;">
<button class="btn btn-success btn-xs" type="button" onclick=" $('#row-nueva-opcion').toggle()" id="add-opcion">
<span class="glyphicon glyphicon-plus-sign"></span> Añadir nueva opción
</button>
</div>
</div>
</div>
<div class="row" id="row-nueva-opcion" style="display:none">
<div class="col-md-10">
<label>
<input type="checkbox" id="opcion-extra" onclick=" $('#nuevo-precio').attr('disabled', !this.checked);" />
Es opción extra
</label>
<div class="input-group" style="margin-bottom:1.7em;">
<input type="text" placeholder="Opción" class="form-control" name="nombre" style="max-width:70%;">
<input type="number" placeholder="Cantidad" min="1" value="1" class="form-control" name="cantidad" style="max-width:15%;">
<input type="number" placeholder="Precio" class="form-control" id="nuevo-precio" name="precio" style="max-width:15%;" disabled>
<input type="hidden" name="idrespuesta" id="idrespuesta" value="#listItems.Select(x=>x.Value).FirstOrDefault()" />
<div class="input-group-addon">€</div>
<span class="input-group-btn">
<a class="btn btn-primary" data-title="Confirmación de acción" data-toggle="modal" data-target="#modal_confirm" onclick="confirmar('frm_nueva_opcion')">
<span class="glyphicon glyphicon-floppy-disk"></span> Guardar
</a>
</span>
</div>
</div>
<div class="col-md-8">
<div class="form-group">
<label>
¿Para que pregunta es la opción?
#Html.DropDownList("OptionSelectedItem", listItems, new { #class = "form-control" })
</label>
</div>
</div>
</div>
}
</div>
To manage it, I have a script that looks like this:
function mostrarModal(idmodal, mensaje, tipo) {
$(idmodal + ' .modal-body h4').addClass(tipo == 'error' ? 'text-danger' : 'text-secondary').html(mensaje);
$(idmodal).modal('show');
}
function enviar(form) {
debugger;
var NuevoPrecio = $('#' + form).attr("nuevo-precio");
if( (NuevoPrecio == null) || (typeof NuevoPrecio === "undefined") ) { var NuevoPrecio = 0; }
var datos = {
Id: $('#' + form).attr("#Id"),
IdPresupuestador: $('#' + form).attr("#idPresupuestador"),
IdRespuesta: $('#' + form).attr("#idrespuesta"),
Cantidad: $('#' + form).attr("#cantidad"),
Nombre: $('#' + form).attr("#nombre"),
Precio: NuevoPrecio,
}
$.post("NuevaOpcion", {
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(datos),
});
}
var modalConfirm = function (callback) {
$("#modal-btn-si").on("click", function () {
callback(true);
$("#modal-confirm").modal('hide');
});
$("#modal-btn-no").on("click", function () {
callback(false);
$("#modal-confirm").modal('hide');
}); };
function confirmar(form, text) {
$("#modal-confirm").modal('show');
modalConfirm(function (confirm) {
if (confirm) {
enviar(form);
}
}); };
Trouble is, I've changed the script on several points and now looks like this because the best I could manage was taking all the form in a single object. I can't work with the properties contained in that object, not on the script and neither on the controller method.
So, the question is, how am I selecting the fields wrong? I've tried with "#", ".", just the name between quotes, and as I said, the best I could get was the entire form in a single object. Thanks in advance.

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

customize sweetalert2 outputting raw json

I want to display a sweetalert message if registration is successful or fail (I wrote the sweetalert code in a jquery file) and included it inside the registration view page (it is included in the master.blade.php which all pages extend) but instead of displaying the sweetalert error or success message, it keeps displaying parsed json format message.
These are the files created.
custom_file.js
$(document).ready(function () {
var form = $('#registration');
form.submit(function (e) {
e.preventDefault();
$.ajax({
url: form.attr('action'),
type: "POST",
data: form.serialize(),
dataType: "json"
})
.done(function (response) {
if (response.success) {
swal({
title: "Hi " + response.name,
text: response.success,
timer: 5000,
showConfirmButton: false,
type: "success"
});
window.location.replace(response.url);
} else {
swal("Oops!", response.errors, 'error');
}
})
.fail(function () {
swal("Fail!", "Cannot register now!", 'error');
});
});
the registraion.blade.php file
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">AJAX Register</div>
<div class="panel-body">
<form class="form-horizontal" id="registration" method="POST" action="{{ url('users/register') }}" data-parsley-validate="">
{!! csrf_field() !!}
<div class="form-group">
<label class="col-md-4 control-label">Name</label>
<div class="col-md-6">
<input type="text" class="form-control" name="name" id="name" required="">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">E-Mail Address</label>
<div class="col-md-6">
<input type="email" class="form-control" name="email" id="email" required="">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Password</label>
<div class="col-md-6">
<input type="password" class="form-control" name="password" id="password" required="">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Confirm Password</label>
<div class="col-md-6">
<input type="password" class="form-control" name="password_confirmation" id="password_confirmation" data-parsley-equalto="#password" required="">
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary ladda-button" data-style="expand-left" data-size="s" data-color="green">
<i class="fa fa-btn fa-user"></i> Register
</button>
<div class="btn btn-md btn-primary ladda-button" data-style="expand-left" data-size="s" data-color="blue"> <i class="fa fa-facebook"></i> Login with Facebook </div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
and this is the RegisterController.php script
public function postRegister(Request $request)
{
$validator = Validator::make($request->all(), [
'email' => 'required|email|unique:users,email',
'name' => 'required|min:2',
'password' => 'required|alphaNum|min:6|same:password_confirmation',
]);
if ($validator->fails()) {
$message = ['errors' => $validator->messages()->all()];
$response = Response::json($message, 202);
} else {
// Create a new user
$user = new User([
'name' => $request->name,
'email' => $request->email,
'password' => $request->password,
'facebook_id' => $request->email
]);
$user->save();
Auth::login($user);
$message = ['success' => 'Thank you for joining us!', 'url' => '/', 'name' => $request->name];
$response = Response::json($message, 200);
}
return $response;
}
}
Here's some test code:
index.php
<!DOCTYPE html>
<html>
<head>
<title>SweetAlert2 test</title>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/6.6.5/sweetalert2.min.css">
</head>
<body>
<form id="myForm" method="post" action="ajax.php">
<input type="text" name="uname">
<input type="submit" value="Submit">
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/6.6.5/sweetalert2.min.js"></script>
<script>
$(document).ready(function () {
var form = $('#myForm');
form.submit(function (e) {
e.preventDefault();
$.ajax({
url: form.attr('action'),
type: "POST",
data: form.serialize(),
dataType: "json"
})
.done(function (response) {
if (response.data) {
swal({
title: "Message",
text: response.data,
timer: 5000,
showConfirmButton: false,
type: "success"
})
.then(function() {}, function() {
// redirect after alert has been displayed
window.location.replace("https://google.com");
});
} else {
swal("Oops!", "Registration error!", 'error');
}
})
.fail(function () {
swal("Fail!", "Network/Server error!", 'error');
});
});
});
</script>
</body>
</html>
ajax.php
<?php
$user = isset($_POST['uname']) ? $_POST['uname'] : "Anonymous";
$myJson = ["data" => "Hi " . $user . "! Thank you for joining us!"];
echo(json_encode($myJson));
This works fine! Compare it with your code to see if there's an error somewhere.

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

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();

Categories

Resources