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?
Related
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>
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+"¬e="+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();
?>
im have an autocomplete function searching in database field (name).
If my field = john, and i typing "joh" autocomplete works fine.
But
If my field = john marshall, and i typing "joh" or anything, autocomplete doesn't work.
Any ideas? Thanks so much.
my code:
index.php
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js"></script>
<link href="css/jqueryui.css" type="text/css" rel="stylesheet"/>
<script>
$(document).ready(function(){
$( "#matricula" ).autocomplete({
source: "searchalumno.php",
minLength: 2
});
$("#matricula").focusout(function(){
$.ajax({
url:'alumno.php',
type:'POST',
dataType:'json',
data:{ matricula:$('#matricula')}
}).done(function(respuesta){
$("#nombre").val(respuesta.nombre);
$("#paterno").val(respuesta.paterno);
$("#materno").val(respuesta.materno);
});
});
});
</script>
</head>
<body>
<form>
<label for="matricula">Matricula:</label>
<input type="text" id="matricula" name="matricula" value=""/>
<label for="nombre">Nombre:</label>
<input type="text" id="nombre" name="nombre" value=""/>
<label for="paterno">Paterno:</label>
<input type="text" id="paterno" name="paterno" value=""/>
<label for="materno">Materno:</label>
<input type="text" id="materno" name="materno" value=""/>
</form>
</body>
alumno.php:
<?php
$conexion = new mysqli('servidor','usuario','password','basedatos',3306);
$matricula = $_POST['matricula'];
$consulta = "select nombre, paterno, materno FROM tblalumno WHERE matricula = '$matricula'";
$result = $conexion->query($consulta);
$respuesta = new stdClass();
if($result->num_rows > 0){
$fila = $result->fetch_array();
$respuesta->nombre = $fila['nombre'];
$respuesta->paterno = $fila['paterno'];
$respuesta->materno = $fila['materno'];
}
echo json_encode($respuesta);
?>
searchalumno:
<?php
$conexion = new mysqli('servidor','usuario','password','basedatos',3306);
$matricula = $_GET['term'];
$consulta = "select matricula FROM tblalumno WHERE matricula LIKE '%$matricula%'";
$result = $conexion->query($consulta);
if($result->num_rows > 0){
while($fila = $result->fetch_array()){
$matriculas[] = $fila['matricula'];
}
echo json_encode($matriculas);
}
?>
In your ajax request, use input value instead of input object:
$.ajax({ ... data:{ matricula: $('#matricula').val() } })
I build a search feature with infinite scroll. How do i get search string from search page to my scroll page for query database.
PHP :
search.php
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="style/css/scroll.css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<link href="css/search.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="search">
<form action="search" method="post">
<input type="text" name="search" id="search" autocomplete="off">
<button type="submit" class="btn btn-primary">Search</button>
</form>
</div>
<img id='loading' src='img/loading.gif'>
<div id="demoajax" cellspacing="0">
</div>
</body>
<script type="text/javascript" src="js/infinitescroll/search.js"></script>
scroll.php
<?php
include('db.php');
$searchstring = $_POST['search'];
if(isset($_REQUEST['actionfunction']) && $_REQUEST['actionfunction']!=''){
$actionfunction = $_REQUEST['actionfunction'];
call_user_func($actionfunction,$_REQUEST,$con,$limit);
}
function showData($data,$con,$limit){
$page = $data['page'];
if($page==1){
$start = 0;
}
else{
$start = ($page-1)*$limit;
}
$sql = "SELECT fm_product.p_name, fm_product.p_descp, fm_product.p_id, fm_product.p_price, fm_product.p_discount, fm_product.p_img, fm_member.member_display_name, fm_product.p_member_id, fm_package.package_name, fm_package.package_id FROM fm_member LEFT JOIN fm_product ON fm_member.member_id = fm_product.p_member_id LEFT JOIN fm_package ON fm_member.package_id = fm_package.package_id order by p_created_date desc limit $start,$limit";
$str='';
$data = $con->query($sql);
if($data!=null && $data->num_rows>0) {
while( $row = $data->fetch_array(MYSQLI_ASSOC)){
if($row['package_id']=='1'){
$package = "No Package";
} else {
$package = "<form class='form-item'><input name='product_code' type='hidden' value='".$row['p_id']."'><button type='submit'>Add to Cart</button></input></form>";
}
$id = $row['p_id'];
$str.="<div style=align: center class='data-container'><a href=item?id = $id><img src=upload/".$row['p_img']." width=300px style=max-width:100%; height: auto; vertical-align: middle></a><p>By ".$row['member_display_name']."</p><p>Product Name : ".$row['p_name']."</p><p>Price : ".$row['p_price']."</p><p>Discount : ".$row['p_discount']."</p><p>Description : ".$row['p_descp']."</p><p>Package ".$_POST['search']." : ".$row['package_name']."</p><p>".$package."</p></div>";
}
$str.="<input type='hidden' class='nextpage' value='".($page+1)."'><input type='hidden' class='isload' value='true'>";
} else {
$str .= "<input type='hidden' class='isload' value='false'><p>Finished</p>";
}
echo $str;
}
?>
Javascript :
search.js
var ajax_arry=[];
var ajax_index =0;
var sctp = 100;
$(function(){
$('#loading').show();
$.ajax({
url:"scroll.php",
type:"POST",
data:"actionfunction=showData&page=1",
cache: false,
success: function(response){
$('#loading').hide();
$('#demoajax').html(response);
}
});
$(window).scroll(function(){
var height = $('#demoajax').height();
var scroll_top = $(this).scrollTop();
if(ajax_arry.length>0){
$('#loading').hide();
for(var i=0;i<ajax_arry.length;i++){
ajax_arry[i].abort();
}
}
var page = $('#demoajax').find('.nextpage').val();
var isload = $('#demoajax').find('.isload').val();
if ((($(window).scrollTop()+document.body.clientHeight)==$(window).height()) && isload=='true'){
$('#loading').show();
var ajaxreq = $.ajax({
url:"scroll.php",
type:"POST",
data:"actionfunction=showData&page="+page,
cache: false,
success: function(response){
$('#demoajax').find('.nextpage').remove();
$('#demoajax').find('.isload').remove();
$('#loading').hide();
$('#demoajax').append(response);
}
});
ajax_arry[ajax_index++]= ajaxreq;
}
return false;
if($(window).scrollTop() == $(window).height()) {
alert("bottom!");
}
});
});
I want to get $_POST['search'] from search.php to scroll.php for replace it into WHERE on this query like.
$sql = "SELECT ... FROM ... LEFT JOIN ... ON ... LEFT JOIN ... ON ... WHERE p_name LIKE '%$_POST['search']' ORDER BY ... LIMIT ..."
Appreciated.
<form action="search" method="post">
This redirects to /search page, which you don't have. You have /search.php and /scroll.php. I think you should just put scroll.php as the action, and you'd get your result.
<form action="scroll.php" method="post">
EDIT:
I seem to have misunderstood the code. scroll.php is an API endpoint in this. Then the action remains search.php, BUT, in order to have the submitted values, you can kill 2 birds with 1 stone.
Update the form HTML (you don't need action, you don't need the form either, but let's keep it):
<form action="" method="post">
<input type="text" name="search" id="search" autocomplete="off">
<button type="button" id="do_search" class="btn btn-primary">Search</button>
</form>
In your JS, make the function get triggered by the search:
jQuery(document).ready(function($) {
$("#do_search").on("click", function() {
var searchTerm = $("#search").val();
//this is where you do the AJAX stuff. You can use searchTerm variable.
});
});
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.