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.
Related
When I click the button to submit the form it sends me to the PHP file (Php/modify-recipes.php). I'm using AJAX with e.preventDefault();, but it doesn't seem to work. I have a similar form on my other page and it works fine. This one is a little bit different, the form is generated from another PHP file (it takes values from the database).
// AJAX (in HTML head tag)
<script>
$(function () {
$("#search-form").on('click', 'p.product', function(e){
var product = $(this).attr('id');
e.preventDefault();
$.ajax({
type: "post",
url: 'Php/display-modify-recipes.php',
data: { "id": product },
success: function(response) {
$(".modify-recipes").html(response);
$(".search-results").html("");
}
});
}
)});
$(function () {
$('#add_recipes_form').on('click', '#add', function (e) {
e.preventDefault();
let sendForm = true;
$('.required').each(function(){
if ($(this).val() == ''){
$(this).addClass('error', 4000);
$('#placeholder-text').html("Fill in the form");
$('#placeholder-text').addClass('error');
$('#add').addClass('error', 4000);
sendForm = false;
} else {
$(this).removeClass('error');
$('#placeholder-text').removeClass('error');
$('#add').removeClass('error');
}
})
$('.required2').each(function(){
if ($(this).val() == ''){
$('#placeholder-text').html("Fill in the form");
$('#placeholder-text').addClass('error');
$('#add').addClass('error');
$('#file_style').addClass('error');
sendForm = false;
} else {
$('#file_style').removeClass('error');
$('#placeholder-text').removeClass('error');
$('#add').removeClass('error');
}
})
if (sendForm) {
$.ajax({
type: "post",
url: 'Php/modify-recipes.php',
data: new FormData(this),
processData: false,
contentType: false,
success: function () {
},
error: function () {
}
});
}
});
});
</script>
// HTML
<form method="POST" enctype='multipart/form-data' id="search-form" class="aaa">
<input type="text" name="search-bar" class="search-bar" placeholder="Search">
<div class="search-results"></div>
</form>
<div class="modify-recipes"></div>
// Php/display-modify-recipes.php
<?php
function display_mod_form(){
$con = mysqli_connect("localhost", "root", "", "cookbook");
$product = $_POST["id"];
$sql = "SELECT * FROM product WHERE id = '$product'";
$res = mysqli_query($con,$sql);
while($row = mysqli_fetch_assoc($res)) {
$id = $row['id'];
$name = $row['name'];
$description = $row['description'];
$type = $row['type'];
$difficulty = $row['difficulty'];
$image = $row['image'];
?>
<form method="POST" action="Php/modify-recipes.php" enctype="multipart/form-data" id="add_recipes_form" class="add-form">
<input type="text" name="id" id="<?php echo $id ?>" value="<?php echo $id ?>" style="display:none;">
<label for="name">Name</label>
<input type="text" name="name" id="name" class="required" maxlength="28" value='<?php echo $name ?>'>
<label for="description">Desc.</label>
<input type="text" name="description" id="description" class="required" maxlength="128" value='<?php echo $description ?>'>
<label for="type">Type</label>
<select name="type" class="required">
<option value="dishes" <?php if($type == 'dishes') {echo "selected=selected"; } ?>>
Dishes
</option>
<option value="desserts" <?php if($type == 'desserts') {echo "selected=selected"; } ?>>
Desserts
</option>
<option value="snacks" <?php if($type == 'snacks') {echo "selected=selected"; } ?>>
Snacks
</option>
<option value="other" <?php if($type == 'other') {echo "selected=selected"; } ?>>
Other
</option>
</select>
<label for="difficulty">Difficulty</label>
<select name="difficulty" class="required">
<option value="easy" <?php if($difficulty == 'easy') {echo "selected=selected"; } ?>>
Ease
</option>
<option value="moderate" <?php if($difficulty == 'moderate') {echo "selected=selected"; } ?>>
Moderate
</option>
<option value="hard" <?php if($difficulty == 'hard') {echo "selected=selected"; } ?>>
Hard
</option>
</select>
<label for="image">Image (jpg, png)</label>
<label for="upload_image" id="file_style">Choose image</label>
<input type="file" style="display:none;" id="upload_image" name="image" accept="image/*" onchange="loadFile(event)" class="required2">
<div class="send-btn">
<p id="placeholder-text"></p>
<input type="submit" name="add" id="add" value="Send">
<div class="send-block"></div>
</div>
</form>
<?php
}
mysqli_close($con);
}
display_mod_form();
?>
// Php/modify-recipes.php
<?php
$con = mysqli_connect("localhost", "root", "", "cookbook");
$id = $_POST["id"];
$name = $_POST["name"];
$description = $_POST["description"];
$type = $_POST["type"];
$difficulty = $_POST["difficulty"];
if ($_FILES['image']['name'] == ""){
$sql_var = "SELECT image FROM product where id = '$id'";
$var = mysqli_query($con,$sql_var);
while($row = mysqli_fetch_assoc($var)) {
$image = $row['image'];
}
} else {
$image = $_FILES['image']['name'];
}
$sql = "
UPDATE product SET
name = '$name',
description = '$description',
type = '$type',
difficulty = '$difficulty',
image = '$image',
last_mod_date = '$mod_date'
WHERE id = '$id';
";
$target = "../Uploads/".basename($image);
if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
}
$var = mysqli_multi_query($con,$sql); <!-- There are more queries -->
mysqli_close($con);
?>
(Sorry for any mistakes, it's a shortened version)
There is a third ajax function and PHP file, but it's not important (simple search bar). I tried other things like action="", no action at all, etc., but it didn't work.
How to fix this?
Edit: There is only one form (when you click on p.product it displays the form according to the data in the database). The problem occurs ONLY when I'm submitting the "add_recipes_form", there is no problem with the search box. Please don't mark this question as a duplicate of a 10 year old post that is irrelevant to my problem.
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();
?>
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?
I'm trying to make an ajax request with jquery/codeigniter. Well, there seems to be a problem. i do get it to work, but it seems like the POST is not sent, for some reason...
Javascript
$('#profileUpdateButton').click(function() {
$.ajax({ // Starter Ajax Call
method: "POST",
url: baseurl + 'profile/statusUpdate',
data: $('#statusUpdateForm').serialize(),
success: function(data) {
alert(data);
}
});
return false;
});
From the codeigniter controller
if($this->input->is_ajax_request()) {
echo $this->input->post('profileUpdate');
}
If i replace the "echo $this->" etc.. with just echo "Hello" i do get an alertbox with "Hello", why don't i get the text from the box?
html
<div id="statusUpdate">
<?php echo form_open(base_url() . 'profile/statusUpdate', array('name' => 'statusUpdateForm')); ?>
<input type="text" value="Hva tenker du på?" name="profileUpdate" id="profileUpdate" onfocus="if(this.value == 'Hva tenker du på?')this.value=''" onblur="if(this.value == '')this.value='Hva tenker du på?'" />
<input type="submit" value="" name="profileUpdateButton" id="profileUpdateButton" />
<?php echo form_close(); ?>
</div>
Change your html markup to this...
<div id="statusUpdate"> <!-- Use ID not NAME here |v| -->
<?php echo form_open(base_url() . 'profile/statusUpdate', array('id' => 'statusUpdateForm')); ?>
<input type="text" value="Hva tenker du på?" name="profileUpdate" id="profileUpdate" onfocus="if(this.value == 'Hva tenker du på?')this.value=''" onblur="if(this.value == '')this.value='Hva tenker du på?'" />
<input type="submit" value="" name="profileUpdateButton" id="profileUpdateButton" />
<?php echo form_close(); ?>
</div>
you were setting the form's name and you were selecting $('#statusUpdateForm') which means the id of statusUpdateForm, not the name attribute...