Strange behaviour of my javascript - javascript

Sorry for the vague title, but this behaviour is pretty hard to explain.
I have a form where I enter some information. When the user click the submit button (values "programma"), I call a javascript. I check that the info are correct and use AJAX to add a record in my local database. The strange behaviour is the following:
I fill up the form. The record doesn't exist in my DB. Everything works correctly and my record is inserted. Success: I write in the span tag "Esecuzione registrata correttamente!"
Then I try to insert the same record. Since it exists in my DB, the error gets notified correctly in my span: "Esiste un condannato con gli stessi dati"
At this point my form is still full of text, if the user want to correct his mistake and insert a non-existing record. What happens is that, when I change some input (and I'm sure that record doesn't exist in my DB) and click the submit button, literally nothing happens. I still see my error message "Esiste un condannato con gli stessi dati", even if I saw in my console that my AJAX worked correctly
programma.php (what you see in my screenshot)
<?php
session_start();
if(!isset($_SESSION["nickname"]) && !isset($_SESSION["password"]) ) {
header("location: index.php");
exit();
}
else
{
echo "<p> Sessione di ".$_SESSION["nickname"]." con password ".$_SESSION["password"]." </p>";
}
?>
<!DOCTYPE html>
<html lang="it">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="programma.css">
<style type="text/css">
.container {
width: 500px;
clear: both;
}
.container text {
width: 100%;
clear: both;
}
</style>
<title>RIPconvicts - Programma esecuzione</title>
</head>
<body>
<?php require 'snippets/menu.php'; ?>
<form>
<fieldset class="centered">
<legend>Programma nuova esecuzione</legend>
<label for="nome"> Nome* </label> <br>
<input type="text" name="nome" id="nome"> <br> <br>
<label for="cognome"> Cognome* </label> <br>
<input type="text" name="cognome" id="cognome"> <br> <br>
<label for="classe"> Classe* </label> <br>
<input type="text" name="classe" id="classe"> <br> <br>
<label for="materia"> Materia* </label> <br>
<input type="text" name="materia" id="materia"> <br> <br>
<label for="data">Data* </label> <br>
<input type="date" name="data" id="data"> <br> <br>
Note <br>
<textarea name="note" id="note" rows="6" cols="50"> </textarea> <br> <br>
<span id="avviso" style="color:red"></span> <br>
<input type="button" onclick="programma_esecuzione()" value="Programma">
</fieldset>
</form>
<?php require 'snippets/footer.php'; ?>
<script>
function programma_esecuzione() {
// Verifica che tutti i campi necessari siano stati riempiti
document.getElementById("avviso").innerHTML = "";
var nomi = ["nome", "cognome", "classe", "materia"];
var campi_mancanti = "";
for(var i=0; i<nomi.length-1; i++) {
if(document.getElementById(nomi[i]).value == "") {
campi_mancanti+=" "+nomi[i];
}
}
if(!Date.parse( document.getElementById("data").value )) {
campi_mancanti+=" data";
}
// Se ci sono campi mancanti, ritorna alla pagina principale
if(campi_mancanti!="") {
window.alert("Riempire i seguenti campi mancanti:"+campi_mancanti);
return;
}
// Se tutti i campi necessari ci sono, allora è possibile richiedere l'aggiunta del record
var xhttp;
xhttp = new XMLHttpRequest();
var nome = document.getElementById("nome").value;
var cognome = document.getElementById("cognome").value;
var classe = document.getElementById("classe").value;
var materia = document.getElementById("materia").value;
var data = document.getElementById("data").value;
var note = document.getElementById("note").value;
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var risposta = this.responseText;
if(risposta.indexOf("Esecuzione registrata correttamente!") > -1) {
// Svuota tutti i campi
document.getElementById("nome").value = "";
document.getElementById("cognome").value = "";
document.getElementById("classe").value = "";
document.getElementById("materia").value = "";
document.getElementById("data").value = "";
document.getElementById("note").value = "";
}
document.getElementById("avviso").innerHTML = risposta;
}
};
xhttp.open("POST", "./snippets/programma_esecuzione.php", false);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("nome="+nome+"&cognome="+cognome+"&classe="+classe+"&materia="+materia+"&data="+data+"&note="+note);
}
</script>
</body>
</html>
programma_esecuzione.php (where I execute my query)
<?php
//Include
require 'connetti_a_DB.php';
// Variabili per il login
$nome = $_POST["nome"];
$cognome = $_POST["cognome"];
$classe = $_POST["classe"];
$materia = $_POST["materia"];
$data = $_POST["data"];
$note = $_POST["note"];
/*echo $nome."<br>";
echo $cognome."<br>";
echo $classe."<br>";
echo $materia."<br>";
echo $data."<br>";
echo $note."<br>";*/
// Inizia una sessione
session_start();
$username = $_SESSION["nickname"];
$password = $_SESSION["password"];
// Stabilire e chiudere connessione
$conn = connetti_a_DB($username, $password);
// Verifica se c'è un record "clone"
$nome_completo = $nome." ".$cognome;
$sql = " SELECT *
FROM `lista`
WHERE `NOME_COMPLETO`='$nome_completo' OR
`CLASSE`='$classe' OR
`MATERIA` ='$materia' OR
`DATA` ='$data'";
$result = $conn->query($sql);
if($result->num_rows > 0) {
echo 'Esiste un condannato con gli stessi dati';
}
else
{
$sql = "INSERT INTO `ripconvicts`.`lista` (`ID`, `NOME_COMPLETO`, `CLASSE`, `MATERIA`, `DATA`, `NOTE`)
VALUES (NULL, '$nome_completo', '$classe', '$materia', '$data', '$note')";
$result = $conn->query($sql);
echo "Esecuzione registrata correttamente!";
}
$conn->close();
// Salta alla pagina iniziale
//header("location: ../programma.php");
//exit();
?>

Related

Opening a .html with window.location

I'm writing a simple login page in Ajax + Jquery
I have an error when I click on the button. And I don't understand why.
Uncaught SyntaxError: Unexpected end of input
At this line
echo '<input type="button" value="connexion" OnClick="window.location.assign("http://localhost/loginmap/members/success.html")>';
There is my code
<?php
session_start();
//si le user a un session de ouverte
/*if(isset($_SESSION['connecté'])){
header('Location : success.html');
die();
}*/
if (isset($_POST['login'])) {
$connection = new mysqli('localhost','root','','monumap');
$email = $connection->real_escape_string($_POST['emailPHP']);
$password = $connection->real_escape_string($_POST['passwordPHP']);
$data = $connection->query("SELECT id FROM users WHERE email = '$email' AND password = '$password'");
if($data->num_rows >= 0) {//tout et ok -> connexion
$_SESSION['connecté'] = '1';
//$_SESSION['email'] = $email;
header('Location:'.$_SESSION['redirectURL']);
exit('<font color = "green">Connexion reussi...</font>');
}else{
exit('<font color = "red">Le Mot de passe / Email est inconnue </font>');
}
//exit($email . " = " . $password);
}
?>
<html>
<head>
<title>Monumap Connexion</title>
</head>
<body>
<form method="post" action="login.php">
<input type="text" id="email" placeholder="Email..."><br>
<input type="password" id="password" placeholder="Mot de passe..."><br>
<input type="submit" value="Log In" id="login">
</form>
<p id = "reponse"></p>
<div class="Bouton">
<?php if($_SESSION['connecté']==1){
echo '<input type="button" value="connexion" OnClick="window.location.assign("http://localhost/loginmap/members/success.html")>';
}
?>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#login").on('click', function () {
var email = $("#email").val();
var password = $("#password").val();
if (email == "" || password == "")
alert('vos inputs sont vides');
else {
$.ajax(
{
url: 'login.php',
method: 'POST',
data: {
login: 1,
emailPHP: email,
passwordPHP: password
},
success: function (reponse) {
$("#reponse").html(reponse);
},
dataType: 'text'
}
);
}
});
});
</script>
</body>
</html>
echo '<input type="button" value="connexion" onclick="window.location.assign('."'http://localhost/loginmap/members/success.html'".');")/>';
It's cause you wrote quote character.
You can use this way as well.
echo '<input type="button" value="connexion" onclick="func()"/>';
?>
<script>
function func(){
window.location.assign("http://localhost/loginmap/members/success.html");
}
</script>

javascript function is supposed to display php SESSION data but isn't called

I'm trying to make a regular old registration form for a website; and I'm trying to display the name of the logged-in user(if any) at the top of the page. However, the function that is supposed to update that field doesn't seem o be called at all, and I can't make heads or tails of it, nor of the error messages my console displays:
"Uncaught SyntaxError: Unexpected token < -- pagina_registrazione.php:36"
"Uncaught ReferenceError: update_name is not defined
onload -- pagina_registrazione.php:10"
here is the code:
<?php
require './config_db.php';
?>
<!DOCTYPE HTML>
<html lang = "it" >
<head>
<meta charset="utf-8">
<meta name = "keywords" content = "catcher, profilo, registrazione, utente">
<meta name="author" content="Luca Ballarati">
<link rel="stylesheet" href="./../stile/sottopagine.css" type="text/css" media="screen">
<title>pagina di registrazione</title>
</head>
<body onload=update_name>
<section>
<p id="spia_connessione">NOMEUTENTEQUI</p>
<p>Se hai già un'account <strong>clicca qui</strong> per accedere.</p>
<p>Altrimenti <strong>registrati</strong> compilando i campi qui sotto</p>
</section>
<div id="login_form">
<form name="registra" action="./pagina_registrazione.php" method="post">
<div>
<label><p>Nome Utente</p></label>
<input type="text" placeholder="nome_utente" name="username" required autofocus>
</div>
<div>
<label><p>Password</p></label>
<input type="password" placeholder="password" name="password" required>
</div>
<div>
<label><p>Conferma Password</p></label>
<input type="password" placeholder="conferma_password" name="passwordconfirm" required>
</div>
<input name="pulsante_invio" type="submit" value="Invia">
<?php
if(isset($_POST['pulsante_invio'])) {
$nomeutente = $_POST['username'];
$password = $_POST['password'];
$cpassword = $_POST['passwordconfirm'];
if ($password==$cpassword) {
$query = "SELECT * FROM utenti WHERE NomeUtente='$nomeutente'";
$esegui_query = mysqli_query($con,$query);
if(mysqli_num_rows($esegui_query)>0) {
echo '<script type="text/javascript">
window.alert("Nome Utente già usato: registrarsi con un diverso Nome Utente");
</script>';
}
else {
$query = "INSERT INTO utenti (NomeUtente,Password,Record,Partite)
VALUES('$nomeutente','$password',0,0)";
$esegui_query = mysqli_query($con,$query);
if ($esegui_query) {
$nome = $_SESSION['username'];
//porta l'utente alla pagina di login
echo '<script type="text/javascript">
window.alert("Utente registrato correttamente");
</script>';
//echo '<script type="text/javascript">
//document.getElementById("spia_connessione").innerHTML = "'$nome'";
//</script>';
}
else {
echo '<script type="text/javascript">
window.alert("Errore durante la registrazione");
</script>';
}
}
}
else {
echo '<script type="text/javascript">
window.alert("Password e Password di conferma devono essere uguali");
</script>';
}
}
?>
</form>
</div>
<script type="text/javascript">
function update_name() {
window.alert("nome utente aggiornato");
var nm = <?php echo $_SESSION['username']; ?>;
document.getElementById("spia_connessione").innerHTML = nm;
}
</script>
</body>
Please write this code on the top of your php file.
<?php
ob_start();
session_start();
?>

Problems with retrieving database info through AJAX/jQuery using dynamic fields

I am creating dynamic input textbox fields through jQuery. When a user clicks the link, two input fields are created. On the left input, the user can type in a code (or DB table id) and on the right input, they should see the name related to the id as the result.
To accomplish this, I attached a 'blur' event that will make an AJAX request to a PHP script which will query the database to retrieve the information. However my code is not working.
Here's what I've tried so far:
consulta.php
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var contenedor = $("#contenedor");
var AddButton = $("#agregarCampo");
var x = $("#contenedor div").length + 1;
var FieldCount = x-1;
$(AddButton).click(function (e)
{
if(x)
{
FieldCount++;
$(contenedor).append('<div class="added"><input type="text" name="codigo[]" id="campo'+FieldCount+'" placeholder="Ingrese codigo ID '+ FieldCount +'"/><input type="text" name="nombre" id="nombre'+FieldCount+'" value=""></div>');
x++;
}
return false;
});
});
</script>
</head>
<body>
<div id="cliente">
<table>
<tr>
<td>
Codigo
</td>
</tr>
<tr>
<td>
<div id="contenedor">
<div class="added">
<input type="text" name="codigo[]" id="codigo" placeholder="Ingrese codigo ID" required/>
<input type="text" name="nombre" id="nombre" value="">
</div>
</div>
<p>
<a id="agregarCampo" href="#">Agregar Campo</a>
</p>
</td>
</tr>
</table>
</div>
<script type="text/javascript" src="cliente.js"></script>
</body>
</html>
cliente.js
$(function(){
$('#cliente').on('blur','#codigo',function(){
var id = $(this).parents('div').attr('id');
var valor = this.value;
if(valor.length>=1){
var consulta = $.ajax({
type:'POST',
url:'cliente.php',
data:{codigo:valor},
dataType:'JSON'
});
consulta.done(function(data){
if(data.error!==undefined){
$('#estado').html('Ha ocurrido un error: '+data.error);
return false;
} else {
if(data.nombre!==undefined){$("#cliente #nombre").val(data.nombre);}
return true;
}
});
}
});
});
cliente.php
<?php
$codigo=$_POST['codigo'];
$conexion=mysqli_connect("localhost","root","","gabu");
if (mysqli_connect_errno($conexion)) {
echo "Fallo al conectar a MySQL: " . mysqli_connect_error();
}
$registros=mysqli_query($conexion, "select * from estudiantes where estudiante_id='$codigo'") or
die("Problemas en el select:".mysqli_error());
if ($reg=mysqli_fetch_array($registros))
{
$return = array('nombre' => $reg['nombre_estudiante']);
} else {
$return = array('nombre'=>'No existe el registro');
}
die(json_encode($return));
?>
This is how it should look like. Please help. Thanks.
You have a few problems. The ones that stand out the most are the HTML IDs and Classes. Theres no reason to create IDs dynamically as you can use classes for reference. Also, in PHP, you should use the right syntax for mysqli and return a proper JSON, with headers.
This is what I would do:
HTML/JS:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var $contenedor = $("#contenedor");
var $AddButton = $("#agregarCampo");
$AddButton.click(function (e) {
e.preventDefault();
var FieldCount = $contenedor.children('div').length + 1;
$contenedor.append('<div class="added">\
<input type="text" class="codigo_input" placeholder="Ingrese codigo ID ' + FieldCount + '"/>\
<input type="text" class="nombre_input" >\
</div>');
});
});
</script>
</head>
<body>
<div id="cliente">
<table>
<tr>
<td>
Codigo
</td>
</tr>
<tr>
<td>
<div id="contenedor">
<div class="added">
<input type="text" class="codigo_input" placeholder="Ingrese codigo ID" required/>
<input type="text" class="nombre_input" value="">
</div>
</div>
<p>
<a id="agregarCampo" href="#">Agregar Campo</a>
</p>
</td>
</tr>
</table>
</div>
<script>
$(function () {
$('#cliente').on('blur', '.codigo_input', function () {
var $container = $(this).closest(".added");
var valor = $(this).val();
if (valor.length >= 1) {
var consulta = $.ajax({
type: 'POST',
url: 'cliente.php',
data: {codigo: valor},
dataType: 'JSON'
});
consulta.done(function (data) {
if (data.error !== undefined) {
$('#estado').html('Ha ocurrido un error: ' + data.error);
return false;
} else {
if (data.nombre !== undefined) {
$container.find('.nombre_input').val(data.nombre);
}
return true;
}
});
consulta.error(function(a,b,c){
console.log(a);
console.log(b);
console.log(c);
});
}
});
});
</script>
</body>
</html>
PHP
$codigo = $_POST['codigo'];
$conexion = mysqli_connect("localhost", "root", "", "gabu");
if (mysqli_connect_errno()) {
echo "Fallo al conectar a MySQL: " . mysqli_connect_error();
}
$registros = mysqli_query($conexion, "select * from estudiantes where estudiante_id='$codigo'") or
die("Problemas en el select:" . mysqli_error($conexion));
if (mysqli_num_rows($registros) > 0) {
$reg = mysqli_fetch_assoc($registros);
$return = array('nombre' => $reg['nombre_estudiante']);
} else {
$return = array('nombre' => 'No existe el registro');
}
header('Content-Type: application/json');
echo json_encode($return);
I'd suggest to debug the frontend and backend separately.
I've rewritten the clinte.php to only display json
<?php
$codigo=$_POST['codigo'];
$return = $_POST;
$return = array('nombre' => 1337);
die(json_encode($return));
?>
and it seems it's working.
The question is if you're selecting by the ID column, should it be number?
Can you add your db structure as well?

javascript form validation with multiple field and display on site

So, hey, I know that there's more than someone could want of this type of question, but maybe I can present it with a little twist, i have try to mix different thing reader here and there, but when i submit the form the validation process don't run and it just submit directly the form. It's a one go script, and it go like this:
<script type="text/javascript">
var errors =[];
function printarray(array){
for (var i=0; i<array.lenght; i++){
document.write(array[i]);
}
}
function validate(){
document.getElementById("npostform").elements["contenidotext"].value=window.frames["contenido"].document.body.innerHTML;
document.getElementById("npostform").elements["resumentext"].value=window.frames["resumen"].document.body.innerHTML;
if (document.npostform.titulo.value=="" || document.npostform.titulo.value==null){
errors.push("Se debe especificar un titulo <br>");
}
if (document.npostform.contenidotext.value=="" || document.npostform.contenidotext.value==null){
errors.push("Se debe incluir un contenido <br>");
}
if (document.npostform.resumentext.value=="" || document.npostform.resumentext.value==null){
errors.push("Se debe incluir un resumen <br>");
}
if(errors.length >0){
for (var i=0; i<errors.lenght; i++){
document.getElementById("error").innerHTML=printarray(errors);
}
return false;
}else{
return true;
}
}
</script>
<div id="error"></div>
<form action="entradas.php" name="npostform" id="npostform" method="post" enctype="multipart/form-data" onsubmit="return validate();">
<label for="Titulo">Titulo:</label>
<input type="text" name="titulo" value="<?php if (isset($_SESSION['titulo'])) { echo $_SESSION['titulo'];} ?>">
<br>
<label for="Categoria">Categoria-Seccion:</label>
<select name="categoria" value= "<?php if(isset($_SESSION['categoria'])){echo $_SESSION['categoria'];} ?>">
<option value=""></option>
<?php
foreach (tomarcategorias() as $order =>$categorias){
$name = $categorias['name'];
$id = $categorias['id'];
$order =$categorias['order'];
if ($categorias['type'] == 'Articulos'){
echo "<optgroup label='", $name, "'>";
foreach(tomarsecciones('idcategoria', $id) as $ord => $secciones){
$ord = $secciones['order'];
echo "<option value='", $secciones['id'], "'><PRE>", $secciones['name'], "</option>";
}
}
}
?>
</select>
<br>
<textarea name="contenidotext" rows="15" cols="50" style="display:none;"></textarea>
<iframe name="contenido" id="contenido" style="width:300; height:100; background: white;"></iframe>
<br>
<label>Resumen del articulo</label>
<br>
<textarea name="resumentext" rows="5" cols="50" style="display:none;"></textarea>
<iframe name="resumen" id="resumen" style="background: white;"><?php if (isset($_SESSION['resumen'])) { echo $_SESSION['resumen'];}?></iframe>
<br>
<input type="submit" name="add_post" value="Subir post"/>
</form>
I have to be sincere, in the head there is a linked javascript but that contain functions for buttons for a simple wysiwyg and already try to make all the script together, in the same and different files, didn't change a thing.
Does anybody know where the bug is? and also,is there a way to view the errors of javascript script as in php?

Reselect dropdownlist after submit/error . validation

I'm sorry but my brain is totally fogging up on this one.
I want to have my dropdownlist 'editprojectSelect' to be selected if there is an error with validation. P.S. in the picture i posted u can see i specifically entered a string 'test' where there should be an integer.
<div id="project-wijzigen" class="form">
<h2> Wijzig een project </h2>
<select id="editprojectSelect" name="editprojectSelect" onchange="getDetails()">
<option value="">-</option>
</select>
<?php echo '<input type="hidden" id="hidden-input" value="'.$_POST['editProjectSelect'].'">';?>
<div id="editProject">
<?php echo form_open('c_admin/wijzigProject');?>
<h2 id="hoofding"></h2>
<div><label> Project titel: </label> <input type="text" id="pt" name="titel" required value="<?php echo set_value('projecttitel'); ?>"/></div>
<div><label> Startdatum: </label> <input type="text" id="sd" name="start" required value="<?php echo set_value('startdatum'); ?>"/></div>
<div><label> Einddatum: </label> <input type="text" id="ed" name="eind" required value="<?php echo set_value('einddatum'); ?>"/></div>
<div><label> In samenwerking met: </label> <input type="text" id="samen" name="samen" required value="<?php echo set_value('ism'); ?>"/></div>
<div><label> Omschrijving: </label> <textarea id="omschr" name="text" required value="<?php echo set_value('text'); ?>"></textarea></div>
<input type="hidden" id="hiddenID" name="hiddenID" />
<input type="submit" name="submit" value="Wijzig project"/>
<?php echo form_close(); ?>
</div>
<?php
// --------------------------- Error checking/display
if(isset($projectWijzigenError)) // check of de variabele wel een waarde heeft (als je die zomaar oproept en hij moest leeg of NULL zijn dan krijg je een error op je pagina)
{
if ($projectWijzigenError=='true') // ALS er een error is, dan opent de form terug en worden errors weergegeven
{
?>
<script>
$("#editProjectSelect").val($('#hidden-input').val());
$('#project-wijzigen').show();
$(this).toggleClass('close');
</script>
<?php
echo validation_errors('<p class="error">');
}
}
// -------------------------- End error checking/displaying
?>
</div>
---------------
$(document).ready(function()
{
$(function()
{
$.ajax(
{
url:"<?php echo site_url("c_admin/ajaxTitels");?>",
type: 'POST',
success: function(msg)
{
var jsonMsg = $.parseJSON(msg);
var count = Object.keys(jsonMsg).length;
for(var x = 0; x < count; x++)
{
$("#projectSelect").append($("<option></option>").val(jsonMsg[x].ProjectID).html(jsonMsg[x].Projecttitel));
$("#delprojectSelect").append($("<option></option>").val(jsonMsg[x].ProjectID).html(jsonMsg[x].Projecttitel));
$("#editprojectSelect").append($("<option></option>").val(jsonMsg[x].ProjectID).html(jsonMsg[x].Projecttitel));
}
}
});
});
})
function getDetails()
{
//$("#editProject").empty();
document.getElementById('editProject').style.display = "none";
$(".error").empty();
var sel = document.getElementById('editprojectSelect');
var opt = sel.options[sel.selectedIndex];
var p = opt.value;
if(p != "")
{
document.getElementById('editProject').style.display = "block";
//$("#editProject").append($("<label></label><br />").html("test"));
$.ajax(
{
url:"<?php echo site_url("c_admin/ajaxProject");?>",
type: 'POST',
data: {project: p},
success: function(msg)
{
var jsonMsg = $.parseJSON(msg);
$('#hoofding').html(jsonMsg.Projecttitel);
document.getElementById("pt").value = jsonMsg.Projecttitel;
document.getElementById("sd").value = jsonMsg.Startdatum;
document.getElementById("ed").value = jsonMsg.Einddatum;
document.getElementById("samen").value = jsonMsg.ISM;
document.getElementById("omschr").value = jsonMsg.Projecttekst;
document.getElementById("hiddenID").value = jsonMsg.ProjectID;
}
});
}
}
$(document).ready(function()
{
$(function()
{
$.ajax(
{
url:"<?php echo site_url("c_admin/ajaxTitels");?>",
type: 'POST',
success: function(msg)
{
var jsonMsg = $.parseJSON(msg);
var count = Object.keys(jsonMsg).length;
for(var x = 0; x < count; x++)
{
$("#projectSelect").append($("<option></option>").val(jsonMsg[x].ProjectID).html(jsonMsg[x].Projecttitel));
$("#delprojectSelect").append($("<option></option>").val(jsonMsg[x].ProjectID).html(jsonMsg[x].Projecttitel));
$("#editprojectSelect").append($("<option></option>").val(jsonMsg[x].ProjectID).html(jsonMsg[x].Projecttitel));
}
}
});
});
if(isset($projectWijzigenError) AND ($projectWijzigenError == true)){
var projectId = '<?php echo set_value('editProjectSelect'); ?>';
//set the select field
$("#editProjectSelect").val(projectId);
//call the getDetails function to populate your fields
getDetails();
}
Your <select> field is not inside the <form> element. So when you submit the form, the field is not submitted and PHP/codeigniter does not know your old value.
What you can do is, put the select field inside the form.
Once your form is submitted and if there are validation errors, do the following:
Get the value of the editprojectSelect, and in $(document).ready part of jquery after the ajax call, set the value of the select to what you got from your form.
After that, call the getDetails() function.

Categories