javascript illegal invocation in $.ajax - javascript

I want to upload an image using ajax in Laravel. Sending formData is giving me
Uncaught TypeError: Illegal invocation
at e (jquery-2.1.4.js:4)
at Ab (jquery-2.1.4.js:4)
at Function.n.param (jquery-2.1.4.js:4)
at Function.ajax (jquery-2.1.4.js:4)
at HTMLFormElement.<anonymous> (products:153)
at HTMLFormElement.dispatch (jquery-2.1.4.js:3)
at HTMLFormElement.r.handle (jquery-2.1.4.js:3)
in the console. I checked the networks and found that formData is fine.
Here is my ajax call
$('#product_form').on('submit', function (e) {
e.preventDefault();
var form_data = new FormData( $('#product_form')[0]);
$.ajax({
type: 'POST',
url: '/admin/insert/products',
data : form_data,
success: function (result) {
if(result.success == 1){
$('#product_message').html('product Successfully Added!!');
}
},
error: function(result){
$('#product_message').html('Something went wrong!! Login Again!!');
$('#product_submit').prop("disabled" ,false);
$('#product_submit').html("Add product");
}
});
});
And this is my form in the view
<form class="col s12" method="post" enctype="multipart/form-data" id="product_form">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="row">
<div class="input-field col s12 m4 offset-m4">
<input id="name" type="text" class="validate" name="name">
<label for="name">Item Name</label>
</div>
<div class="input-field col s12 m4 offset-m4">
<input id="tagline" type="text" class="validate" name="tagline">
<label for="tagline">Tagline</label>
</div>
<div class="input-field col s12 m4 offset-m4">
<div class="file-field input-field">
<div class="btn red">
<span>Item Pic</span>
<input type="file" id="pic" name="item">
</div>
<div class="file-path-wrapper">
<input class="file-path validate" type="text">
</div>
</div>
</div>
<div class="input-field col s12 m4 offset-m4">
<input id="brand" type="text" class="validate" name="brand" style="text-transform:uppercase;">
<label for="brand">Brand Name</label>
</div>
<div class="input-field col s12 m4 offset-m4">
<select name="category">
<option value="" selected>Choose Category</option>
#foreach($categories as $category)
<option value="{{$category->name}}">{{$category->name}}</option>
#endforeach
</select>
<label>Select Item Category</label>
</div>
<div class="input-field col s12 m4 offset-m4">
<button type="submit" class="btn col s12 red" id="product_submit">Add Product</button>
</div>
</div>
</form>

Add the following parameters to the passed object to $.ajax:
contentType: false,
// The following is necessary so jQuery won't try to convert the object into a string
processData: false

Related

Array returns as null in JS but "non-null" in GS

I'm attempting to use Apps Script and JS on a web app to retreive information stored in a google sheet, then output it to the webapp. However, I keep getting the error "cannot read property of null".
Problem is, when i run the apps script side of the code (as follows), my array is fine and when I log it to the console, it comes up no problem : code in snippit at end
When I run my code from the web app, I get the error. Here is the JS code : code in snippit at end
I've narrowed the error down to the last line of code, and to be more specific, the infoArray[i]. It just comes out as an array full of "null", even though when I run the GS code, it retruns the array as it should, with all the info as it is in the spreadsheet.
I've read at least 10 other threads, but still can't seem to figure out why this won't work. Any insight would be much appreciated !
Thank you
2ND EDIT WITH MRE (Sorry this is quite a long snippit. Both include-css files are empty for the moment, no use in the code themselves)
JavaScript
document.addEventListener('DOMContentLoaded', function() {
var elems2 = document.querySelectorAll('.autocomplete');
var instances2 = M.Autocomplete.init(elems2);
google.script.run.withSuccessHandler(populateWords).getNames();
})
document.getElementById('loadButton').addEventListener('click', clickGetInfo);
//FOR AUTOCOMPLETE
function populateWords(words) {
var autocomplete = document.getElementById("autoEmployee");
var instances = M.Autocomplete.init(autocomplete, {
data: words
});
}
function clickGetInfo() {
var employeeInfo = {};
employeeInfo.name = document.getElementById('autoEmployee').value;
google.script.run.withSuccessHandler(updateText).getInfoEdit(employeeInfo);
}
function updateText(infoArray) {
var elements = ["matricule", "sexe", "civ", "nom", "prenom", "nomJf", "birthday", "nationalite", "adresse", "codePostal", "ville", "pays", "communeNais", "paysNais", "dptNais", "numerosecu", "email",
"telephone", "shop", "contrat", "hhebdo", "dateDebut", "periodeEssais", "dateFin", "tuteur", "poste", "statut", "echelon", "salaire", "iban", "bic", "domiciliation",
"primeTel", "primeFroid", "comment", "rqth", "commentRqth", "titreSejour", "numeroTitre", "dateExpiration", "dateIngestion"
];
for (var i = 0; i < elements.length; i++) {
// console.log(document.getElementById(elements[i]).value);
// console.log(infoArray);
document.getElementById(elements[i]).value = infoArray[i];
}
}
GS
//common vars
var id = '1Sq6f68fjnF3qPfi6guWlSHT84f_UjcFFMnAXwKsqQkM'; // data base
//VARIABLES PAGE HTML
var Route = {};
Route.path= function(route,callback){
Route[route] = callback;}
// doGet + routes
function doGet(e) {
Route.path("pageEditEmployee",loadEdit);
if(Route[e.parameter.v]){
return Route[e.parameter.v]();
}else{
return HtmlService.createTemplateFromFile("home").evaluate();}}
// load edit page
function loadEdit(){
var tmp = HtmlService.createTemplateFromFile("pageEditEmployee");
return tmp.evaluate();
}
//CREATION DE LA FONCTION INCLUDE HTML
function include(filename){
return HtmlService.createHtmlOutputFromFile(filename).getContent();}
function getInfoEdit(employeeInfo) {
var ss = SpreadsheetApp.openById(id);
var wsData = ss.getSheetByName("DATA");
var data = wsData.getDataRange().getValues();
var infoArray = new Array();
var matricule = employeeInfo.name;
Logger.log(matricule);
for (var i = 0; i < data.length; i++) {
if (data[i][41] == matricule) {
//[41] for column AP
var row = i + 1; // row of data
Logger.log(row);
}
}
for (var i = 1; i < 42; i++) {
infoArray.push(wsData.getRange(row, i).getValue()); // push data into array
}
return infoArray; // return the array
}
// names for AUTOCOMPLETE FOR EDIT PAGE
function getNames() {
var ss = SpreadsheetApp.openById(id);
var wsData = ss.getSheetByName("DATA");
var lastRow = wsData.getRange("A1").getDataRegion().getLastRow();
var listOfNames = wsData.getRange(2, 42, lastRow - 1, 1).getValues();
var obj = Object.fromEntries(
// create object from array
listOfNames.map((name) => [name, null])
);
return obj;
}
HTML EDIT PAGE
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<?!= include("pageEditEmployee-css");?>
</head>
<body>
<div class="container">
<div class="row"></div>
<nav>
<div class="nav-wrapper lime">
<a class="brand-logo right">Espace RH</a>
<ul id="nav-mobile" class="left hide-on-med-and-down">
<li><i class="material-icons left">home</i>Home</li>
</ul>
</div>
</nav>
<div class="container">
<!-- DIV CONTAINER 1 -->
<div class="row">
<div class="col s12">
<div class="row">
<div class="input-field col s6">
<i class="material-icons prefix">textsms</i>
<input type="text" id="autoEmployee" class="autocomplete">
<label for="autoEmployee">Take your pick</label>
</div>
<div class="input-field col s6">
<button id="loadButton" class="btn waves-effect waves-light" type="submit" name="action">Load
<i class="material-icons right">check_circle</i>
</button>
</div>
</div>
</div>
</div>
<div class="row">
<div class="input-field col s3">
<input disabled value="Matricule" id="matricule" type="text" class="validate">
</div>
<div class="input-field col s3">
<input disabled value="Civilité" id="civ" type="text" class="validate">
</div>
<div class="input-field col s3">
<input disabled value="Sexe" id="sexe" type="text" class="validate">
</div>
<div class="input-field col s3">
<input disabled value="Nom" id="nom" type="text" class="validate">
</div>
</div>
<div class="row">
<div class="input-field col s4">
<input disabled value="Prénom" id="prenom" type="text" class="validate">
</div>
<div class="input-field col s4">
<input disabled value="Nom Jeune Fille" id="nomJf" type="text" class="validate">
</div>
<div class="input-field col s4">
<input disabled value="Date de Naissance" id="birthday" type="text" class="validate">
</div>
</div>
<div class="row">
<div class="input-field col s4">
<input disabled value="Nationalité" id="nationalite" type="text" class="validate">
</div>
<div class="input-field col s4">
<input disabled value="Adresse" id="adresse" type="text" class="validate">
</div>
<div class="input-field col s4">
<input disabled value="Code Postal" id="codePostal" type="text" class="validate">
</div>
</div>
<div class="row">
<div class="input-field col s4">
<input disabled value="Ville" id="ville" type="text" class="validate">
</div>
<div class="input-field col s4">
<input disabled value="Pays" id="pays" type="text" class="validate">
</div>
<div class="input-field col s4">
<input disabled value="Commune de Naissance" id="communeNais" type="text" class="validate">
</div>
</div>
<div class="row">
<div class="input-field col s4">
<input disabled value="Pays de Naissance" id="paysNais" type="text" class="validate">
</div>
<div class="input-field col s4">
<input disabled value="Département de Naissance" id="dptNais" type="text" class="validate">
</div>
<div class="input-field col s4">
<input disabled value="Numéro de sécurité sociale" id="numerosecu" type="text" class="validate">
</div>
</div>
<div class="row">
<div class="input-field col s4">
<input disabled value="Email" id="email" type="text" class="validate">
</div>
<div class="input-field col s4">
<input disabled value="Téléphone" id="telephone" type="text" class="validate">
</div>
<div class="input-field col s4">
<input disabled value="Atelier" id="shop" type="text" class="validate">
</div>
</div>
<div class="row">
<div class="input-field col s4">
<input disabled value="Type de contrat" id="contrat" type="text" class="validate">
</div>
<div class="input-field col s4">
<input disabled value="Heures Hebdo" id="hhebdo" type="text" class="validate">
</div>
<div class="input-field col s4">
<input disabled value="Date de début" id="dateDebut" type="text" class="validate">
</div>
</div>
<div class="row">
<div class="input-field col s3">
<input disabled value="Fin de la période probatoire" id="periodeEssais" type="text" class="validate">
</div>
<div class="input-field col s3">
<input disabled value="Fin contrat si CDD" id="dateFin" type="text" class="validate">
</div>
<div class="input-field col s3">
<input disabled value="Tuteur ou Tutrice" id="tuteur" type="text" class="validate">
</div>
<div class="input-field col s3">
<input disabled value="Poste" id="poste" type="text" class="validate">
</div>
</div>
<div class="row">
<div class="input-field col s4">
<input disabled value="Statut" id="statut" type="text" class="validate">
</div>
<div class="input-field col s4">
<input disabled value="Echelon" id="echelon" type="text" class="validate">
</div>
<div class="input-field col s4">
<input disabled value="Salaire" id="salaire" type="text" class="validate">
</div>
</div>
<div class="row">
<div class="input-field col s4">
<input disabled value="IBAN" id="iban" type="text" class="validate">
</div>
<div class="input-field col s4">
<input disabled value="BIC" id="bic" type="text" class="validate">
</div>
<div class="input-field col s4">
<input disabled value="Domiciliation" id="domiciliation" type="text" class="validate">
</div>
</div>
<div class="row">
<div class="input-field col s4">
<input disabled value="Prime de téléphone" id="primeTel" type="text" class="validate">
</div>
<div class="input-field col s4">
<input disabled value="Prime froid" id="primeFroid" type="text" class="validate">
</div>
<div class="input-field col s4">
<input disabled value="Commentaires primes" id="comment" type="text" class="validate">
</div>
</div>
<div class="row">
<div class="input-field col s4">
<input disabled value="RQTH" id="rqth" type="text" class="validate">
</div>
<div class="input-field col s4">
<input disabled value="Commentaires RQTH" id="commentRqth" type="text" class="validate">
</div>
<div class="input-field col s4">
<input disabled value="Titre de séjour" id="titreSejour" type="text" class="validate">
</div>
</div>
<div class="row">
<div class="input-field col s4">
<input disabled value="Numéro de titre" id="numeroTitre" type="text" class="validate">
</div>
<div class="input-field col s4">
<input disabled value="Date expiration" id="dateExpiration" type="text" class="validate">
</div>
<div class="input-field col s4">
<input disabled value="Date d'enregistrement de la personne" id="dateIngestion" type="text" class="validate">
</div>
</div>
</div>
<!-- END DIV CONTAINER 1 -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<?!= include("pageEditEmployee-js");?>
<div class="container">
<footer class="page-footer light-green darken-4 s12">
<div class="footer-copyright lime">
<div class="container black-text">
</div>
</div>
</footer>
</div>
</body>
</html>
HTML home page
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<?!= include("home-css");?>
</head>
<body>
<div class="container">
<div class="row"></div>
<nav>
<div class="nav-wrapper lime">
<a class="brand-logo right"></a>
<ul id="nav-mobile" class="left hide-on-med-and-down">
<li><i class="material-icons left">home</i>Accueil</li>
</ul>
</div>
</nav>
<div class="row"></div>
<h3 class="card-panel z-depth-3 white-text light-green darken-4">Hello, world</h3>
<div class="row"></div>
<div class="row"><!-- 1ERE LIGNE -->
<div class="col s6 m6">
<div class="card horizontal">
<div class="card-image">
<i class="large material-icons">access_time</i>
</div>
<div class="card-stacked">
<div class="card-content">
<p>My problem is in here</p>
</div>
<div class="card-action">
<a class="green-text" href="<?= ScriptApp.getService().getUrl();?>?v=pageEditEmployee">Click me</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div><!-- CLOSE CONTAINER -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<div class="container">
<footer class="page-footer light-green darken-4 s12">
<div class="footer-copyright lime">
<div class="container black-text">
</div>
</div>
</footer>
</div>
</body>
</html>
Trying out your MRE I was getting completely different errors from you. But it was helpful to at least understand what you are trying to do.
What I believe the issue is:
Requests fail if you attempt to pass a Date, Function, DOM element besides a form, or other prohibited type, including prohibited types inside objects or arrays.
Parameters and return values - Google Documentation
Within your data is Date objects, so this will return null. I think this is the error you are getting.
Solution
So here is a minimal reproducible example, showing how to get your data as an array into the front-end.
Code.gs
function doGet(){
return HtmlService.createHtmlOutputFromFile("index")
}
function getInfo() {
let file = SpreadsheetApp.getActive();
let sheet = file.getSheetByName("Sheet1");
let range = sheet.getDataRange();
let values = range.getValues();
return JSON.stringify(values);
}
index.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<h1>Hello</h1>
<button id=main>Run</button>
<script>
function main(){
google.script.run.withSuccessHandler(handleInfo).getInfo()
}
function handleInfo(info){
console.log(JSON.parse(info))
}
const mainButton = document.getElementById("main")
mainButton.addEventListener('click', () => main())
</script>
</body>
</html>
Pressing the button in the web page results in this in the console:
Main change:
On the return value from Apps Script (server)
JSON.stringify([YOUR ARRAY OR OBJECT WITH DATES]);
Then when you recieve it in the front-end:
JSON.parse([YOUR ARRAY OR OBJECT WITH DATES])
References
JSON Object
Client-Server communication
Try this:
function getInfoEdit(employeeInfo) {
var ss = SpreadsheetApp.openById(id);
var dsh = ss.getSheetByName('DATA');
var data = dsh.getDataRange().getValues()
var infoArray = [];
var matricule = employeeInfo.name;
for (var i = 0; i < data.length; i++) {
if (data[i][41] == matricule) { //[41] for column AP column 42
infoArray.push(data[i]);//This pushes the entire row in to your output array
}
}
return (infoArray); // return the array
}
Can't confirm any of this because you did not supply the html but there are only 41 elements in the array below. I believe that you have 42 columns
function updateText(infoArray){
var elements = ["matricule","sexe", "civ", "nom", "prenom", "nomJf", "birthday", "nationalite", "adresse", "codePostal", "ville", "pays", "communeNais", "paysNais", "dptNais", "numerosecu", "email",
"telephone", "shop", "contrat", "hhebdo", "dateDebut", "periodeEssais", "dateFin", "tuteur", "poste", "statut", "echelon", "salaire", "iban", "bic", "domiciliation",
"primeTel", "primeFroid", "comment", "rqth", "commentRqth", "titreSejour", "numeroTitre", "dateExpiration","dateIngestion"];
for (var i = 0;i<elements.length;i++){
document.getElementById(elements[i]).value = infoArray[i];
}
}

integrating dropzone with normal form

I have successfully integrated dropzone with my form using jquery. However, I have an issue with validation of the other form inputs. It seems the other form inputs do not respect the validation such as "required". I also tried using parsley for validation but does not work. when I remove the dropzone field, the validation works well.
Here is the form.
<form class="form-vertical"
id="createPropertyForm"
enctype="multipart/form-data"
method="POST"
>
<div class="col-md-12 col-lg-12 col-sm-12" >
<div class="col-md-6">
<div class="form-group">
<label class=" control-
label">Country</label>
<div class="inputGroupContainer">
<input id="country"
name="country" placeholder="Country" class="form-control" required
value="" type="text">
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="control-
label">County</label>
<div
class="inputGroupContainer">
<input id="county"
name="county" placeholder="County" class="form-control" required value=""
type="text">
</div>
</div>
</div>
</div>
<div class="col-md-12 col-lg-12 col-sm-12" >
<div class="col-md-6">
<div class="form-group">
<label class=" control-
label">Town</label>
<div class=" inputGroupContainer">
<input id="town" name="town"
placeholder="Town" class="form-control" required value="" type="text">
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="control-
label">Postcode</label>
<div class="inputGroupContainer">
<input id="postcode"
name="postcode" placeholder="Postcode" class="form-control" required
value=""
type="text">
</div>
</div>
</div>
</div>
<div class="col-md-12 col-lg-12 col-sm-12" >
<div class="col-md-6">
<div class="form-group">
<label class=" control-
label">Description</label>
<div class=" inputGroupContainer">
<textarea id="description"
name="description" placeholder="Description" class="form-control"
required="true" value="" type="text"></textarea>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="control-
label">Address</label>
<div class="inputGroupContainer">
<input id="address" name="address"
placeholder="Address" class="form-control" required value="" type="text">
</div>
</div>
</div>
</div>
<div class="col-md-12 col-lg-12 col-sm-12" >
<div class="col-md-6">
<div class="form-group">
<label class=" control-
label">Bedrooms</label>
<div class=" inputGroupContainer">
<select class=" form-control"
name="bedrooms" id="bedrooms" required>
</select>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="control-label
">Bathrooms</label>
<div class=" inputGroupContainer">
<select
class="selectpicker bathrooms form-control" name="bathrooms"
id="bathrooms"
required>
</select>
</div>
</div>
</div>
</div>
<div class="col-md-12 col-lg-12 col-sm-12" >
<div class="col-md-6">
<div class="form-group">
<label class=" control-
label">Price</label>
<div class="inputGroupContainer">
<input id="price" name="price"
placeholder="Price" class="form-control" required value="" type="number">
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="control-
label">Property Type</label>
<div class=" inputGroupContainer">
<select
class="selectpicker form-control" name="propertyType" id="propertyType">
<option
value="">Choose type</option>
<?php
foreach
($propertyTypes as $propertyType) {
?>
<option value="<?=
$propertyType->id ?>"><?= $propertyType->title ?></option>
<?php
}
?>
</select>
</div>
</div>
</div>
</div>
<div class="col-md-12 col-lg-12 col-sm-12" >
<div class="col-md-6">
<div class="form-group">
<label class=" control-
label">Type</label>
<div class="col-md-12">
<div class="col-md-6 ">
<label><input type="radio"
name="type" class="form-control type" required>Sale</label>
</div>
<div class="col-md-6">
<label><input type="radio"
name="type" class="form-control type" required>Rent</label>
</div>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="control-
label">Upload Image</label>
<div class=" inputGroupContainer">
<div class="dropzone"
id="create-dropzone" >
<div class="fallback">
<input name="file"
type="file" required/>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6 col-sm-6">
<div class="dropzone-previews"></div>
</div>
</div>
<div class="col-md-6 col-sm-6">
<button class="btn btn-success btn-lg"
type="submit" id="submitCreateForm"> Submit </button>
</div>
</form>.
Here is the jquery code:
// Parsley for form validation
$('#createPropertyForm').parsley();
$('#editPropertyForm').parsley();
Dropzone.options.createDropzone = {
url: `${baseUrl}administrator/properties`,
autoProcessQueue: false,
parallelUploads: 1,
maxFiles: 1,
maxFileSize:2048,
uploadMultiple: false,
acceptedFiles: "image/*",
init: function () {
var submitButton = document.querySelector("#submitCreateForm");
var wrapperThis = this;
submitButton.addEventListener("click", function (e) {
e.preventDefault();
if (wrapperThis.files.length) {
wrapperThis.processQueue();
} else {
wrapperThis.submit();
}
});
this.on("addedfile", function (file) {
var removeButton = Dropzone.createElement("<button class='btn btn-block btn-danger'><i class='fa-times fa'></button>");
removeButton.addEventListener("click", function (e) {
e.preventDefault();
e.stopPropagation();
wrapperThis.removeFile(file);
});
file.previewElement.appendChild(removeButton);
});
this.on('sending', function (data, xhr, formData) {
formData.append("country", $("#country").val());
formData.append("county", $("#county").val());
formData.append("town", $("#town").val());
formData.append("postcode", $("#postcode").val());
formData.append("description", $("#description").val());
formData.append("address", $("#address").val());
formData.append("bathrooms", $("#bathrooms").val());
formData.append("price", $("#price").val());
formData.append("bedrooms", $("#bedrooms").val());
formData.append("propertyTypeId", $("#propertyType").val());
formData.append("type", $(".type").val());
});
this.on('success', function (files, response) {
toastr.success(response.message);
setTimeout(function () {
location.reload();
}, 1000);
});
this.on('error', function (file, error, xhr) {
file.status = 'queued';
if (xhr.status === 422){
toastr.error('An error occurred, please confirm that you have filled all inputs and try again');
}else{
toastr.error('An error occurred');
}
});
this.on("maxfilesexceeded", function(file) {
wrapperThis.removeFile(file);
});
}
};

Not getting Formdata in post using ajax

I'm trying to get formdata to my php file. but i'm getting not any value on post. please advice me what i'm doing is right? i'm doing something wrong in post
// add item to additem
<script type="text/javascript">
$(document).ready(function(){
$("#additembutton").click(function(evt){
evt.preventDefault();
var formData = new FormData($("form #itemform")[0]);
alert(formData);
$.ajax({
url: 'additem.php',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
enctype: 'multipart/form-data',
processData: false,
success: function (response) {
alert(response);
}
});
return false;
});
</script>
// form submit image
This is my additem.php file
<?php
include '../class/dbconfig.php';
$filename=$_POST['myfile']['name'];
echo $_POST['myfile'];
This is my html form
<form class="form-horizontal" enctype="multipart/form-data">
<div class="form-group">
<label for="select" class="col-md-3 control-label">Menu Type</label>
<div class="col-md-6">
<select class="form-control" id="menutype">
<option>Select Menu</option>
<option value="fastfood">FastFood</option>
<option value="other">Other</option>
</select>
</div>
</div>
<!--
<div class="form-group" id="otherdiv">
<label for="menuorder" class="col-md-3 control-label">Other Menu Type</label>
<div class="col-md-6">
<input type="number" class="form-control" id="othermenu" placeholder="Enter Order">
</div>
</div>
-->
<div class="form-group">
<label for="menuorder" class="col-md-3 control-label">Menu Order</label>
<div class="col-md-6">
<input type="number" class="form-control" id="menuorder" pattern="[0-9]+" placeholder="Enter Order">
</div>
</div>
<div class="form-group">
<label for="select" class="col-md-3 control-label">Menu Status</label>
<div class="col-md-6">
<select class="form-control" id="menustatus">
<option value="1">Active</option>
<option value="0">Deactive</option>
</select>
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-3">
<button type="reset" class="btn btn-default">Cancel</button>
<button type="button" class="btn btn-primary" id="addmenubutton" >Submit</button>
</div>
</div>
</form>
You just need to send the form via post:
<form method="POST">

Codeigniter form serialize not working

i'm triying to pass data from form to controller in codeigniter...but when I want to print a table with the results...i'm getting null on every row of the table. Here is my code:
FORM
<form class="col s12" id="update_form" name="update_form" method="post" >
<div class="row">
<div class="input-field col s6">
<input id="update_name" type="text" name="name" class="validate">
<label for="first_name">Nombre</label>
</div>
<div class="input-field col s6">
<input id="update_last_name" name="lastname" type="text" class="validate">
<label for="last_name">Apellido</label>
</div>
</div>
<div class="row">
<div class="input-field col s6">
<input id="update_side" type="text" name="side" class="validate">
<label for="partido">Partido</label>
</div>
<div class="input-field col s6">
<input id="update_charge" type="text" name="charge" class="validate">
<label for="cargo">Cargo</label>
</div>
</div>
<div class="row">
<div class="input-field col s6">
<div class="file-field input-field no-margin-top">
<div class="btn light-blue darken-4">
<span>Animación</span>
<input type="file">
</div>
<div class="file-path-wrapper">
<input class="file-path validate" name="animation" type="text">
</div>
</div>
</div>
<div class="input-field col s6">
<select id="update_section" name="section" autocomplete="off">
<option value="" disabled selected>Seleccione una opción</option>
<option value="1">Presidencia</option>
<option value="2">Senadores</option>
<option value="3">Diputados</option>
</select>
<label>Sección</label>
</div>
</div>
<input type="hidden" name="update_politic_hide" id="update_politic_hdn" value="">
</form>
Jquery
$("#update_politic_btn").click(function(event) {
/* Act on the event */
var chango = $("#update_form").serialize();
alert(chango);
$.post(baseurl + 'admin/update_politic', {
data: chango
},
function(data) {
console.log(data);
list_politic();
});
event.preventDefault();
});
Controller
public function update_politic(){
if ($this->input->is_ajax_request()) {
$params["name"] = $this->input->post("name");
$params["lastname"] = $this->input->post("lastname");
$params["side"] = $this->input->post("side");
$params["charge"] = $this->input->post("charge");
$params["animation"] = $this->input->post("animation");
$params["section"] = $this->input->post("section");
$params["id"] = $this->input->post("update_politic_hide");
if ($params["section"]=="Presidencia") {
$params["section"]=1;
}
if ($params["section"]=="Senadores") {
$params["section"]=2;
}
if ($params["section"]=="Diputados") {
$params["section"]=3;
}
$this->load->model("politic");
$this->politic->update($params);
}
}
MODEL
public function update($param){
$id = $param["id"];
$values = array(
"POLITIC_NAME" => $param["name"],
"POLITIC_LASTNAME" => $param["lastname"],
"POLITIC_SIDE" => $param["side"],
"POLITIC_CHARGE" => $param["charge"],
//"animation" => $param["animation"],
"SECTION_ID" => $param["section"],
);
$this->db->update("politics",$values);
$this->db->where("POLITIC_ID",$id);
}
HELP!!! I don't understan why i'm getting null values once I want print results!!
Your where condition should come first like,
public function update($param){
$id = $param["id"];
$values = array(
"POLITIC_NAME" => $param["name"],
"POLITIC_LASTNAME" => $param["lastname"],
"POLITIC_SIDE" => $param["side"],
"POLITIC_CHARGE" => $param["charge"],
//"animation" => $param["animation"],
"SECTION_ID" => $param["section"],
);
$this->db->where("POLITIC_ID",$id);
$this->db->update("politics",$values);
}
And show us your list_politic(); code if it is not working.
I think you are passing data in incorrect way if you are using serialize() then use it directly in $.post like,
$.post(baseurl + 'admin/update_politic',chango,function(data) {
console.log(data);
list_politic();
});

how can i capture multiple form inputs and save in an array

<template name="uploadTicket">
<div class="row">
<h3> Upload Ticket</h3>
<form class="ticket-form col s12" enctype="multipart/form-data">
<div class="row">
<div class="input-field col s12">
<input id="name" type="text" class="validate">
<label for="name">Event Name</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input id="location" type="text" class="validate">
<label for="location">Location</label>
</div>
</div>
<div class="row">
<div class="input-field col s4">
<input id="date" type="date" class="validate">
<label for="date"></label>
</div>
</div>
<div class="row">
<div class="input-field col s6">
<textarea id="description" class="materialize-textarea"></textarea>
<label for="Description">Description</label>
</div>
</div>
<div class="row">
<div class="col s6">
<h5>More Price Fields</h5>
</div>
<div class="col s6">
<a class="btn-floating btn-large waves-effect waves-light red" id="addField"><i class="mdi mdi-plus"></i></a>
</div>
</div>
<div class="wrapper">
<div class="row">
<div class="input-field col s4">
<input name="priceClass[]" type="text" class="validate">
<label for="priceClass[]">Class</label>
</div>
<div class="input-field col s4">
<input name="priceAmount[]" type="text" class="validate">
<label for="priceAmount[]">Price</label>
</div>
<div class="input-field col s4">
<h6>Input Price Classes and Amounts.</h6>
</div>
</div>
<br>
</div>
<br>
<div class="row">
<div >
<button class="waves-effect waves-light btn" type="submit">Upload</button>
</div>
</div>
</form>
</div>
</template>
This is my Template
Template.uploadTicket.events({
'click #addField': function (event) {
event.preventDefault();
var max_fields = 10;
var wrapper = $(".wrapper");
var add_button = $(".addField");
var x = 1;
if (x < max_fields)
{
x++; //text box increment
$(wrapper).append(' <div class="row"> <div class="input-field col s4"> <input name="priceClass[]" type="text" class="validate"> <label for="priceClass[]">Class</label> </div> <div class="input-field col s4"> <input name="priceAmount[]" type="text" class="validate"> <label for="priceAmount[]">Price</label> </div> <a class="btn-floating btn-large waves-effect waves-light red" id="removeField"><i class="mdi mdi-minus"></i></a></div> <br>'); //add input box
}
$(wrapper).on("click","#removeField", function(e)
{ //user click on remove text
e.preventDefault();
$(this).parent('div').remove();
x--;
})
}
});
This is my JavaScript for that template. I am giving the user option to add multiple fields so that they can have different classes for prices. Like gold class for a certain amount, VIP for another amount ,regular for another amount and so on. I am having a problem with how to get those input values when submitting the values and saving them into an array.
You would use jquery to loop through your inputs and send their values into an empty array. Then take the array with data and send it to your collection.
let valueStore = [];
console.log(valueStore) // an empty array
$('.input-field input').each(function(){
if (this.value != ''){
valueStore.push(this.value)
}
})
console.log(valueStore) // will have your values.
You can use JQuery-Selectors to get all Input Fields. You allready gave them a class. After that you can extract all necessary information into your array.
The JQuery-Selector should look something like:
$('.input-field')
Use a forEach loop to get every selected element.

Categories

Resources