i'm have confusing problem about uploading image in multiple input text like registration page. i found solution but the image is not save to database or folder.
please help me all...
my admin.php view
<script>
//upload img
$('#form').ajaxForm({
//uploadimg is my form id
dataType: 'json',
success: processJson
});
function processJson(data) {
if(data.msg=="success"){
alert('Upload sukses.');
}
else{
alert('Upload gagal.');
}
}
function add_edulibs()
{
save_method = 'add';
$('#form')[0].reset(); // reset form on modals
$('.form-group').removeClass('has-error'); // clear error class
$('.help-block').empty(); // clear error string
$('#modal_form').modal('show'); // show bootstrap modal
$('.modal-title').text('Tambah Data'); // Set Title to Bootstrap modal title
}
function edit_edulibs(id)
{
save_method = 'update';
$('#form')[0].reset(); // reset form on modals
$('.form-group').removeClass('has-error'); // clear error class
$('.help-block').empty(); // clear error string
//Ajax Load data from ajax
$.ajax({
url : "<?php echo site_url('edulibs/ajax_edit/')?>/" + id,
type: "GET",
dataType: "JSON",
success: function(data)
{
$('[name="id"]').val(data.id);
$('[name="nama"]').val(data.nama);
$('[name="nim"]').val(data.nim);
$('[name="pembimbing"]').val(data.pembimbing);
$('[name="subyek"]').val(data.subyek);
$('[name="judul"]').val(data.judul);
$('[name="tanggal"]').datepicker('update',data.tanggal);
$('[name="alamat"]').val(data.alamat);
$('[name="kontak"]').val(data.kontak);
$('[name="email"]').val(data.email);
$('[name="penerbit"]').val(data.penerbit);
$('[name="file_upload"]').val(data.gambar);
$('#modal_form').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('Edit Data'); // Set title to Bootstrap modal title
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error mendapatkan data');
}
});
}
</script>
<div class="modal fade" id="modal_form" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h3 class="modal-title">Kelola Data</h3>
</div>
<div class="modal-body form">
<form action="<?php echo base_url('edulibs/do_upload/')?>" method="post" enctype="multipart/form-data" id="form" class="form-horizontal">
<input type="hidden" value="" name="id"/>
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-3">Nama</label>
<div class="col-md-9">
<input name="nama" placeholder="Nama Lengkap" class="form-control" type="text">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">NIM</label>
<div class="col-md-9">
<input name="nim" placeholder="Nomor Induk Mahasiswa" class="form-control" type="text">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Pembimbing</label>
<div class="col-md-9">
<input name="pembimbing" placeholder="Nama Pembimbing" class="form-control" type="text">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Subyek</label>
<div class="col-md-9">
<input name="subyek" placeholder="Subyek" class="form-control" type="text">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Judul</label>
<div class="col-md-9">
<textarea name="judul" placeholder="Judul Karya Tulis" class="form-control"></textarea>
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Tanggal Terbit</label>
<div class="col-md-9">
<input name="tanggal" placeholder="Tahun-Bulan-Hari" class="form-control datepicker" type="text">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Alamat</label>
<div class="col-md-9">
<textarea name="alamat" placeholder="Alamat Lengkap" class="form-control"></textarea>
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Kontak</label>
<div class="col-md-9">
<input name="kontak" placeholder="Nomor Kontak" class="form-control" type="text">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Email</label>
<div class="col-md-9">
<input name="email" placeholder="Alamat e-mail" class="form-control" type="text">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Penerbit</label>
<div class="col-md-9">
<input name="penerbit" placeholder="Nama Penerbit" class="form-control" type="text">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Foto</label>
<div class="col-md-9">
<input type="file" name="file_upload" />
<span class="help-block"></span>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Simpan</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Batalkan</button>
</div>
My edulibs.php controller
public function admin()
{
$this->load->view('admin');
}
function do_upload(){
$config['upload_path'] = "./uploads/foto/";
$config['allowed_types'] = 'gif|jpg|png|JPEG';
$config['file_name'] = url_title($this->input->post('file_upload'));
$this->upload->initialize($config);
if(!$this->upload->do_upload('file_upload'))
{
echo $this->upload->display_errors();
}
else{
$data = array(
'gambar'=>$this->upload->file_name
);
$this->edulib_model->insert($data,'edulib');
}
}
My edulib_model.php
public function save($data)
{
$this->db->insert($this->table, $data);
return $this->db->insert_id();
}
public function insert($data,$table){
$this->db->insert($data,$table);
}
Related
hello i have a problem with sending data
i have a form that send data to a php file to insert it in data base.
signup.js
import { useState } from "react";
import axios from "axios";
const Signup =()=>{
const [cin,setCIN]=useState()
const [name,setName]=useState()
const [lastname,setLastname]=useState()
const [adress,setAdress]=useState()
const [tele,setTele]=useState()
const [email,setEmail]=useState()
const [pass,setPass]=useState()
const [re_pass,setRepass]=useState()
function Valide(e){
e.preventDefault();
if(pass===re_pass){
let data=new FormData()
data.append("cin",cin)
data.append("nom",name)
data.append("prenom",lastname)
data.append("email",email)
data.append("tele",tele)
data.append("adress",adress)
data.append("pass_word",pass)
axios({
method: 'post',
url:'http://localhost/projet_stage/src/PHP/register.php',
data: data,
config: { headers: { 'Content-Type': 'multipart/form-data' } }
})
.then(function (response) {
//handle success
console.log(response)
})
.catch(function (response) {
//handle error
console.log(response)
});
} else{
alert("Password mismatch")
}
}
function handleCIN(e){
setCIN(e.target.value)
}
function handleName(e){
setName(e.target.value)
}
function handleLastname(e){
setLastname(e.target.value)
}
function handleEmail(e){
setEmail(e.target.value)
}
function handlePass(e){
setPass(e.target.value)
}
function handleRepass(e){
setRepass(e.target.value)
}
function handleAdress(e){
setAdress(e.target.value)
}
function handleTele(e){
setTele(e.target.value)
}
return (
<section class="vh-100 bg-image"
style={{backgroundImage: "url('https://mdbcdn.b-cdn.net/img/Photos/new-templates/search-box/img4.webp');"}}>
<div class="mask d-flex align-items-center h-100 gradient-custom-3">
<div class="container h-100">
<div class="row d-flex justify-content-center align-items-center h-100">
<div class="col-12 col-md-9 col-lg-7 col-xl-6">
<div class="card" style={{borderRadius: "15px"}}>
<div class="card-body p-5">
<h2 class="text-uppercase text-center mb-5">Create an account</h2>
<div class="form-outline mb-4">
<input value={cin} name={"cin"} onChange={(e)=>handleCIN(e)} type="text" id="form3Example1ck" class="form-control form-control-lg" />
<label class="form-label" >cin</label>
</div>
<div class="form-outline mb-4">
<input value={name} name={"nom"} onChange={(e)=>handleName(e)} type="text" id="form3Example1cg" class="form-control form-control-lg" />
<label class="form-label" >nom</label>
</div>
<div class="form-outline mb-4">
<input value={lastname} name={"prenom"} onChange={(e)=>handleLastname(e)} type="text" id="form3Example2cg" class="form-control form-control-lg" />
<label class="form-label" >prenom</label>
</div>
<div class="form-outline mb-4">
<input value={adress} name={"adress"} onChange={(e)=>handleAdress(e)} type="text" id="form3Example2cm" class="form-control form-control-lg" />
<label class="form-label" >adress</label>
</div>
<div class="form-outline mb-4">
<input value={tele} name={"tele"} onChange={(e)=>handleTele(e)} type="text" id="form3Example2cl" class="form-control form-control-lg" />
<label class="form-label" >téle</label>
</div>
<div class="form-outline mb-4">
<input value={email} name={"email"} onChange={(e)=>handleEmail(e)} type="email" id="form3Example3cg" class="form-control form-control-lg" />
<label class="form-label">Your Email</label>
</div>
<div class="form-outline mb-4">
<input value={pass} name={"password"} onChange={(e)=>handlePass(e)} type="password" id="form3Example4cg" class="form-control form-control-lg" />
<label class="form-label" >Password</label>
</div>
<div class="form-outline mb-4">
<input value={re_pass} name={"re_password"} onChange={(e)=>handleRepass(e)} type="password" id="form3Example4cdg" class="form-control form-control-lg" />
<label class="form-label" >Repeat your password</label>
</div>
<div class="form-check d-flex justify-content-center mb-5">
<input class="form-check-input me-2" type="checkbox" value="" id="form2Example3cg" />
<label class="form-check-label" for="form2Example3g">
I agree all statements in <u>Terms of service</u>
</label>
</div>
<div class="d-flex justify-content-center">
<button type="button" name={"valide"} onClick={(e)=>Valide(e)}
class="btn btn-success btn-block btn-lg gradient-custom-4 text-body">Register</button>
</div>
<p class="text-center text-muted mt-5 mb-0">Have already an account? <a href="#!"
class="fw-bold text-body"><u>Login here</u></a></p>
</div>
</div>
</div>
</div>
</div>
</div>
</section>)
}
export default Signup;
when i submit the form the the php file insert a user with empty values that mean every think work but the data never send to php file .
register.php
require './server/connect.php';
$method = $_SERVER['REQUEST_METHOD'];
$request = explode('/', trim($_SERVER['PATH_INFO'], '/'));
if(isset($_POST["valide"])){
$cin = $_POST["cin"];
$name = $_POST["nom"];
$prenom = $_POST["prenom"];
$adres = $_POST["adress"];
$tele = $_POST["tele"];
$email = $_POST["email"];
$password = $_POST["password"];
}
$sql = "INSERT INTO user
(cin,nom,prenom,email,télé,
adress,pass_word,statut)
VALUES ('$cin','$name','$prenom','$email','$tele',
'$adres','$password','guest')";
if($db->query($sql)){
echo "workd";
}
?>
when show the data in the console i find a empty object i dont know whay???
CONSOLE.LOG:
also:
I'm writing a dynamic form that appends available text-fields depending on value that was selected by the user. How do I make it work? For context, it's an edit button, so the text-field will be pre-filled with STRING from the database.
The functions of getting the data from the database works, and the modal also shows, but the problem is just that the select-form doesn't work.
I tried calling "#btn-edit-account" but it doesn't work.
Code for the modal edit-account
<div class="modal fade" id="edit-account-modal" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Edit Account Details</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="tab-content" id="nav-tabContent">
<div class="tab-pane fade show active" id="nav-add" role="tabpanel" aria-labelledby="nav-home-tab">
<form id="form-edit-account">
<input type="hidden" name="_token" value="{{csrf_token()}}">
<div class="container my-2">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Role</label>
<select type="select" id="select-role" class="form-control edit_role select-role" name="role_id" required>
</select>
</div>
<div class="form-group student-number-container hidden">
<label>Student Number</label>
<input type="text" class="form-control" id="edit_student_number" name="student_number" required>
</div>
<div class="organization-container hidden">
</div>
<div class="form-row">
<div class="col-md-6">
<label>First name</label>
<input type="text" class="form-control" id="edit_first_name" name="first_name" required>
</div>
<input type="hidden" id="token" name="_token" value="{{csrf_token()}}">
<div class="col-md-6">
<label>Last Name</label>
<input type="text" class="form-control" id="edit_last_name" name="last_name" required>
</div>
</div>
<div class="form-group">
<label>Email</label>
<input type="email" class="form-control" id="edit_email" name="email">
</div>
<div class="form-row">
<label class="control-label">New Password <span class="required">*</span></label>
<input type="password" id="new_password" name="new_password" minlength="6" class="form-control password" required>
</div>
<div class="form-row">
<label class="control-label">Confirm New Password <span class="required">*</span></label>
<input type="password" id="confirm_password" name="confirm_password" minlength="6" class="form-control password" required>
</div>
<div class="form-group text-right mt-4">
<button type="button" class="btn btn-dark" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-success btn-confirm-edit-account">Update</button>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
Javascript for btn-edit-account
$(document).on('click', '.btn-edit-account', function() {
$('#edit-account-modal').modal('show');
var id = $(this).attr('data-id');
$.ajax({
url: "users/get-specific-user-info",
type: "POST",
data: {
id: id,
_token: "{{csrf_token()}}"
},
success: function(data) {
// $('#edit_role').val(data.role_id);
$('#edit_first_name').val(data.first_name);
$('#edit_last_name').val(data.last_name);
$('#edit_email').val(data.email);
console.log(data);
}
});
});
});
Javascript for select-role
$(document).on('change', '#select-role', function() {
var val = $(this).val();
if(val != 3){
$('.student-number-container').show();
}
else {
$('.student-number-container').hide();
}
if(val != 1){
$('.organization-container').html("");
}
else {
appendOrganization();
$('.organization-container').show();
}
});
function for appendOrganization
function appendOrganization() {
var html = "";
html += '<div class="form-group"> <label>Organization Name</label> <input type="text" class="form-control" name="organization_name" required> </div>';
html += '<div class="form-group"> <label>Organization Type</label> <select type="select" id="select-org-type" class="form-control" name="organization_type" required>'+
'<option value="" selected disabled>Select Organization Type</option>'+
'<option value="TYPE A">TYPE A</option>'+
'<option value="TYPE B">TYPE B</option>'+
'</select></div>';
html += '<div class="form-group"> <label>College</label> <select type="select" id="select-org-type" class="form-control" name="organization_college" required> <option value="" selected disabled>Select Organization Type</option> <option value="COLLEGE ONE">COLLEGE ONE</option> <option value="COLLEGE TWO">COLLEGE TWO</option> </select> </div>';
$('.organization-container').html(html);
}
The select in the modal should show the available choices in the given select, then will dynamically change the form depending on the selected choice.
I'm having some troble with AJAX call to update a page after insert the info in the DB.
I update the form, but i need to update the form after the update.
Need some help, i'm not so good whit javascript.
Thks!
<script>
function chk()
{
var nome=document.getElementById('nome').value;
var dataString= 'nome='+ nome;
$.ajax({
type:"post",
url: default,
data:dataString,
cache:false
//success: function(html){
// $('#msg').html(html);
//}
});
return false;
}
</script>
All the code i use, it's not final and not uptimized, its a form, update the field, and i want to update with the changes, without make a page refresh
<div class="col-md-12 personal-info">
<form class="form-horizontal" role="form" method="post" action="">
<div class="form-group">
<label class="col-lg-4 control-label">Nome:</label>
<div class="col-lg-8">
<input class="form-control" type="text" id="nome" name="nome" value="<?php echo name($resultado); ?>">
<!--<input class="form-control" type="text" value="<?php $nome; ?>">-->
</div>
</div>
<div class="form-group">
<label class="col-lg-4 control-label">Apelido:</label>
<div class="col-lg-8">
<input class="form-control" type="text" value="<?php echo apelido($chamada); ?>">
</div>
</div>
<div class="form-group">
<label class="col-lg-4 control-label">Morada:</label>
<div class="col-lg-8">
<input class="form-control" type="text" value="<?php echo morada(); ?>">
</div>
</div>
<div class="form-group">
<label class="col-lg-4 control-label">Código Postal:</label>
<div class="col-lg-8">
<input class="form-control" type="text" value="<?php echo codigopostal(); ?>">
</div>
</div>
<div class="form-group">
<label class="col-lg-4 control-label">Localidade:</label>
<div class="col-lg-8">
<input class="form-control" type="text" value="<?php echo localidade(); ?>">
</div>
</div>
<div class="form-group">
<label class="col-lg-4 control-label">Email:</label>
<div class="col-lg-8">
<input class="form-control" type="text" value="<?php echo email(); ?>">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Username:</label>
<div class="col-md-8">
<input class="form-control" type="text" value="<?php echo $current_user->user_login ?>">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Password:</label>
<div class="col-md-8">
<input class="form-control" type="password" value="11111122333">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Confirm password:</label>
<div class="col-md-8">
<input class="form-control" type="password" value="11111122333">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label"></label>
<div class="col-md-8">
<input type="submit" name="submit" class="btn btn-primary" value="Save Changes" onclick="return chk()">
<!--<input type="submit" name="submit" class="btn btn-primary" value="Save Changes">-->
<span></span>
<input type="reset" name="reset" class="btn btn-default" value="Cancel">
</div>
</div>
</form>
</div>
</div>
</div>
<hr>
<!--teste final-->
<?php
global $wpdb;
global $seconddb;
global $current_user;
if ($_POST['submit']){
$new = $_POST['nome'];
$query = $seconddb->query("UPDATE {$wpdb->prefix}sgc_socios SET nome='$new' WHERE email = '{$current_user->user_email}' ");
}
?>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
function chk()
{
var nome=document.getElementById('nome').value;
var dataString= 'nome='+ nome;
$.ajax({
type:"post",
url: default,
data:dataString,
cache:false
//success: function(html){
// $('#msg').html(html);
//}
});
return false;
}
</script>
Thks for the help!
When im doing a ajax call to the update.php from profiles.php it go a blank page update.php but it does make the changes if i go back to the profile.php
idk what im doing wrong what im missing??
profile.php
<?php include_once("includes/config.php");
if (isset($_GET['id']))
{
$Nome = $_GET['id'];
$sql = "SELECT * FROM utilizadores WHERE id='$Nome'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
if($row = $result->fetch_assoc()) {
echo'
<br>
<form action="update.php" method="post" id="go" class="go" accept-charset="utf-8">
<div class="content" >
<div class="container-fluid">
div class="row">
<div class="col-md-8">
<div class="card">
<div class="header">
<h4 class="title">Perfil do paciente</h4>
</div>
<div class="content">
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label>Nome</label>
<input type="text" class="form-control" disabled placeholder="Nome" value="'.$row["Nome"].'">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>Apelido</label>
input type="text" class="form-control" disabled placeholder="Apelido" value="'.$row["Apelido"].'">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label for="exampleInputEmail1">Email</label>
<input type="email" class="form-control" name="Email "disabled placeholder="Email" value="'.$row["Email"].'">
</div>
</div>
</div>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label>Idade</label>
<input type="text" class="form-control" disabled placeholder="Idade" value="'.$row["Idade"].'">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>Sexo</label>
<input type="text" class="form-control" disabled placeholder="Sexo" value="'.$row["Sexo"].'">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>Telefone</label>
<input type="text" class="form-control" disabled placeholder="Telefone" value="'.$row["Telefone"].'">
</div>
</div>
</div>
<div class="row">
<div class="col-md-3">
<div class="form-group">
<label>Peso</label>
<input type="text" class="form-control" disabled placeholder="Peso" value="'.$row["Peso"].'Kg">
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label>Altura</label>
<input type="text" class="form-control" disabled placeholder="Altura" value="'.$row["Altura"].'Cm">
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label>Perimetro Abdominal</label>
<input type="text" class="form-control" disabled placeholder="Perimetro abdominal" value="'.$row["Perimetro_abdominal"].'Cm">
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label>Perimetro Anca </label>
<input type="text" class="form-control" disabled placeholder="Perimetro Anca" value="'.$row["Perimetro_anca"].'Cm">
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Medicação:</label>
<textarea rows="3" class="form-control" name="Medicacao" placeholder="Medicação" id="Medicacao">'.$row["Medicacao"].'</textarea>
</div>
<input type=hidden name=hidden value="'.$row["id"].' ">
<input type="submit" name="med" class="btn btn-info btn-fill pull-right" value="Atualizar" id="med"></div>
<div class="col-md-6">
<div class="form-group">
<label>Observações:</label>
<textarea rows="3" name="Obs" class="form-control" placeholder="Anotar observações" id="Obs">'.$row["Obs"].' </textarea>
</div>
<input type="submit" name="obs" class="btn btn-info btn-fill pull-right" value="Atualizar">
</div>
</div></form>';
}
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_close($conn);
?>
<script type="text/javascript">
$( "#med" ).click(function() {
$.ajax({
type: "POST",
url: "update.php",
success: function(){
alertify.success('campo atualizado com sucesso');
}
});
});
</script>
update.php
include_once("includes/config.php");
if(isset($_POST['med'])) {
$UpdateQuery = "UPDATE utilizadores SET Medicacao='$_POST[Medicacao]' WHERE id='$_POST[hidden]' ";
$res = mysqli_query($conn,$UpdateQuery);
if($res == 1)
{
//header('Location: ' . $_SERVER['HTTP_REFERER'],true, 301 );
}
?>
You are not cancelling the default submit event of your submit button when you handle the click event. That causes the form to be submitted in the normal way as well by going to the url that is set in the action attribute of the form.
Apart from that, you also need to add the data to the ajax request.
This:
$( "#med" ).click(function() {
$.ajax({
type: "POST",
url: "update.php",
success: function(){
alertify.success('campo atualizado com sucesso');
}
});
});
should be:
$( "#med" ).click(function(event) {
// cancel default submit event
event.preventDefault();
$.ajax({
type: "POST",
// add data
data: $('form#go').serialize(),
url: "update.php",
success: function(){
// Do whatever you need to here
console.log('campo atualizado com sucesso');
}
});
});
I have an AngularJS front end for a new internal web portal I am building. Using value={{data.Param}} I have successfully gotten my get and create requests to work via Slim PHP. Now however I am trying to create a PUT request and I am running into an issue.
This is the current code for my "Update /PUT" page.
request-edit.html
<div class="jumbotron text-center">
<form class="form-horizontal" role="form">
<div class="form-group">
<div class="text-center">
<h1>{{ header }}</h1>
<br/>
<h3>{{ request.Header }}</h3>
<br/>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Id:</label>
<div class="col-sm-3">
<input name="id" class="form-control" type="text" value="{{request.ID}}" disabled />
</div>
<label class="col-sm-3 control-label">Date:</label>
<div class="col-sm-3">
<input type="text" class="form-control" value="{{ request.Date_Submitted }}" disabled/>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Change Initiator:</label>
<div class="col-sm-3">
<input type="text" class="form-control" placeholder="{{request.Change_Initiator}}" ng-model="request.changeInitiator"/>
</div>
<label class="col-sm-3 control-label">Risk Level:</label>
<div class="col-sm-3">
<input type="text" class="form-control" placeholder="{{ request.Risk_Level }}" ng-model="request.riskLevel" />
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">CI Details:</label>
<div class="col-sm-3">
<input type="text" class="form-control" placeholder="{{ request.Change_Initiator_id }}" ng-model="request.changeInitiatorId" />
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Requestor:</label>
<div class="col-sm-3">
<input type="text" class="form-control" placeholder="{{ request.Requestor }}" ng-model="request.requestor" />
</div>
<label class="col-sm-3 control-label">Systems Affected:</label>
<div class="col-sm-3">
<input type="text" class="form-control" placeholder="{{ request.Systems_Affected }}" ng-model="request.systemsAffected" />
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Implemented By:</label>
<div class="col-sm-3">
<input type="text" class="form-control" placeholder="{{ request.Implemented_By }}" ng-model="request.implementationBy" />
</div>
<label class="col-sm-3 control-label">Implementation Date:</label>
<div class="col-sm-3">
<input type="text" class="form-control" placeholder="{{ request.Implementation_Date }}" ng-model="request.implementationDate" bs-datepicker/>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Close Date:</label>
<div class="col-sm-3">
<input type="text" class="form-control" placeholder="{{ request.Close_Date }}" ng-model="request.closeDate" />
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Work to be Performed:</label>
<div class="col-sm-3">
<textarea name="request.description" ng-model="request.workToBePerformed" placeholder="{{ request.Work_to_be_performed }}" ></textarea>
</div>
<label class="col-sm-3 control-label">Backout Plan:</label>
<div class="col-sm-3">
<textarea name="request.description" ng-model="request.backoutPlan" placeholder="{{ request.Backout_Plan }}" ></textarea>
</div>
</div>
<div class="form-group">
<button class="update" ng:click="updateRequest()">Save Edits</button>
<button class="approve" ng:click="approveRequest()">Approve</button>
</div>
</form>
<div class="form-group">
<a href="#/requests" class="btn btn-default pull-right">
<span class="glyphicon glyphicon-arrow-left"></span> Back
</a>
</div>
</div>
My confusion in with ng-model, value and placeholders. Currently all my data populates in the form, but when the user goes to update the page they have to re-fill out every box or else blank data will be pushed. I understand the Placeholder does not actually fill in the data - however I have been un-able to use both ng-model and value on the same input field.
My top two fields populate using value just fine, but I do not want people to edit the date or ID. My other fields show the correct data in a temp form using placeholder but do not populate using ng-model. Additionally when my user goes to make the update the ng-model DOES function.
So in short my current issue is that ng-model does not display the original data- but does push it correctly. This causes my users to have to re-type all the data everytime or else the record will be updated with null values.
Below is the rest of my logic for review.
app.js
var app = angular.module('changeControlApp', [
'ngRoute',
'ngResource'
]);
//This configures the routes and associates each route with a view and a controller
app.config(function($routeProvider, $locationProvider) {
//$locationProvider.html5Mode(true);
$routeProvider
.when('/', {templateUrl: 'app/partials/request-list.html', controller: 'viewController' })
.when('/requests', {templateUrl: 'app/partials/request-list.html', controller: 'viewController' })
.when('/requests/create', {templateUrl: 'app/partials/request-create.html', controller: 'createRequestController' })
.when('/settings', {templateUrl: 'app/partials/settings.html', controller: 'settingsController'})
.when('/requests/:id', {templateUrl: 'app/partials/request-view.html', controller: 'viewRequestController' })
.when('/requests/edit/:id', {templateUrl: 'app/partials/request-edit.html', controller: 'editRequestController' })
.otherwise({ redirectTo: '/' });
});
app.controller('editRequestController', function($scope, $location, $route, $routeParams, $resource) {
$scope.header = 'Edit Change Request';
// Update User details
var request_Id = $routeParams.id;
if (request_Id) {
var Request = $resource(('http://pdgrosit02v/changeRequest/app/api/requests/'+ request_Id));
$scope.request = Request.get();
}
$scope.updateRequest = function() {
var RequestPut = $resource(('http://pdgrosit02v/changeRequest/app/api/requests/'+ request_Id), {}, { update: { method: 'PUT'}} );
RequestPut.update($scope.request, function() {
// success
$location.path('/requests');
}, function() {
// error
console.log(error);
});
}
});
And the Slim file
index.php
<?php
require 'Slim/Slim.php';
\Slim\Slim::registerAutoloader();
use Slim\Slim;
$app = new Slim();
//$paramValue = $app->request->params('paramName');
$app->get('/requests', 'getRequests');
$app->get('/requests/:id', 'getRequest');
$app->post('/requests/create', 'addRequest');
$app->put('/requests/:id', 'updateRequest');
$app->run();
function updateRequest($id) {
$request = Slim::getInstance()->request()->getBody();
$data = json_decode($request, true);
$sql = "UPDATE change_request SET Change_Initiator=:changeInitiator, Change_Initiator_id=:changeInitiatorId, Risk_Level=:riskLevel, Requestor=:requestor, Work_to_be_performed=:workToBePerformed, Backout_Plan=:backoutPlan, Backout_Time=:backoutTime, Implementation_Date=:implementationDate, Header=:title, Systems_Affected=:systemsAffected, Implemented_By=:implementationBy WHERE ID=$id";
//$sql = "UPDATE change_request SET Change_Initiator=:changeInitiator WHERE ID=$id";
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindValue(":changeInitiator", $data['changeInitiator']);
$stmt->bindParam(":changeInitiatorId", $data['changeInitiatorId']);
$stmt->bindParam(":riskLevel", $data['riskLevel']);
$stmt->bindParam(":requestor", $data['requestor']);
$stmt->bindParam(":workToBePerformed", $data['workToBePerformed']);
$stmt->bindParam(":backoutPlan", $data['backoutPlan']);
$stmt->bindParam(":backoutTime", $data['backoutTime']);
$stmt->bindParam(":implementationDate", $data['implementationDate']);
$stmt->bindParam(":title", $data['title']);
$stmt->bindParam(":systemsAffected", $data['systemsAffected']);
$stmt->bindParam(":implementationBy", $data['implementationBy']);
$stmt->execute();
$db = null;
echo json_encode($data);
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
I figured out the issue, turns out Value and ng-model conflict and I had to modify my form to get the data correctly.
I removed all value commands and replaced them with ng-model="data.keyvalue". I was confused before as I thought you needed to use {{}} when referencing things off the scope.
I also added form validation for updating - new code below
request-edit.html
<div class="jumbotron text-center">
<form class="form-horizontal" role="form" name="requestEditForm" ng-submit="updateRequest()">
<div class="form-group">
<div class="text-center">
<h1>{{ header }}</h1>
<br/>
<h3>Title of request:</h3>
<input name="title" id="title" class="form-control" type="text" ng-model="request.Header" />
<br/>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Id:</label>
<div class="col-sm-3">
<input name="id" class="form-control" type="text" value="{{request.ID}}" disabled />
</div>
<label class="col-sm-3 control-label">Date Submitted:</label>
<div class="col-sm-3">
<input type="text" class="form-control" value="{{ request.Date_Submitted }}" disabled/>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Change Initiator:</label>
<div class="col-sm-3">
<input type="text" class="form-control" ng-model="request.Change_Initiator" name="changeInitiator" id="changeInitiator" />
<span class="error" ng-show="requestEditForm.changeInitiator.$error.required && requestEditForm.changeInitiator.$dirty">Title is required</span>
</div>
<label class="col-sm-3 control-label">Risk Level:</label>
<div class="col-sm-3">
<input type="text" class="form-control" ng-model="request.Risk_Level" name="riskLevel" id="riskLevel" required/>
<span class="error" ng-show="requestEditForm.riskLevel.$error.required && requestEditForm.riskLevel.$dirty">Risk Level is required</span>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">CI Details:</label>
<div class="col-sm-3">
<input type="text" class="form-control" ng-model="request.Change_Initiator_id" />
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Requestor:</label>
<div class="col-sm-3">
<input type="text" class="form-control" ng-model="request.Requestor" />
</div>
<label class="col-sm-3 control-label">Systems Affected:</label>
<div class="col-sm-3">
<input type="text" class="form-control" ng-model="request.Systems_Affected" />
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Implemented By:</label>
<div class="col-sm-3">
<input type="text" class="form-control" ng-model="request.Implemented_By" />
</div>
<label class="col-sm-3 control-label">Implementation Date:</label>
<div class="col-sm-3">
<input type="text" class="form-control" ng-model="request.Implementation_Date" bs-datepicker/>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Close Date:</label>
<div class="col-sm-3">
<input type="text" class="form-control" ng-model="request.Close_Date" />
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Work to be Performed:</label>
<div class="col-sm-3">
<textarea name="request.description" ng-model="request.Work_to_be_performed"></textarea>
</div>
<label class="col-sm-3 control-label">Backout Plan:</label>
<div class="col-sm-3">
<textarea name="request.description" ng-model="request.Backout_Plan"></textarea>
</div>
</div>
<div class="form-group">
<button class="submit">Save Edits</button>
<button class="approve" ng:click="approveRequest()">Approve</button>
</div>
</form>
<div class="form-group">
<a href="#/requests" class="btn btn-default pull-right">
<span class="glyphicon glyphicon-arrow-left"></span> Back
</a>
</div>
</div>