I want letting user add dynamic inputs and save those values in the database. But with this code only one value save to the database. How can I save all values to the database entered by user
this is my view to add dynamic inputs
<script type="text/javascript">
$(document).ready(function() {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('</br><div><input class="input form-control"" name="mytext[]"/>Remove</div>'); //add input box
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
</script>
<div class="input_fields_wrap">
<div class="form-group">
<button type="button" class="btn btn-success add_field_button">Add More Fields</button>
</div>
<div>
<input class="input form-control" name="mytext[]">
</div>
</div>
This is my controller to save those dynamic inputs in the database
function error(){
if ($this->input->post('mytext')) {
$attain = $this->input->post('mytext', true);
foreach ($attain as $i => $a) { // need index to match other properties
$data2 = array(
'mytext' => $a,
'projectname' => $this->input->post('projectname'),
);
$this->db->insert('projectem', $data2);
redirect('Select_ctrl2/ModalAddEmployeesProject');
}
}
}
function error(){
if ($this->input->post('mytext')) {
$attain = $this->input->post('mytext', true);
$data2=array(); //<-initialize
foreach ($attain as $i => $a) { // need index to match other properties
//append array
$data2[] = array(
'mytext' => $a,
'projectname'=> $this->input->post('projectname'),
);
//for multiple entry in same table
$this->db->insert_batch('projectem', $data2);
redirect('Select_ctrl2/ModalAddEmployeesProject');
}
}
}
Related
Hi everyone I need your help on how to split value from textarea and insert in a users table using laravel, I was able to get file content = "name | username | password", I need to split each value so I ca save it to a users table the file itself is save in a different table, should I put it in a different method or just specify my target table in the same as the file will be saved? Your help will be much appreciated.
UploadController:
public function store(Request $request){
$validator = Validator::make(
$request->all(),
['filename' => 'required|mimes:txt,jpeg,png,jpg,bmp|max:2048']
);
if ($validator->fails()) {
return back()->withErrors($validator->errors());
}
// if validation success
if ($file = $request->file('filename')) {
$filename = 'uploaded-here.' . $file->getClientOriginalExtension();
//stored in laravel local storage
$target_path = $file->storeAs('uploaded-here/', $filename);
if ($file->move($target_path, $filename)) {
// save file name in the database
$file = File::create(['filename' => $filename]);
return back()->with("success", "File uploaded successfully");
}
}
}
html code:
<div class="form-group" {{ $errors->has('filename') ? 'has-error' : '' }}>
<label for="filename"></label>
<input type="file" name="filename" id="filename" class="form-control">
<span class="text-danger"> {{ $errors->first('filename') }}</span>
<textarea id="editor" name="editor></textarea>
</div>
<button type="submit" class="btn btn-success btn-md"> Upload </button>
js
window.onload = function() {
var doc = document.getElementById('filename');
if (doc) {
doc.addEventListener('change', getFile);
}
}
function getFile(event) {
const input = event.target
if ('files' in input && input.files.length > 0) {
placeFileContent(
document.getElementById('editor'),
input.files[0])
}
}
function placeFileContent(target, file) {
readFileContent(file).then(content => {
target.value = content
}).catch(error => console.log(error))
}
function readFileContent(file) {
const reader = new FileReader()
return new Promise((resolve, reject) => {
reader.onload = event => resolve(event.target.result)
reader.onerror = error => reject(error)
reader.readAsText(file)
})
}
There is an error. Quotation closed sign is missing in name attribute of textarea.
<textarea id="editor" name="editor"></textarea>
You can split using JavaScipt's split() method. Like follwoing:
Say, you have the textarea value as your given format: name | email | password
as you have given example: example errol | errol.boneo13#gmail.com | password123.
Let's say, you have get the textarea value,
var textValue = document.getElementById('editor').value;
textValue = textValue .split(" | ");
var name = textValue [0];
var email = textValue [1];
var password = textValue [2];
Hope it helps....
EDIT::
As you wanted to do in laravel, you can do like following:
$textValue = $request->editor;
$textValue = explode(" | ", $textValue );
$name = $textValue [0];
$email = $textValue [1];
$password = $textValue [2];
Hi I successfully designed a chat message system between users and it works fine. The only problem I am having at this point is polling data from chat table to browser real time.
The messages are displayed using ajax and the setInterval works as I checked the console. The issue is that it does not capture new entries to the table for display and hence the user has to keep refreshing the page to see new content.
Please help. My code is below. Please forgive my file naming convention as I will change it later on.
PS this is developed using codeigniter framework.
**Chats.php - Controller**
public function ajax_get_chat_messages(){
echo $this->_get_chat_messages();
}
function _get_chat_messages($recipient = null)
{
$user_id = $this->session->userdata('user_id');
$recipient = $this->input->post('recipient');
$data['recipient'] = $this->User_model->get_users($user_id);
$data['chats_count'] = $this->Chats_model->get_chat_messages_count($recipient);
$content = $this->Chats_model->get_chat_messages_count($recipient);
$data['chats'] = $this->Chats_model->get_chat_messages($user_id);
$result = array('status' =>'ok', 'content'=>$content);
return json_encode($result);
}
**Model - Chats_model.php**
public function get_chat_messages_count($recipient = null){
$session = $this->session->userdata('user_id');
$this->db->select('*');
$this->db->from('chat_messages');
$this->db->join('users', 'users.user_id = chat_messages.user_id');
$this->db->where(array('chat_messages.user_id' => $session));
$this->db->where(array('chat_messages.recipient' => $recipient));
$this->db->or_where(array('chat_messages.user_id' => $recipient));
$this->db->where(array('chat_messages.recipient' => $session));
$this->db->where_in(array('chat_messages.chat_id' => $session , $recipient));
$query = $this->db->get();
return $query->result_array();
}
**View - chats_view.php**
<script type="text/javascript">
var user = "<div class='timeline-item' id='view'><ul><?php foreach($chats_count as $chat){echo '<li>'; echo $chat['username']; echo '</li>'; }?></ul></div>";
</script>
<div class="wrapper wrapper-content">
<div class="row animated fadeInRight">
<div class="col-lg-12">
<div class="ibox float-e-margins">
<div class="ibox-title">
<h5>Chat</h5>
<div class="ibox-tools" >
</div>
</div>
<div class="ibox-content inspinia-timeline" id="view1" >
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
**JS - chat2.js**
$(document).ready(function(){
setInterval(function() { get_chat_messages(); }, 2500)
$("input#chat_message").keypress(function(e){
if(e.which == 13){
$("a#submit_message").click();
return false;
}
});
function get_chat_messages(){
$.post(base_url +"user/chats/ajax_get_chat_messages",{user: user}, function(data) {
if(data)
{
var current_content = $("#view1").html();
$("#view1").html(user);
console.log(user);
}
else
{
}, "json");
}
get_chat_messages();
});
Images attached showing the table structure, the chat page on browser and console data.
[Chat page on browser, only showing username for testing purposes][1]
[Chat Table][2]
[Console Data, only showing username for testing purposes][3]
have a form like this. This is an update form, i just need to update qty foreach product in cart.
But i have tried to explode each results and not work... it return object2array conversion error... its the first time that i get this error How i can save this in DB?
<form action="update">
#foreach($products as $product)
<input type="text" name="products[]">
<input type="text" name="qty[]">
#endforeach
<input type="submit" calss="btn btn-primary">
This is my controller:
Route::post('aggiorna', function() {
$quantita = Input::all();
$carrelli = \App\Models\Carrello::where('entry_by', \Session::get('uid'))->get();
$quantita = explode(',', $quantita);
$i = 0;
foreach($carrelli as $carrello) {
$carrello->quantita = $quantita[$i];
$i = $i++;
}
return Redirect::to('carrello');
});
Thanks in advance.
you do the iteration for each $carreli that exist on your database, however you never save the value.
Route::post('aggiorna', function() {
$quantita = Input::all();
$carrelli = \App\Models\Carrello::where('entry_by', \Session::get('uid'))->get();
$quantita = explode(',', $quantita);
$i = 0;
foreach($carrelli as $carrello) {
$carrello->quantita = $quantita[$i];
$i = $i++;
$carrelo->save();
}
return Redirect::to('carrello');
});
add the $carrelo->save(); after you update the value in order to save it on db.
Also careful when you use Input::all();. That means that your data array contains both products and quantities. I would suggest using the following code:
Route::post('aggiorna', function() {
$quantita = Input::get('qty');
$products = Input::get('products');
$carrelli = \App\Models\Carrello::where('entry_by', \Session::get('uid'))->get();
$quantita = explode(',', $quantita);
$products = explode(',', $products);
$i = 0;
foreach($carrelli as $carrello) {
$carrello->quantita = $quantita[$i];
$carrello->products = $products[$i];
$i = $i++;
$carrelo->save();
}
return Redirect::to('carrello');
});
However since i do not know what you are trying to achieve, I posted both solutions here.
My website is built using Codeigniter, and there's an area for users to modify their information. This area allows users to choose a profile picture, and when editing it, the selected picture is previewed. In case they don't choose a new one, there's a hidden field storing its name, which is passed to the controller to specify the same image name, but if the user decides to change it, the new name is passed to the controller.
public function edit($id)
{
$this->input->post('tipo_usuario') === 'F' ? $validator = 'editar_pessoa_fisica' : $validator = 'editar_pessoa_juridica';
if ($this->form_validation->run($validator)) {
$data = array();
$data['nome_razao_social'] = $this->input->post('nome_razao_social');
$data['nome_responsavel'] = $this->input->post('nome_responsavel');
$data['nome_fantasia'] = $this->input->post('nome_fantasia');
$data['cpf_cnpj'] = $this->input->post('cpf_cnpj');
$data['telefone'] = $this->input->post('telefone');
$data['telefone_2'] = $this->input->post('telefone_2');
$data['email'] = $this->input->post('email');
$data['novo_email'] = $this->input->post('novo_email');
$data['senha'] = md5($this->input->post('senha'));
$data['cep'] = $this->input->post('cep');
$data['logradouro'] = $this->input->post('logradouro');
$data['id_cidade'] = $this->input->post('id_cidade');
$data['id_estado'] = $this->input->post('id_estado');
$data['numero'] = $this->input->post('numero');
$data['complemento'] = $this->input->post('complemento');
$data['tipo_usuario'] = $this->input->post('tipo_usuario');
/*
HERE IS IN CASE THE USER DOES NOT CHANGE HIS PROFILE PICTURE
*/
$data['imagem'] = $this->input->post('imagem_old');
$data['url'] = $this->input->post('url');
// Nova senha?
if ($this->input->post('novasenha') !== '') {
$data['senha'] = md5($this->input->post('novasenha'));
} else {
$data['senha'] = $this->input->post('senha');
}
/*
HERE IS IN CASE THE USER CHANGES HIS PROFILE PICTURE
*/
// Nova imagem?
if ($_FILES['imagem']['name'] !== '') {
$data['imagem'] = $_FILES['imagem']['name'];
}
// Novo e-mail?
if ($this->input->post('email') !== $this->input->post('novoemail')) {
$data['novo_email'] = $this->input->post('novoemail');
$this->Usuarios_model->update($data, $id);
$this->Usuarios_model->send_confirmation_email($data['novo_email'], $data['email']);
}
if ($this->input->post('novo_novo_email') !== $this->input->post('novo_email')) {
$data['novo_email'] = $this->input->post('novo_novo_email');
$this->Usuarios_model->update($data, $id);
$this->Usuarios_model->send_confirmation_email($data['novo_email'], $data['email']);
}
if ($this->Usuarios_model->update($data, $id)) {
$this->upload->do_upload('imagem');
$this->session->set_flashdata('message', 'Dados alterados');
echo json_encode(array(
'redirect' => '/usuario/painel'
));
}
} else {
echo json_encode(array(
'type' => 'validation',
'message' => validation_errors(),
));
}
}
This is the HTML:
<form action="/auto/usuario/edit/<?php echo $id_usuario; ?>" method="POST" class="formulario" enctype="multipart/form-data">
<input type="hidden" name="tipo_usuario" value="F"/>
<div class="p100">
<span class="titulo">Foto de Perfil</span>
<div class="imagem_destaque img_perfil image-trigger">
<div class="file-upload-trigger">
<input type="file" name="imagem" class="none file-chooser"/>
<img src="/uploads/perfil/<?php echo $u['imagem'] ?>" class="preview more"/>
</div>
</div>
<input type="hidden" name="imagem_old" value="<?php echo $u['imagem']; ?>"/>
</div>
With Google Chrome, it works fine, but in Firefox 45, if I do not choose a new image, an error is thrown:
Severity: Notice
Message: Undefined index: imagem
Filename: controllers/Usuario.php
Line Number: 362
It only works locally.
If you do not upload a new image, your $_FILES[] is undefined, as the error says. To check if the user has changed his image you should do:
if ( isset($_FILES['imagem']['name']) ) {
$data['imagem'] = $_FILES['imagem']['name'];
}
I have ajax code that display the name of the cities(in selectbox) according the area that has been chosen:
<?PHP if ($_POST) { ?>
$(document).ready(function(){
$('#areaID').filter(function(){
var areaID=$('#areaID').val();
var cityID=<?PHP echo $cityID ?>;
$('#cityID').load('js/ajax/getCities.php?areaID=' + areaID+'&cityID=' + cityID);
return false;
});
});
<?PHP }else { ?>
$(function () {
function updateCitySelectBox() {
var areaID = $('#areaID').val();
$('#cityID').load('js/ajax/getCities.php?areaID=' + areaID);
return false;
}
updateCitySelectBox();
$('#areaID').change(updateCitySelectBox);
});
<?PHP } ?>
The problem is - after user submit the form and get error (i.e - forget to fill some field), user can change the area but the cities select box doesn't change according the new area.
What is wrong with the code?
<p><label>area</label>
<select name='areaID' id='areaID'>
<?PHP
$query = mysql_query("SELECT * FROM `areas` ORDER BY id ASC ");
while($index = mysql_fetch_array($query))
{
$db_area_id = $index['id'];
$db_area_name = $index['name'];
if ($db_area_id == $areaID)
echo "<option value='$db_area_id' selected>$db_area_name</option>";
else
echo "<option value='$db_area_id'>$db_area_name</option>";
}
?>
</select><span>*</span>
</p>
<p><label>City</label>
<select id='cityID' name='cityID'> </select>
</p>