I'm trying to send to the php backend a file and form data, but I'm not trying to succeed.
Could someone give a hint or even fix the sending part to the backend
HTML img
<div class='form-group is-empty col-md-6'>
<input style="display: none" type="file" (change)="onFileChanged($event)" #fileInput formControlName='arquivo_cifra'>
<div class="file-cifra" [style.background-image]="'url(' + img + ' )' | safeHtml: 'style' "></div>
<button (click)="fileInput.click()" style="width: 250px">Select File</button>
</div>
<div class='box-footer'>
<button (click)='save(form.value)' [disabled]='!form.valid' class='btn btn-primary'>Salvar</button>
</div>
component.ts
selectedFile: File;
img: any = 'assets/img/user_photo.png';
onFileChanged(event) {
var tmppath = URL.createObjectURL(event.target.files[0]);
this.img = tmppath;
this.selectedFile = event.target.files[0];
}
save(form) {
const uploadData = new FormData();
uploadData.append('myFile', this.selectedFile, this.selectedFile.name);
uploadData.append('form', form); //formBuilder
// this.form.value.arquivo_cifra = this.selectedFile;
// this.cifraService.saveFile(uploadData);
this.cifraService.save(uploadData)
}
service.ts
save(form) {
return this.http.post(`${BE_API}/cifra.php?acao=salvar`, form)
.subscribe((data) => {
if (data['success'] == 'ok') {
this.notify('Registro inserido com sucesso!');
this.router.navigate(['/cifra'])
}
console.log(data);
}, (error) => {
this.notify(`Error: ${error}`);
});
}
backend php
the file its work but form builder not.
public function incluir($ar) {
var_dump($_FILES);
var_dump($_REQUEST);
$dados = $this->dados($ar);
die();
$cd = self::insert($this->table, $dados);
if($cd>0){
self::commit();
}
}
return console
Related
I want to insert in 2 tables of mysql, one table is about information of a product and the other one is for the images of those products.
I have this form
<form action="#" method="post" enctype="multipart/form-data" id="upload-multi-images">
<div class="form-group">
<label>Name</label>
<input type="text" name="name" class="form-control" required autocomplete="off">
</div>
<div class="form-group">
<label>Price</label>
<input type="text" name="price" class="form-control" required autocomplete="off">
</div>
<div class="form-group">
<label>Stock</label>
<input type="text" name="stock" class="form-control" required autocomplete="off">
</div>
<div class="row">
<div class="col-xl-2 col-lg-2 col-md-3 col-sm-4 col-xs-12" id="add-photo-container">
<div class="add-new-photo first" id="add-photo">
<span><i class="icon-camera"></i></span>
</div>
<input type="file" multiple id="add-new-photo">
</div>
</div>
<div class="button-container">
<button type="submit">Subir imágenes</button>
</div>
</form>
I get the images and the information with this JS
$(document).on("submit", "#upload-multi-images", function (e) {
e.preventDefault();
$(document).on("submit", "#upload-multi-images", function (e) {
var namePro = document.getElementsByName('name')[0].value;
var price = document.getElementsByName('price')[0].value;
var stock = document.getElementsByName('stock')[0].value;
formData.append('namePro', namePro);
formData.append('price', price);
formData.append('stock', stock);
e.preventDefault();
//Envio mediante Ajax
$.ajax({
url: "upload.php",
type: "post",
dataType: "json",
data: formData,
cache: false,
contentType: false,
processData: false,
beforeSend: function () {
loading(true, "Adding photo...");
},
success: function (res) {
loading(false);
if (res.status == "true") {
createImages(res.all_ids);
$("#Images form .row > div:not(#add-photo-container)").remove();
formData = new FormData();
} else {
alert(res.error);
}
},
error: function (e) {
console.log(e.responseText);
}
});
});
Then y send the images to this php to send them to mysql
$namePRO = $_REQUEST['namePro'];
$price = $_REQUEST['price'];
$stock = $_REQUEST['stock'];
$insertDatos = $conexion->prepare("INSERT INTO products (name , price, stock) VALUES (:name, :price, :stock)");
$wasUploadedDATA = $insertDatos->execute(array(
":name" => $namePRO,
":price" => $price,
":stock" => $stock,
));
$idPRO = $conexion->lastInsertId();
if (isset($_FILES) && !empty($_FILES)) {
$files = array_filter($_FILES, function($item) {
return $item["name"][0] != "";
});
foreach ($files as $file) {
$tmp_name = $file["tmp_name"];
$name = $file["name"];
$path = "/images/$name";
$pathSYS = "/var/www/html/images/$name";
$insertImages = $conexion->prepare("INSERT INTO product_files (id_pro, name, web_path, system_path) VALUES (:idPRO, :name, :path, :pathSYS)");
$wasUploaded = $insertImages->execute(array(
":name" => $name,
":idPRO" => $idPRO,
":path" => $path,
":pathSYS" => $pathSYS,
));
if ($wasUploaded) {
$id = $conexion->lastInsertId();
$data["all_ids"]["id_$id"]["id"] = $id;
$data["all_ids"]["id_$id"]["name"] = $name;
move_uploaded_file($tmp_name, "images/$name");
}
else {
die("There was an error. Please contact with the admin.");
}
}
}
I also have these other JS but I think they are not very important
function getRandomString(length) {
var text = "";
var possible =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < length; i++)
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
function createPreview(file, id) {
var imgCodified = URL.createObjectURL(file);
var img = $('<div class="col-xl-2 col-lg-2 col-md-3 col-sm-4 col-xs-12"
id="'
+ id + '"><div class="image-container"> <figure> <img src="' + imgCodified +
'" alt="Foto del usuario"> <figcaption> <i class="icon-cross"></i>
</figcaption> </figure> </div></div>');
$(img).insertBefore("#add-photo-container");
}
function createImages(all_ids) {
for (const key in all_ids) {
var image = all_ids[key];
var img = $('<div class="col-xl-2 col-lg-2 col-md-3 col-sm-4 col-xs-12"
data-id="' + image.id + '"><div class="image-container"> <figure> <img
src="images/' + image.name + '" alt="Foto del usuario"> <figcaption> <i
class="icon-cross"></i> </figcaption> </figure> </div></div>');
$("#my-images").append(img);
}
}
function showModal(card) {
$("#" + card).show();
$(".modal").addClass("show");
}
function closeModal() {
$(".modal").removeClass("show");
setTimeout(function () {
$(".modal .modal-card").hide();
}, 300);
}
function loading(status, tag) {
if (status) {
$("#loading .tag").text(tag);
showModal("loading");
}
else {
closeModal();
}
}
function showMessage(message) {
$("#Message .tag").text(message);
showModal("Message");
}
I don't have all of your code, but I've identified the issue in your code and I'll just add add the fix here for you.
First of all, if you are using jquery, it's better to write your code in a unified format and use jquery everywhere and not switch between jquery and plain JavaScript.
Having that said, instead of using document.getElementsByName you can easily add id attribute to your html element and access them with $('#<id>') way in jquery.
Second, even if you are using javascript to grab your html element data, what you are doing is wrong. var namePro = document.getElementsByName('name'); will select the whole html <input> object and not it's value. So you have to change it to: document.getElementsByName("name")[0].value
So you have 2 options:
1- Use what you have already and just change it a bit to:
var namePro = document.getElementsByName('name')[0].value;
var price = document.getElementsByName('price')[0].value;
var stock = document.getElementsByName('stock')[0].value;
2- Or for switching to jquery, you need to add id to all of these elements in your html:
<div class="form-group">
<label>Name</label>
<input type="text" id="name" name="name" class="form-control" required autocomplete="off">
</div>
<div class="form-group">
<label>Price</label>
<input type="text" id="price" name="price" class="form-control" required autocomplete="off">
</div>
<div class="form-group">
<label>Stock</label>
<input type="text" id="stock" name="stock" class="form-control" required autocomplete="off">
</div>
And then change you JavaScript to:
formData.append('name', $('#name').val());
formData.append('price', $('#price').val());
formData.append('stock', $('#stock').val());
Update:
The sample code which works on my machine is like this:
HTML:
<form action="#" method="post" enctype="multipart/form-data" id="upload-multi-images">
<div class="form-group">
<label>Name</label>
<input type="text" name="name" class="form-control" required autocomplete="off">
</div>
<div class="form-group">
<label>Price</label>
<input type="text" name="price" class="form-control" required autocomplete="off">
</div>
<div class="form-group">
<label>Stock</label>
<input type="text" name="stock" class="form-control" required autocomplete="off">
</div>
<div class="row">
<div class="col-xl-2 col-lg-2 col-md-3 col-sm-4 col-xs-12" id="add-photo-container">
<div class="add-new-photo first" id="add-photo">
<span><i class="icon-camera"></i></span>
</div>
<input type="file" multiple id="add-new-photo">
</div>
</div>
<div class="button-container">
<button type="submit">Subir imágenes</button>
</div>
</form>
JS #1:
var formData = new FormData();
$(document).ready(function(){
$(".modal").on("click", function (e) {
console.log(e);
if (($(e.target).hasClass("modal-main") || $(e.target).hasClass("close-modal")) && $("#loading").css("display") == "none") {
closeModal();
}
});
$(document).on("click", "#add-photo", function(){
$("#add-new-photo").click();
});
$(document).on("change", "#add-new-photo", function () {
var files = this.files;
var element;
var supportedImages = ["image/jpeg", "image/png", "image/gif"];
var InvalidElementFound = false;
for (var i = 0; i < files.length; i++) {
element = files[i];
if (supportedImages.indexOf(element.type) != -1) {
var id = getRandomString(7);
createPreview(element, id);
formData.append(id, element);
}
else {
InvalidElementFound = true;
}
}
if (InvalidElementFound) {
showMessage("Invalid Elements Found.");
}
else {
showMessage("All the files were uploaded succesfully.");
}
});
$(document).on("click", "#Images .image-container", function(e){
var parent = $(this).parent();
var id = $(parent).attr("id");
formData.delete(id);
$(parent).remove();
});
$(document).on("submit", "#upload-multi-images", function (e) {
e.preventDefault();
var namePro = document.getElementsByName('name')[0].value;
var price = document.getElementsByName('price')[0].value;
var stock = document.getElementsByName('stock')[0].value;
formData.append('namePro', namePro);
formData.append('price', price);
formData.append('stock', stock);
//Envio mediante Ajax
$.ajax({
url: "upload.php",
type: "post",
dataType: "json",
data: formData,
cache: false,
contentType: false,
processData: false,
beforeSend: function () {
loading(true, "Adding photo...");
},
success: function (res) {
console.log('success');
console.log(res);
loading(false);
if (res.status == "true") {
createImages(res.all_ids);
$("#Images form .row > div:not(#add-photo-container)").remove();
formData = new FormData();
} else {
alert(res.error);
}
},
error: function (e) {
console.log('error');
console.log(e.responseText);
}
});
});
$(document).on("click", "#MyImages .image-container", function (e) {
var parent = $(this).parent();
var id = $(parent).attr("data-id");
var data = {
id : id
}
$.post("delete.php", data, function(res) {
if (res == "true") {
showMessage("¡Images successfully removed!");
$(parent).remove();
}
else {
showMessage("Sorry, there was an error uploading the images.");
}
});
});
});
JS #2:
function getRandomString(length) {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < length; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
}
function createPreview(file, id) {
var imgCodified = URL.createObjectURL(file);
var img = $('<div class="col-xl-2 col-lg-2 col-md-3 col-sm-4 col-xs-12" id="'+ id + '"><div class="image-container"> <figure> <img src="' + imgCodified + '" alt="Foto del usuario"> <figcaption> <i class="icon-cross"></i></figcaption> </figure> </div></div>');
$(img).insertBefore("#add-photo-container");
}
function createImages(all_ids) {
for (const key in all_ids) {
var image = all_ids[key];
var img = $('<div class="col-xl-2 col-lg-2 col-md-3 col-sm-4 col-xs-12" data-id="' + image.id + '"><div class="image-container"> <figure> <img src="images/' + image.name + '" alt="Foto del usuario"> <figcaption> <i class="icon-cross"></i> </figcaption> </figure> </div></div>');
$("#my-images").append(img);
}
}
function showModal(card) {
$("#" + card).show();
$(".modal").addClass("show");
}
function closeModal() {
$(".modal").removeClass("show");
setTimeout(function () {
$(".modal .modal-card").hide();
}, 300);
}
function loading(status, tag) {
if (status) {
$("#loading .tag").text(tag);
showModal("loading");
}
else {
closeModal();
}
}
function showMessage(message) {
$("#Message .tag").text(message);
showModal("Message");
}
PHP: (upload.php)
$arr_ajax = array();
$arr_ajax['namePro'] = $_REQUEST['namePro'];
$arr_ajax['price'] = $_REQUEST['price'];
$arr_ajax['stock'] = $_REQUEST['stock'];
if (isset($_FILES) && !empty($_FILES)) {
$files = array_filter($_FILES, function($item) {
return $item["name"][0] != "";
});
$iCnt = 0;
foreach ($files as $file) {
$arr_ajax['Filename'.$iCnt] = $file["name"];
$iCnt++;
}
}
echo json_encode($arr_ajax);
And with this code, when I click on Submit button, I get the following response in my browser console:
index.html:79 success
index.html:80 {namePro: "Test Product", price: "100.00", stock: "15", Filename0: "faces1.jpg"}
I'm trying to passing, through HTML form, a MediaRecorder file but it doesn't work. The code is the following:
This is the code which record the audio
function hasGetUserMedia() {
return !!( navigator.mediaDevices && navigator.mediaDevices.getUserMedia );
}
function audioPlay(){
if ( hasGetUserMedia() ) {
audioRunner();
}else{
console.log('UserMedia not supported');
}
}
function audioRunner(){
var audio = document.getElementById('audio');
let audioButtons = {
start: document.getElementById('audio_recorder'),
stop: document.getElementById('audio_stop'),
}
let boxAudio = {
input: document.getElementById('input_audio')
}
let chunks = [];
let constraintObj = {
audio: true
}
if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia(constraintObj).then(function(stream) {
let mediaRecorder = new MediaRecorder(stream);
//BUTTONS
audioButtons.start.addEventListener('click', (ev) => {
mediaRecorder.start();
startAnimation();
console.log(mediaRecorder.state);
});
audioButtons.stop.addEventListener('click', (ev) => {
mediaRecorder.stop();
stopAnimation();
console.log(mediaRecorder.state);
})
mediaRecorder.ondataavailable = function(ev){
chunks.push(ev.data);
}
mediaRecorder.onstop = (ev) => {
let blob = new Blob(chunks, { 'type' : 'audio/mpeg-3' });
let videoURL = window.URL.createObjectURL(blob);
audio.src = videoURL;
audio.style.display = 'block';
fr = new FormData();
fr.append('blob', videoURL);
boxAudio.input.value = fr;
console.log(fr);
chunks = [];
}
<form enctype="multipart/form-data" action="views/send_message_form.php" method="post">
<div class="card bg-light message_ctn" id="audio_message_ctn">
<div class="card-header">Header</div>
<div class="card-body">
<div id="microphone-icon">
<span data-color="red"><i class="fas fa-microphone-alt"></i></span>
</div>
<audio id="audio" controls></audio>
<input type="text" name="audio_message" id="input_audio">
<div id="audio_buttons" class="box_buttons">
<button type="button" id="audio_recorder" class="btn btn-outline-primary">Registra</button>
<button type="button" id="audio_stop" class="btn btn-outline-info">Stop</button>
<button type="submit" id="audio_send" class="btn btn-outline-success">Invia</button>
</div>
</div>
</div>
</form>
and this is the code PHP that receives the data by form
var_dump($_POST);
?>
<video src="<?=$_POST['audio_message'] ?>"></video>
When I submit the form the variable $_POST is empty, How can I pass the video to send_message_form.php and then save it into htdocs sub-folder?
An input field is being generated by ng-repeat. The input tag includes ng-model and ng-blur. The ng-blur action is not triggered and the console doesn't show any errors.
The HTML is generated by a Zend Framework 3 app. I'm using angularjs 1.7.8 and jquery 3.1.0.
Here is the body of the web page
<body ng-app='byDomainApp' ng-controller='ByDomainCtrl'>
<center>
<h2>Maintenance By Domain</h2>
</center>
<p>You may edit/correct any of the following details. Note that an
update will be ignored if the email address is changed to one that has
been tried previously.</p>
<div class='row'>
<div class='col-xs-3'>
Choose a domain: <select class='form-control' ng-model="myDomain"
ng-change="domainUsers(myDomain)"
ng-options="domain.domain_name for domain in domains track by domain.domain_id"></select>
<p ng-hide 'message=null' >
<br> <br>{{message}}
</p>
</div>
</div>
<div class='row'>
<div class='col-xs-2'>Name</div>
<div class='col-xs-2'>Email</div>
<div class='col-xs-2'>Company</div>
<div class='col-xs-2'>Job title</div>
<div class='col-xs-2'>Country</div>
<div class='col-xs-2'>Confirmed?</div>
</div>
<div ng-repeat="user in users" class='row'>
<div class='col-xs-2'>
<input ng-model="user.user_name" ng-blur="updateUser(user)">
</div>
<div class='col-xs-2'>{{user.user_email}}</div>
<div class='col-xs-2'>{{user.user_company}}</div>
<div class='col-xs-2'>{{user.user_jobtitle}}</div>
<div class='col-xs-2'>{{user.user_country}}</div>
<div class='col-xs-2'>{{user.user_confirmed}}</div>
</div>
The Javascript angular code
angular.module('byListApp', []).constant("listUrl",
"http://elms2.com/list-rest").constant("userUrl",
"http://elms2.com/user-rest").controller(
"ByListCtrl",
function($scope, $http, listUrl, userUrl) {
$scope.hide = true;
$scope.showMessage = false;
$http.get(listUrl + '/' + ownerId).then(function(response) {
$scope.lists = response.data;
}, function(error) {
$scope.error = error;
alert(error);
});
$scope.listUsers = function(list) {
$scope.message = '';
$scope.hide = true;
$scope.showMessage = false;
// $scope.booksFound[0].message = '';
$http.get(userUrl + '/byList:' + list.list_id).then(
function(response) {
$scope.users = response.data;
});
};
});
angular.module('byDomainApp', []).constant("domainUrl",
"http://elms2.com/domain-rest").constant("userUrl",
"http://elms2.com/user-rest").controller(
"ByDomainCtrl",
function($scope, $http, domainUrl, userUrl) {
$scope.hide = true;
$scope.showMessage = false;
$http.get(domainUrl).then(function(response) {
$scope.domains = response.data;
}, function(error) {
$scope.error = error;
alert(error);
});
$scope.domainUsers = function(domain) {
$scope.message = '';
$scope.hide = true;
$scope.showMessage = false;
$http.get(userUrl + '/byDomain:' + domain.domain_id).then(
function(response) {
$scope.users = response.data;
}, function(error) {
$scope.error = error;
alert(error);
});
};
$scope.updateUser = function(user) {
$http.get(userUrl + '/updateUser:' + user).then(
function(response) {
$scope.userData = response.data;
}, function(error) {
$scope.error = error;
alert(error);
});
};
});
The list of domains is generated correctly and the ng-repeat fills with the correct data when a domain is selected. However nothing happens when the input field contents are edited and then loses focus. I can prove that by deleting the updateUser function from the angular code or replacing the ng-blur action with an alert or similar.
This is now working and I can't explain why as nothing has changed.
I've been searching a lot about that and every post has the same answer: load library, config and then ->do_upload('file'). Seems to solve everyone's problem but mine.
I'm using ajax with FormData to send my file (a pdf) and after I post it, it can be seen using $_FILE yet can't get it thru ->do_upload.
views/home.php
<body>
<?php echo form_open_multipart('formulario/questionario');?>
...
<div class="col-md-6">
<label class="btn btn-secondary" for="input-c-civis">
<input id="input-c-civis" type="file" style="display:none;" accept=".pdf">Selecionar contrato
</label>
</div>
<div class="col-md-6">
<label class="btn btn-secondary" for="input-c-art-civis">
<input id="input-c-art-civis" type="file" style="display:none;" accept=".pdf"> Selecionar contrato
</label>
</div>
<div class="container justify-content-center">
<button id="botao-submit" class="btn btn-primary" type="button">Send</button>
</div>
/assets/js/script.js
$(document).ready(function() {
$("#botao-submit").click(function() {
insertExtras();
});
});
// This method gets the value from home.php elements.
function extraFormData() {
var formData = new FormData();
var contratoPDF = $("#input-c-civis").prop('files')[0];
var artPDF = $("#input-c-art-civis").prop('files')[0];
formData.append("contratoPDF", contratoPDF);
formData.append("artPDF", artPDF);
return formData;
}
function insertExtras() {
$.ajax({
cache: false,
contentType: false,
processData: false,
type: 'POST',
url: 'index.php/formulario/questionario',
data: extraFormData()
}).done(function(msg) {
console.log(msg);
}).fail(function(error) {
console.error(error.responseText);
})
}
/controllers/formulario.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Formulario extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->model('Extras_model', 'questionario');
$this->load->helper(array(
'form',
'url'
));
}
public function index() {
$this->load->view('home');
}
public function questionario() {
$config['upload_path'] = './uploads/contratos/';
$config['allowed_types'] = 'pdf';
$config['max_size'] = 50000;
$this->load->library('upload', $config);
if (!$this->upload->do_upload('contratoPDF')) {
$error = $this->upload->display_errors();
print_r($error);
} else {
$data = array(
'upload_data' => $this->upload->data()
);
echo $data;
}
var_dump($_FILES['contratoPDF']);
var_dump($_FILES['artPDF']);
}
}
?>
So after sending the files with ajax I get:
from: $this->upload->display_errors(); : You did not select a file to upload.
but from var_dump($_FILES['contratoPDF']); and var_dump($_FILES['artPDF']); shows both arrays with files's informations.
Sorry for the wall of codes and misspelling, I tried to be as explicit as possible.
Replace extraFormData() as following:
function extraFormData() {
var formData = new FormData();
var contratoPDF = $("#input-c-civis")[0].files[0];
var artPDF = $("#input-c-art-civis")[0].files[0];
formData.append("contratoPDF", contratoPDF);
formData.append("artPDF", artPDF);
return formData;
}
In laravel, I'm trying to update several tables and rows. i have items that are to be received and checked by 2 different users.
in my show.blade.php, i have this verify button and submit button depending on the user.
#if (($current_user_id != $saved_receiver_id) && ($saved_receiver_id != $not_yet_received))
<div class="row padder m-b">
<div class="col-md-12">
<label for="received_by" class="pull-left" >Received by:</label> <span class="fa"></span>
<input type="hidden" name="receiver_id" value="{{ $saved_receiver_id }}" >{{ $receiver_username }}</input>
</div>
</div>
<div class="row padder m-b">
<div class="col-md-12">
<label for="received_date" class="pull-left" >Received date:</label> <span class="fa"></span>
<input type="hidden" name="received_date" value="{{ $received_date }}" >{{ $received_date }}</input>
</div>
</div>
<input type="hidden" name="purchase_orders_id" value="{{ $purchase_order_number }}">
<input type="hidden" name="checker_id" value="{{ $current_user_id }}">
<div class="row padder m-b">
<div class="col-md-12">
<label for="final_checker_remarks" class="pull-left" >Final Remarks</label>
<textarea class="form-control col-md-12" name="final_checker_remarks" value="{{ $final_checker_remarks }}" id="final_checker_remarks">{{ $final_checker_remarks }}</textarea>
</div>
</div>
<br />
<div class="row">
<div class="col-md-12">
<button type="button" class="pull-right btn btn-success btn-sm submit-btn" id="update-form-submit" data-action="verified">Verified</button>
</div>
</div>
#else
<div class="pull-right">
<div class="btn-group">
<button type="button" class="btn btn-info btn-sm submit-btn" id="update-form-submit" data-action="submit">Submit List</button>
</a>
</div>
#endif
now in my ReceivesController.php, i have this postUpdate function,
public function postUpdate(Request $request)
{
if (! $request->ajax()) {
abort(404);
}
$items = json_decode($request->items);
$action = json_decode($request->action);
if(!count($items) && !count($items->purchase_item_id)){
return false;
}
$cnt = count($items->purchase_item_id);
// Receiver Submit function
if ($action == "submit") {
// Saves the received id of the one who received to purchase order table
DB::table('purchase_orders')
->where('id', $items->purchase_orders_id)
->update([
'receiver_id' => $items->receiver_id,
]);
// Saves the quantity received and receiver remarks to purchase items table
for($i=0; $i<$cnt; $i++){
DB::table('purchase_items')
->where('id', $items->purchase_item_id[$i])
->update([
'quantity_received' => $items->quantity_received[$i],
'receiver_remarks' => $items->receiver_remarks[$i],
]);
}
// Items Received Success Message
$message = 'Items Received';
}
// QA or Checker Finalize function
else {
// Saves the checker id, and final checker remarks of the one who made the QA to purchase order table
DB::table('purchase_orders')
->where('id', $items->purchase_orders_id)
->update([
'checker_id' => $items->checker_id,
'final_checker_remarks' => $items->final_checker_remarks,
]);
// Saves the quality received and checker remarks to purchase items table
for($i=0; $i<$cnt; $i++){
$quality_received = $items->quality_received;
if(is_array($items->quality_received)){
$quality_received = $items->quality_received[$i];
}
$checker_remarks = $items->checker_remarks;
if(is_array($items->checker_remarks)){
$checker_remarks = $items->checker_remarks[$i];
}
$quantity_received = $items->quantity_received;
if(is_array($items->quantity_received)){
$quantity_received = $items->quantity_received[$i];
}
$receiver_remarks = $items->receiver_remarks;
if(is_array($items->receiver_remarks)){
$receiver_remarks = $items->receiver_remarks[$i];
}
DB::table('purchase_items')
->where('id', $items->purchase_item_id[$i])
->update([
'quality_received' => $quality_received,
'checker_remarks' => $checker_remarks,
'quantity_received' => $quantity_received,
'receiver_remarks' => $receiver_remarks,
]);
// Increments or Adds the quantity received to items table
DB::table('items')
->where('purchase_items.id', $items->purchase_item_id[$i])
->join('purchase_items', 'items.id', '=', 'purchase_items.item_id')
->increment('items.measurement', $items->quantity_received[$i]);
}
/ / Items Finalized Success Message
$message = 'Items Verified';
}
// Returns Success Message
return response()->json([
'success' => true,
'message' => $message
]);
}
Now my problem is only the first letter of the word that is typed in the input area are being saved, and in others they are not saved, however, in other, it can be saved. I know its weird, but i cant find which part of my codes is doing such result, what is it that i need to do for me to update my tables correctly? Thanks in advance for the help.
Update: Here is my receive-form-function.js
/* ========================================================================
* Initialize Pages
* ======================================================================== */
$(initialPages);
/* ========================================================================
* Major function
* ======================================================================== */
/* ==== function to init this page === */
function initialPages($) {
// if($('#receives-list-table').length){
// DataTables("#receives-list-table", "receives");
// }
if($('#receiveItems-list-table').length){
$("#receiveItems-list-table").DataTable({
responsive: true,
ordering: false,
});
}
$('#update-form-submit').on('click', function(){
var action = $(this).data('action');
updateReceiveItem(action);
});
clearInputs();
}
/* === dataTables === */
function DataTables(selector, controller) {
$(selector).DataTable({
responsive: true,
processing: true,
serverSide: true,
ajax: url+'/'+controller+'/paginate'
});
}
function updateReceiveItem(action){
loadingModal('show','Updating ....');
ajaxCsrfToken();
var data = $('#receiveItems_id').serializeArray();
data = JSON.stringify(data);
// data = JSON.parse(data);
data = JSON.stringify($('#receiveItems_id').serializeObject());
// data = $('#receiveItems_id').serializeObject();
$.ajax({
url: url+'/receives/update',
type: 'post',
data: {'items':data, 'action': action},
dataType: 'json',
complete: function() {
loadingModal('close');
},
error: function(result) {
},
success: function(result) {
successAlert('#receiveItems-result', result.message);
// if (result.success) {
// $('input, select, textarea').attr('disabled', true);
// } else {
// alert(result.message);
// }
}
});
console.log(data);
return false;
}
/**
* Use to format serialize data and convert to json data
*
* Usage: JSON.stringify($('form').serializeObject())
*/
$.fn.serializeObject = function() {
var o = Object.create(null),
elementMapper = function(element) {
element.name = $.camelCase(element.name);
return element;
},
appendToResult = function(i, element) {
var node = o[element.name];
if ('undefined' != typeof node && node !== null) {
o[element.name] = node.push ? node.push(element.value) : [node, element.value];
} else {
o[element.name] = element.value;
}
};
$.each($.map(this.serializeArray(), elementMapper), appendToResult);
console.log(o);
return o;
};
my $.fn.serializeObject = function() above seems to have the bug, i tried using another $.fn.serializeObject = function(), and it gave me the json object that i want. here is the $.fn.serializeObject = function() that i am using now.
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};