This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 6 years ago.
I have a select option which is working perfectly but only one time, the request does not executes again.
I think it's because of the 'onchange' event.
This is my ajax code :
jQuery(document).ready(function($) {
$('#referenceProduit').change(function(){
//on recupere la valeur de l'attribut value pour afficher tel ou tel resultat
var req=$('#referenceProduit').val();
//requête ajax, appel du fichier function.php
$.ajax({
type: "POST",
url: "include/php.php",
data: "referenceProduit="+req,
dataType : "json",
//affichage de l'erreur en cas de problème
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest + '--' + textStatus + '--' + errorThrown);
},
//function s'il n'y a pas de probleme
success:function(data){
//On affiche la réponse du serveur
$('.produit').empty();
$('.produit').prepend(data.produit);
$('input[name="designation"]').val(data.resDisplayForm.designation);
$('input[name="prix"]').val(data.resDisplayForm.prix);
}
});
});
});
HTML code :
<div class="form-group">
<label for="referenceProduit" class="col-sm-1 control-label">Reference</label>
<div class="col-sm-2">
<select class="form-control" name="referenceProduit" id="referenceProduit">
<option selected="selected" disabled="disabled">Choisir</option>
<?php foreach($lesProduits as $unProduit){?>
<option name="<?php echo $unProduit['id'];?>" value="<?php echo $unProduit['id'];?>"><?php echo $unProduit['reference']?></option>
<?php } ?>
</select>
</div>
</div>
<div class="form-group">
<div class="produit"></div>
</div><br/><br/>
You should map to
.on(eventType, selector, function)
example
$('#parentElement').on('change', '#referenceProduit', function)
Related
Let's see if you can help me, because I'm stuck because I can't get the ajax instruction to save the data to be executed
I have a modal window in the admin of my wordpress plugin, which I did via thickbox. The code for that modal is:
<p>Por favor, elija la configuración para <b><?php echo($_GET['title']);?></b>:</p>
<form method="post" id="ajax-form">
<label for="tipo">Introduzca el tipo de producto</label>
<select name="tipo" id="tipo">
<option value="Subscripción">Subscripción</option>
<option value="Sesion">Sesion</option>
</select><br><br>
<label for="cantidad">Introduzca el número de sesiones o de meses de subscripción</label>
<input name="cantidad" id="cantidad"></input>
<input id="id" name="id" type="hidden" value="<?php echo($_GET['id']);?>"><br>
<input type="submit">
<script type="text/javascript">
jQuery(document).ready(function(event) {
jQuery('#ajax-form').submit(ajaxSubmit);
function ajaxSubmit() {
var ajaxform = jQuery(this).serialize();
jQuery.ajax({
action: 'grabardatos_desde_modalform',
data: ajaxform,
type: 'POST',
url: '<?php echo admin_url('admin-ajax.php'); ?>',
success: function(data) {
alert("GUAYYYYYY");
}
});
}); }
</script>
</form>
The php code that should process the data is:
add_action('wp_ajax_grabardatos_desde_modalform' , 'grabardatos_desde_modalform');
add_action('wp_ajax_nopriv_grabardatos_desde_modalform','grabardatos_desde_modalform');
function grabardatos_desde_modalform(){
$datos=array(
$_POST['id'] => array(
'cantidad' => $_POST['cantidad'],
'tipo' => $_POST['tipo']
));
error_log(print_r($datos));
update_option('arrayproductos',$datos);
}
But I don't know why the query is not executed, because when I hit send it is as if the modal was reloaded.
On the other hand, I also need that after processing the data the main page is redirected.
Each time I press the button to load the AJAX, I load the start screen with everything (header, menu and footer) apart from not loading the data from the table I request. I get this warning in the console:
[Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check.
I tried to put async: true and also the script at the end of the document, but nothing.
INDEX.PHP
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>Sistema de Administración de Envíos - Pedidos</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script src="js/main.js"></script>
<script src="js/jquery.slim.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/popper.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
</head>
<body>
<?php
require('components/menu.php');
?>
<div class="main">
<div id="top-pedidos">
<div class="input-group mb-2 mr-sm-2 mb-sm-0">
<div class="input-group-addon"><button id="buttonFechaPedido" type="submit"><i class="fa fa-calendar"></i></button></div>
<input type="date" class="form-control" id="inputFechaPedido" name="fecha">
</div>
<div class="input-group mb-2 mr-sm-2 mb-sm-0">
<div class="input-group-addon"><button id="buttonNumeroPedido"><i class="fa fa-search"></i></button></div>
<input type="text" class="form-control" id="inputNumeroPedido" name="npedido" placeholder="Nº pedido">
</div>
<div class="input-group mb-2 mr-sm-2 mb-sm-0">
<div class="input-group-addon"><button id="buttonEstadoPedido"><i class="fa fa-check-square"></i></button></div>
<select class="custom-select mb-2 mr-sm-2 mb-sm-0" id="inputEstadoPedido" name="estado">
<option value="vacio" selected></option>
<option value="Pendiente">Pendiente</option>
<option value="Aceptado">Aceptado</option>
<option value="Rechazado">Rechazado</option>
</select>
</div>
<button class="newPedido btn btn-primary">Nuevo Pedido</button>
</div>
<div class="tables">
<?php
require('sql/sql-pedidos.php');
?>
<div id="tablaPedido">
<p id="emptyFecha" class="mistake red">Debes poner una fecha</p>
<p id="errorFecha" class="mistake red">Ha ocurrido un error con la fecha</p>
<p id="emptyNumero" class="mistake red">Debes poner un número de pedido</p>
<p id="errorNumero" class="mistake red">Ha ocurrido un error con el número de pedido</p>
<p id="emptyEstado" class="mistake red">Debes seleccionar un estado</p>
<p id="errorEstado" class="mistake red">Ha ocurrido un error con el estado</p>
</div>
</div>
</div>
<?php
require('components/footer.php');
?>
</body>
</html>
loadAjax.php
<?php
//Tabla inicial sin parámetros de búsqueda
require('conexionbd.php');
$general = 'SELECT * FROM pedidos';
$result = mysql_query($general) or die('Consulta fallida: ' . mysql_error());
echo "<table class='table table-striped table-pedidos-g'>\n";
echo "<tr class='superior'>
<td>Nº pedido</td>
<td>Fecha</td>
<td>Descuento</td>
<td>Cliente</td>
<td>Estado</td>
</tr>";
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo "\t<tr>\n";
foreach ($line as $col_value) {
echo "\t\t<td>$col_value</td>\n";
}
echo "\t</tr>\n";
}
echo "</table>\n";
?>
<script>
$('#buttonFechaPedido').click(function() {
$('.table-pedidos-g').hide();
$('.table-pedidos-n').hide();
$('.table-pedidos-e').hide();
var valorFecha = $('#inputFechaPedido').val();
if (valorFecha.length == 0){
$('#emptyFecha').removeClass('mistake');
}
else{
$(document).ready(function() {
$.ajax({
data: valorFecha,
url: 'pedidos/pfechas.php',
type: 'post',
beforeSend: function () {
$("#tablaPedido").html("Procesando, espere por favor...");
},
error:function (){
$('#errorFecha').removeClass('mistake');
},
success: function (response) {
$("#tablaPedido").html(response);
}
});
});
}
});
</script>
<script>
$('#buttonNumeroPedido').click(function() {
$('.table-pedidos-g').hide();
$('.table-pedidos-f').hide();
$('.table-pedidos-e').hide();
var valorNumero =$('#inputNumeroPedido').val();
if (valorNumero.length == 0){
$('#emptyNumero').removeClass('mistake');
}
else{
$(document).ready(function() {
$.ajax({
data: valorNumero,
url: 'pedidos/pnumero.php',
type: 'post',
beforeSend: function () {
$("#tablaPedido").html("Procesando, espere por favor...");
},
error:function (){
$('#errorNumero').removeClass('mistake');
},
success: function (response) {
$("#tablaPedido").html(response);
}
});
});
}
});
</script>
<script>
$('#buttonEstadoPedido').click(function() {
$('.table-pedidos-g').hide();
$('.table-pedidos-n').hide();
$('.table-pedidos-f').hide();
var valorEstado =$('#inputEstadoPedido').val();
if (valorEstado == 'vacio'){
$('#emptyEstado').removeClass('mistake');
}
else{
$(document).ready(function() {
$.ajax({
data: valorEstado,
url: 'pedidos/pestado.php',
type: 'post',
beforeSend: function () {
$("#tablaPedido").html("Procesando, espere por favor...");
},
error:function (){
$('#errorEstado').removeClass('mistake');
},
success: function (response) {
$("#tablaPedido").html(response);
}
});
});
}
});
</script>
pfechas.php
<?php
require('../conexionbd.php');
// Realizar una consulta MySQL
$fechas = 'SELECT * FROM pedidos WHERE fecha_pdo = $_POST["valorFecha"]';
$result = mysql_query($fechas) or die('Consulta fallida: ' . mysql_error());
// Imprimir los resultados en HTML
echo "<table class='table table-striped table-pedidos-f'>\n";
echo "<tr class='superior'>
<td>Nº pedido</td>
<td>Fecha</td>
<td>Descuento</td>
<td>Cliente</td>
<td>Estado</td>
</tr>";
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo "\t<tr>\n";
foreach ($line as $col_value) {
echo "\t\t<td>$col_value</td>\n";
}
echo "\t</tr>\n";
}
echo "</table>\n";
// Liberar resultados
mysql_free_result($result);
// Cerrar la conexión
mysql_close($link);
?>
pnumero.php
<?php
require('../conexionbd.php');
// Realizar una consulta MySQL
$numeros = 'SELECT * FROM pedidos WHERE numero_pdo = $_POST["valorNumero"]';
$result = mysql_query($fnumeros) or die('Consulta fallida: ' . mysql_error());
// Imprimir los resultados en HTML
echo "<table class='table table-striped table-pedidos-n'>\n";
echo "<tr class='superior'>
<td>Nº pedido</td>
<td>Fecha</td>
<td>Descuento</td>
<td>Cliente</td>
<td>Estado</td>
</tr>";
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo "\t<tr>\n";
foreach ($line as $col_value) {
echo "\t\t<td>$col_value</td>\n";
}
echo "\t</tr>\n";
}
echo "</table>\n";
// Liberar resultados
mysql_free_result($result);
// Cerrar la conexión
mysql_close($link);
?>
pestado.php
<?php
require('../conexionbd.php');
// Realizar una consulta MySQL
$estados = 'SELECT * FROM pedidos WHERE estado = $_POST["valorEstado"]';
$result = mysql_query($estados) or die('Consulta fallida: ' . mysql_error());
// Imprimir los resultados en HTML
echo "<table class='table table-striped table-pedidos-e'>\n";
echo "<tr class='superior'>
<td>Nº pedido</td>
<td>Fecha</td>
<td>Descuento</td>
<td>Cliente</td>
<td>Estado</td>
</tr>";
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo "\t<tr>\n";
foreach ($line as $col_value) {
echo "\t\t<td>$col_value</td>\n";
}
echo "\t</tr>\n";
}
echo "</table>\n";
// Liberar resultados
mysql_free_result($result);
// Cerrar la conexión
mysql_close($link);
?>
Good morning.
I'm stucked on this thing:
I'm doing a form (which send info to other page via submit button, post) which dynamically user can add some other form-groups with a button.
Ok, that's easy.
BUT the user is making something called "DPT" (work stuff) which have a table in my DB, and also have a "Function" (things to do) table. A DPT can have one or many Functions.
Function
---------
id int(4) AI
title VARCHAR(64) NOT NULL
description VARCHAR(256)
dpt int(4) --> FK
| 1..*
|
V 1
DPT
-----
id
name
(...)
So I have a <div> which I inflate with jQuery for making a panel and form inside it.
Why I did that? Because if a DPT can have one or many Functions I have to store the ID of the current Function I am creating.
Then I have a button for adding more functions, but I have to storage the ID of the function and the title and description of it.
So with jQuery I can dynamically add before the button of "Add function" a new form...
My idea was create a JSON and send it via PHP but have no idea where I have to send the info or where to return to...
I let you here my important code for doing the thing:
<div id="initialFunction" class="panel panel-default panel-body">
<?php
$nextID = mysqli_fetch_assoc(mysqli_query($con,"SELECT MAX(id_funcion) as siguiente_id from funcion"))['siguiente_id'];
?>
<button class="button btn-danger" type="button">
<span class="fa fa-minus">
</span>
</button>
</div>
<script>
var nextId = <?php echo $nextID?>
var arrayToPass = {}
$(function(){
$("#initialFunction").html('<div class="form-group">'+
'<label>Función a desarrollar <sup style="color:red">*</sup></label>'+
'<input class="form-control" name="funcion" type="text" placeholder="Función a desarrollar" maxlength="200" required>'+
'</div>'+
'<div class="form-group">'+
'<label>Tarea principal en esta función <sup style="color:red">*</sup></label>'+
'<textarea class="form-control" name="tarea" placeholder="Enumere las funciones de su puesto de trabajo comenzando por las más representativas, así como las tareas necesarias para el cumplimiento de las mismas" rows="3" required></textarea>'+
'</div>');
});
$("#bttn-add").click(function(){
$("#bttn-add-function").before(
'<div class="form-group">'+
'<label>Función a desarrollar <sup style="color:red">*</sup></label>'+
'<input class="form-control" name="funcion" type="text" placeholder="Función a desarrollar" maxlength="200" required>'+
'</div>'+
'<div class="form-group">'+
'<label>Tarea principal en esta función <sup style="color:red">*</sup></label>'+
'<textarea class="form-control" name="tarea" placeholder="Enumere las funciones de su puesto de trabajo comenzando por las más representativas, así como las tareas necesarias para el cumplimiento de las mismas" rows="3" required></textarea>'+
'</div>');
nextId++;
});
Can I return an array/json when I do click on the submit button and pass it through POST?
something like:
$("#guardar_dpt").click(function(){
return json_object
} )
?
I show you a what I am doing.
also the entire form:
It is possible. And simple. Here is example:
HTML:
<script src="https://unpkg.com/jquery"></script>
<form id="myForm" method="post">
<input type="text" name="first"><br>
<input type="text" name="last"><br>
<input type="submit" value="Send">
</form>
<p id="output"></p>
JS:
function parseAnswer (data) {
var content
content += 'Name: ' + data.first + '<br>'
content += 'Surname: ' + data.last
$('#output').text(Name)
}
$('#myForm').on( "submit", function (evt) {
var data = $(this).serialize()
evt.preventDefault()
$.post('any.php', data, parseAnswer)
})
PHP:
<?php
header("Content-type: application/json");
$first = $_POST['first'];
$last = $_POST['last'];
$arr = ['first' => $first, 'last' => $last];
echo json_encode($arr);
?>
I have one problem with my ajax code. It is called more than once. My php code is next :
(While loop where I get all results from a database. I pasted only a modal and a dropdown menu because everything else works fine)
$rezPet = mysqli_query($kon, "SELECT * FROM pets WHERE user_id = ". $userId ." ORDER BY id DESC");
while($redPet = mysqli_fetch_assoc($rezPet)){
......
<div id=\"confirmBox-". $redPet["id"] ."\" class=\"modal fade bs-example-modal-xs\" tabindex=\"-1\" role=\"dialog\" aria-labelledby=\"mySmallModalLabel\">
<div class=\"modal-dialog modal-sm\">
<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>
<h4 class=\"modal-title\" id=\"myModalLabel\"><b>". $redPet["name"] ."</b> is gevonden?</h4>
</div>
<div class=\"modal-body\">
Bent u zeker dat <b>". $redPet["name"] ."</b> gevonden is?
</div>
<div class=\"modal-footer\">
<button id=\"btnFoundCancel-". $redPet["id"] ."\" type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\"><i class=\"fa fa-ban\"></i> Cancel</button>
<button id=\"btnFoundConfirm-". $redPet["id"] ."\" type=\"button\" class=\"btn btn-primary\" data-dismiss=\"modal\"><i class=\"fa fa-floppy-o\"></i> Ja! Ga verder</button>
</div>
</div>
</div>
</div>
.
.
.
<div id=\"dropdown-". $redPet["id"] ."\" class=\"col-md-6 col-xs-12\" style=\"padding-right:10px;z-index:99999999;". $showHideDropdown ."\">
<!-- Split button -->
<div class=\"btn-group pull-right\">
<button type=\"button\" id=\"dataTitle\" data-title=\"Beheer informatie over uw dier\" class=\"btn btn-success btn-xs\"><i class=\"fa fa-pencil-square-o\"></i></button>
<button type=\"button\" id=\"dataTitle\" data-title=\"Beheer informatie over uw dier\" class=\"btn btn-success btn-xs dropdown-toggle\" data-toggle=\"dropdown\" aria-haspopup=\"true\" aria-expanded=\"false\">
<span class=\"caret\" style=\"margin-top:0;\"></span>
<span class=\"sr-only\">Toggle Dropdown</span>
</button>
<ul id=\"drpDown-". $redPet["id"] ."\" class=\"dropdown-menu\">
<li class=\"col-lg-12\">
<button id=\"dataTitle btnFound-". $redPet["id"] ."\" class=\"btnFound btn btn-success col-lg-12 col-sm-12 col-md-12 col-xs-12 btn-sm\" data-title=\"Klik hier als uw dier gevonden is\" data-target=\"#confirmBox-". $redPet["id"] ."\" data-toggle=\"modal\"><i class=\"fa fa-home\"></i> Gevonden</button>
</li>
<div style=\"clear:both;\"></div><li role=\"separator\" class=\"divide5\"></li>
<li class=\"col-lg-12\">
<form action=\"dier-toevoegen.php\" method=\"POST\">
<input type=\"hidden\" name=\"changeID\" value=\"". $redPet["id"] ."\">
<button id=\"dataTitle\" class=\"btn btn-info col-lg-12 col-sm-12 col-md-12 col-xs-12 btn-sm\" data-title=\"Klik hier om de informatie over uw dier te wijzigen\" type=\"submit\"><i class=\"fa fa-pencil\"></i> Wijzigen</button>
</form>
</li>
<div style=\"clear:both;\"></div>
<li role=\"separator\" class=\"divider\"></li>
<li class=\"col-lg-12\">
<button id=\"dataTitle btnVerwijderen-". $redPet["id"] ."\" class=\"linkDelete btn btn-danger col-lg-12 col-sm-12 col-md-12 col-xs-12 btn-sm\" data-title=\"Klik hier om uw dier te verwijderen\" href=\"#\"><i class=\"fa fa-trash\"></i> Verwijderen</button>
</li>
</ul>
</div>
</div>
}
My ajax code is next :
(First ajax code, where I update database field found to value 1, it works fine, the only problem is because it has been call more the once)
<script type="text/javascript">
$(document).ready(function() {
$(document).on("click","button[class*=btnFound]", function(e){
var cijeliID = this.id.split("-");
var id = cijeliID[1];
$($("#confirmBox-"+id).data("target")).fadeIn(400);
$(document).on("click", "#btnFoundConfirm-"+id, function(){
/*$("#confirmBox-"+id).modal('toggle');*/
$.ajax({
url : "pet-found.php",
type: "POST",
dataType: "json",
data : {id : id, status:"found", sessionCode : "<?php echo $session_code; ?>"},
beforeSend: function(){
$("#info-middle-register").show();
},
success: function(msg){
$("#info-middle-register").hide();
if(msg.result == "Found"){
$("#delpetsuccess-"+id).html("<i class=\"fa fa-thumbs-o-up\"></i> Uw huisdier is thuis. De VermisteDieren site wenst u veel plezier met uw beestje.").fadeIn(300).fadeOut(10000);
$("#watermark-"+id).show();
$("#drpDown-"+id).html("<li id=\"liTochGezocht-"+id+"\" class=\"col-lg-12\"><button id=\"dataTitle btnNotFound-"+id+"\" class=\"btnNotFound btn btn-primary col-lg-12 xol-sm-12 col-md-12 col-xs-12 btn-sm\" data-title=\"Klik hier als uw beestje toch nog niet gevonden is.\"><i class=\"fa fa-arrow-left\"></i> Toch nog gezocht?</button></li>");
$("#dier-"+id).addClass("opacityClass");
}else{
if(msg.result == "NotFound"){
$("#delpeterror-"+id).html("<i class=\"fa fa-exclamation-triangle\"></i> Er is iets misgelopen. Contacteer ons via info#vermistedieren.be.").fadeIn(300).fadeOut(10000);
}
}
},
error: function(){
$("#info-middle-register").hide();
$("#delpeterror-"+id).html("<i class=\"fa fa-exclamation-triangle\"></i> Er is iets misgelopen. Contacteer ons via info#vermistedieren.be.").fadeIn(300).fadeOut(10000);
}
})
});
e.preventDefault();
});
});
</script>
(Second code, where I update database field found to value 0)
<!-- Ako klikne na go back kada je zivotinja oznacena kao pronadjena -->
<script type="text/javascript">
$(document).ready(function() {
$(document).on("click","button[class*=btnNotFound]", function(e){
var cijeliID = this.id.split("-");
var id = cijeliID[1];
$.ajax({
url : "pet-found.php",
type: "POST",
dataType: "json",
data : {id : id, status:"notFound", sessionCode : "<?php echo $session_code; ?>"},
beforeSend: function(){
$("#info-middle-register").show();
},
success: function(msg){
$("#info-middle-register").hide();
if(msg.result == "changeMindNotFound"){
$("#watermark-"+id).hide();
$("#dier-"+id).removeClass("opacityClass");
$("#txtFound-"+id).hide();
$("#liTochGezocht-"+id).hide();
$("#drpDown-"+id).html("<li class=\"col-lg-12\"><button id=\"dataTitle btnFound-"+id+"\" class=\"btnFound btn btn-success col-lg-12 col-sm-12 col-md-12 col-xs-12 btn-sm\" data-title=\"Klik hier als uw dier gevonden is\" data-target=\"#confirmBox-"+id+"\" data-toggle=\"modal\"><i class=\"fa fa-home\"></i> Gevonden</button></li><div style=\"clear:both;\"></div><li role=\"separator\" class=\"divide5\"></li><li class=\"col-lg-12\"><form action=\"dier-toevoegen.php\" method=\"POST\"><input type=\"hidden\" name=\"changeID\" value=\""+id+"\"><button id=\"dataTitle\" class=\"btn btn-info col-lg-12 col-sm-12 col-md-12 col-xs-12 btn-sm\" data-title=\"Klik hier om de informatie over uw dier te wijzigen\" type=\"submit\"><i class=\"fa fa-pencil\"></i> Wijzigen</button></form></li><div style=\"clear:both;\"></div><li role=\"separator\" class=\"divider\"></li> <li class=\"col-lg-12\"><button id=\"dataTitle btnVerwijderen-"+id+"\" class=\"linkDelete btn btn-danger col-lg-12 col-sm-12 col-md-12 col-xs-12 btn-sm\" data-title=\"Klik hier om uw dier te verwijderen\" href=\"#\"><i class=\"fa fa-trash\"></i> Verwijderen</button></li>");
}else{
if(msg.result == "changeMindFound"){
$("#delpeterror-"+id).html("<i class=\"fa fa-exclamation-triangle\"></i> Er is iets misgelopen. Contacteer ons via info#vermistedieren.be.").fadeIn(300).fadeOut(10000);
}
}
},
error: function(){
$("#info-middle-register").hide();
$("#delpeterror-"+id).html("<i class=\"fa fa-exclamation-triangle\"></i> Er is iets misgelopen. Contacteer ons via info#vermistedieren.be.").fadeIn(300).fadeOut(10000);
}
})
});
});
</script>
When the page loads first time, if I click on "Gevonden" button, than is everything perfect. The first ajax code is called once and it is ok.
But than are the list items of a dropmenu changed to only one button ("toch nog gezoch"). If I click on it, than is second ajax code called and it does what it need to do.
Then are the list items in a dropdown menu changed again to the first three buttons (Gevonden, Wijzigen, Verwijderen). And than I get a problem. When I then click on gevonden button, the first ajax code is called two times. And every next try is the first ajax code called one time more.
Any syggestions? Thanks in advance.
try this :)
<script type="text/javascript">
$(document).ready(function() {
$(document).on("click","button[class*=btnNotFound]", function(e){
// add this around
if (e.handled !== true) {
e.handled = true; // prevent firing two times
// your code
}
I had the same problem on a project I am working and this is how I solved it (this is actual code sample from the project):
$(document).ajaxComplete(function () {
var didItRun = false; //I'm using this boolean to check if I already ran this code.
$('#filterForm2GoodsReceived input').change(function () {
if(didItRun == false)
{
$.ajax({
type: "GET",
url: "/Receiving/List/",
data: $('#filterForm2GoodsReceived').serialize(),
success: function (response) {
$('#listReceivingOrders').html(response);
return false;
}
})
didItRun = true;
}
})
})
I have a solution. I separated one click event of another as #JamesThorpe said.
<script type="text/javascript">
$(document).ready(function() {
$(document).on("click","button[class*=btnFound]", function(e){
var cijeliID = this.id.split("-");
var id = cijeliID[1];
$($("#confirmBox-"+id).data("target")).fadeIn(400);
e.preventDefault();
});
});
</script>
<script type="text/javascript">
$(document).ready(function() {
$(document).on("click", ".btnFoundConfirm", function(){
var cijeliID = this.id.split("-");
var id = cijeliID[1];
/*$("#confirmBox-"+id).modal('toggle');*/
$.ajax({
url : "pet-found.php",
type: "POST",
dataType: "json",
data : {id : id, status:"found", sessionCode : "<?php echo $session_code; ?>"},
beforeSend: function(){
$("#info-middle-register").show();
},
success: function(msg){
$("#info-middle-register").hide();
if(msg.result == "Found"){
$("#delpetsuccess-"+id).html("<i class=\"fa fa-thumbs-o-up\"></i> Uw huisdier is thuis. De VermisteDieren site wenst u veel plezier met uw beestje.").fadeIn(300).fadeOut(10000);
$("#watermark-"+id).show();
$("#drpDown-"+id).html("<li id=\"liTochGezocht-"+id+"\" class=\"col-lg-12\"><button id=\"dataTitle btnNotFound-"+id+"\" class=\"btnNotFound btn btn-primary col-lg-12 xol-sm-12 col-md-12 col-xs-12 btn-sm\" data-title=\"Klik hier als uw beestje toch nog niet gevonden is.\"><i class=\"fa fa-arrow-left\"></i> Toch nog gezocht?</button></li>");
$("#dier-"+id).addClass("opacityClass");
}else{
if(msg.result == "NotFound"){
$("#delpeterror-"+id).html("<i class=\"fa fa-exclamation-triangle\"></i> Er is iets misgelopen. Contacteer ons via info#vermistedieren.be.").fadeIn(300).fadeOut(10000);
}
}
},
error: function(){
$("#info-middle-register").hide();
$("#delpeterror-"+id).html("<i class=\"fa fa-exclamation-triangle\"></i> Er is iets misgelopen. Contacteer ons via info#vermistedieren.be.").fadeIn(300).fadeOut(10000);
}
})
});
});
</script>
And in a modal button (Ja! Ga verder) I added a class btnFoundConfirm and it worked.
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.