Think i'm lost in my code... can't figure out the problem. I have a modal that opens different forms, setting name and id on the form and submit button accordingly, but nothing happens when pressing submit button. My javascript knowledge is limited and based on try and fail and try and fail and try and sometimes achieving results :)
Back to the issue here... The modal opens fine but nothing happens when hitting submit... Nothing visible to me at least...
Hope i have explained my problems ok.
This calls the modal
<span class="stedModal" data-type="sted" title="Legg til sted" style="cursor: pointer"> <i class="fas fa-plus"></i></span>
The modal:
<!-- Modal - Legg til sted -->
<div class="modal fade" id="Modal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Legg til sted</h4>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<!-- name and id is set to sendStedForm in the script that calls the modal -->
<form action="javascript: void(0)" name="none" id="none" class="modalForm">
<div class="main"></div>
<!-- addSted.php is inserted here -->
<div class="text-end">
<!-- button name and id is set by the script that calls the modal to submitSted -->
<button type="submit" name="none1" id="none1" class="btn btn-sm btn-info submitButton" ><i class="far fa-trash-alt"></i> Lagre</button>
<button type="button" class="btn btn-sm btn-success" data-bs-dismiss="modal" aria-label="Close"><i class="fas fa-times"></i> Lukk</button>
</div>
</form>
</div>
</div>
</div>
</div>
calls addSted.php
<input type="hidden" name="lag_id" id="slag_id" value="<?= session()->get('lag_id'); ?>">
<div class="container">
<div class="row">
<div class="col">
<div class="form-group">
<label for="sted">Sted<span class="text-danger fw-bold">*</span></label>
<input type="text" name="sted" id="ssted" class="form-control required" placeholder="Sted">
</div>
</div>
</div>
<div class="row">
<div class="col">
<div class="form-group">
<label for="oppmote">Oppmøte<span class="text-danger fw-bold">*</span></label>
<input type="text" name="oppmote" id="soppmote" class="form-control" placeholder="Oppmøtested">
</div>
</div>
</div>
<div class="row mb-3">
<div class="col">
<div class="form-group">
<label for="sted">Oppmøte tid<span class="text-danger fw-bold">*</span><small class="text-muted">Timer før oppdrag starter</small></label>
<input type="text" name="oppmote_tid" id="soppmote_tid" class="form-control" placeholder="Oppmøte tid">
</div>
</div>
</div>
</div>
The scripts
<script>
function goBack() {
window.history.back();
}
$('#alert').hide();
$('.stedModal').click(function() {
var typet = $(this).data('type');
if (typet == 'type') {
var url = '/vakter/ajaxAddType';
$('.modalForm').attr('id', 'sendTypeForm');
$('.modalForm').attr('name', 'sendTypeForm');
$('.submitButton').attr('id', 'submitType');
$('.submitButton').attr('name', 'submitType');
$('.modal-title').html('Legg til Type');
} else if (typet == 'sted') {
var url = '/vakter/ajaxAddSted';
$('.modalForm').attr('id', 'sendStedForm');
$('.modalForm').attr('name', 'sendStedForm');
$('.submitButton').attr('id', 'submitSted');
$('.submitButton').attr('name', 'submitSted');
$('.modal-title').html('Legg til Sted');
}
// AJAX request
$.ajax({
url: url,
type: 'post',
success: function(response){
// Add response in Modal body
$('#alert').hide();
$('.main').html(response);
// Display Modal
$('#Modal').modal('show');
}
});
});
if ($("#sendStedForm").length > 0) {
$("#sendStedForm").validate({
rules: {
sted: {
required: true,
maxlength: 100,
},
oppmote: {
required: true,
maxlength: 100,
},
oppmote_tid: {
pattern: /^[0-9,]+$/,
maxlength: 4,
}
},
messages: {
sted: {
required: "<small class=\"text-danger\">Legg inn sted</small>",
maxlength: "<small class=\"text-danger\">Sted bør ikke være så langt. 100 tegn er maks</small>",
},
oppmote: {
required: "<small class=\"text-danger\">Legg inn en kort beskrivelse</small>",
maxlength: "Beskrivelsen bær ikke være så lang. Maks 100 tegn</small>",
},
oppmote_tid: {
pattern: "<small class=\"text-danger\">Skriv inn ett gyldig nr</small>",
maxlength: "<small class=\"text-danger\">Oppmøte tid er for langt. Maks 3 tegn</small>",
},
},
submitHandler: function(form) {
alert('hi');
$('#submitSted').html('lagrer..');
// var lag_id = $("#slag_id").val();
// var sted = $("#ssted").val();
// var oppmote = $("#soppmote").val();
// var oppmote_tid = $("#soppmote_tid").val();
// if (!oppmote_tid) { oppmote_tid = '0';}
// oppmote_tid = oppmote_tid.replace(/,/g, '.');
$.ajax({
url: "<?php echo base_url('/vakter/ajaxAddSted/post') ?>",
type: "POST",
// data: $('#ajax_form').serialize(),
dataType: "json",
// data: { lag_id : lag_id, sted : sted, oppmote : oppmote, oppmote_tid : oppmote_tid },
data: $('#sendStedForm').serialize(),
success: function( response ) {
console.log(response);
console.log(response.success);
$('#submitSted').html('Submit');
$('#alert').html(response.msg);
$('#alert').addClass(response.typemsg);
$('#alert').show();
// $('#res_message').removeClass('d-none');
// document.getElementById("ajax_form").reset();
// alert("User record updated successfully with ID: "+response.id);
$("#sted").append('<option value="'+ response.id +'">'+ sted + ' - ' + oppmote + ' - ' + oppmote_tid + ' timer</option>')
$('#stedModal').modal('hide');
$('#submitSted').html('<i class="far fa-trash-alt"></i> Lagre');
setTimeout(function(){
$('#alert').hide();
$('#alert').html('');
},10000);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}
});
}
Try to wrap the sendStedForm inside a function and call it after the dom actually has the sendStedForm id to work with which is after ajax data is loaded and placed inside html. Although I have not tested this, but I hope this should work.
function goBack() {
window.history.back();
}
$('#alert').hide();
$('.stedModal').click(function() {
var typet = $(this).data('type');
if (typet == 'type') {
var url = '/vakter/ajaxAddType';
$('.modalForm').attr('id', 'sendTypeForm');
$('.modalForm').attr('name', 'sendTypeForm');
$('.submitButton').attr('id', 'submitType');
$('.submitButton').attr('name', 'submitType');
$('.modal-title').html('Legg til Type');
} else if (typet == 'sted') {
var url = '/vakter/ajaxAddSted';
$('.modalForm').attr('id', 'sendStedForm');
$('.modalForm').attr('name', 'sendStedForm');
$('.submitButton').attr('id', 'submitSted');
$('.submitButton').attr('name', 'submitSted');
$('.modal-title').html('Legg til Sted');
}
// AJAX request
$.ajax({
url: url,
type: 'post',
success: function(response){
// Add response in Modal body
$('#alert').hide();
$('.main').html(response);
// Display Modal
$('#Modal').modal('show');
process_sendStedForm();
}
});
});
function process_sendStedForm(){
if ($("#sendStedForm").length > 0) {
$("#sendStedForm").validate({
rules: {
sted: {
required: true,
maxlength: 100,
},
oppmote: {
required: true,
maxlength: 100,
},
oppmote_tid: {
pattern: /^[0-9,]+$/,
maxlength: 4,
}
},
messages: {
sted: {
required: "<small class=\"text-danger\">Legg inn sted</small>",
maxlength: "<small class=\"text-danger\">Sted bør ikke være så langt. 100 tegn er maks</small>",
},
oppmote: {
required: "<small class=\"text-danger\">Legg inn en kort beskrivelse</small>",
maxlength: "Beskrivelsen bær ikke være så lang. Maks 100 tegn</small>",
},
oppmote_tid: {
pattern: "<small class=\"text-danger\">Skriv inn ett gyldig nr</small>",
maxlength: "<small class=\"text-danger\">Oppmøte tid er for langt. Maks 3 tegn</small>",
},
},
submitHandler: function(form) {
alert('hi');
$('#submitSted').html('lagrer..');
// var lag_id = $("#slag_id").val();
// var sted = $("#ssted").val();
// var oppmote = $("#soppmote").val();
// var oppmote_tid = $("#soppmote_tid").val();
// if (!oppmote_tid) { oppmote_tid = '0';}
// oppmote_tid = oppmote_tid.replace(/,/g, '.');
$.ajax({
url: "<?php echo base_url('/vakter/ajaxAddSted/post') ?>",
type: "POST",
// data: $('#ajax_form').serialize(),
dataType: "json",
// data: { lag_id : lag_id, sted : sted, oppmote : oppmote, oppmote_tid : oppmote_tid },
data: $('#sendStedForm').serialize(),
success: function( response ) {
console.log(response);
console.log(response.success);
$('#submitSted').html('Submit');
$('#alert').html(response.msg);
$('#alert').addClass(response.typemsg);
$('#alert').show();
// $('#res_message').removeClass('d-none');
// document.getElementById("ajax_form").reset();
// alert("User record updated successfully with ID: "+response.id);
$("#sted").append('<option value="'+ response.id +'">'+ sted + ' - ' + oppmote + ' - ' + oppmote_tid + ' timer</option>')
$('#stedModal').modal('hide');
$('#submitSted').html('<i class="far fa-trash-alt"></i> Lagre');
setTimeout(function(){
$('#alert').hide();
$('#alert').html('');
},10000);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}
});
}
}
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);
?>
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)
Underneath you will find my original code:
function refreshChat() {
var id = "'.$convers_id.'";
var receiver = "'.$system->getFirstName($second_user->full_name).'";
$.get("'.$system->getDomain().'/ajax/refreshChat.php?id=" + id + "&receiver=" + receiver, function(data) {
$("#messages").html(data);
$(".conversation-message-list").getNiceScroll(0).scrollTop($(".conversation-content").height(), -1);
setTimeout(refreshChat, 3000);
});
}
function sendMessage() {
var user2 = "'.$user2.'";
var message = $("#message");
if(message.val() != "" && message.val() != " ") {
$.get("'.$system->getDomain().'/ajax/sendMessage.php?id="+user2+"&msg="+encodeURIComponent(message.val()), function(data) {
$("#messages").html(data);
message.val("");
});
}
}
$(document).keypress(function(e) {
if(e.which == 13) {
sendMessage();
}
});
function appendToMessage(str) {
var message = $("#message");
message.val(message.val()+" "+str);
$("#emoticonList").modal("hide");
}
What i am trying to is change the interval based on the height of the scroller (or the position), because every time it runs the refreshChat function, it pushes the scroller back down, which makes it impossible to scroll the chat.
I have already tried changing:
window.setInterval(function(){
refreshChat();
}, 1000);
To:
if ($(window).scrollTop() > 200) {
window.setInterval(function(){
refreshChat();
}, 100000000000);
} else {
window.setInterval(function(){
refreshChat();
}, 1000);
}
But this breaks the script. I would like to thank everybody beforehand for taking the efford on helping me solve my problem.
NOTE: I HAVE EDITED MY ORIGINAL CODE BASED ON MPLUNGJAN'S SUGGESTION
But how can i append a new message inside the chatscreen as suggested?
HTML:
<div class="conversation-message-list" onclick="hideEmoticons()">
<?php if ($user->expire == NULL){ ?>
<!--geen abbo-->
<div class="i-info-msg text-center" style="padding-top:15%;"><div class="pass-frac-item"><p class="title">Je hebt een nieuw bericht ontvangen!<span class="arrow"></span></p></div>
<p>Zien wie jou een bericht heeft gestuurd en antwoorden? Neem nu een Membership!</p>
<p>Maak ook gebruik van andere Upgrades, zoals zonder reclame surfen, anoniem profielen bekijken of jezelf in de spotlight plaatsen!</p>
<a class="i-button-14 i-button-bg-1" href="<?=$system->getDomain()?>/memberships.php">Neem een membership!</a>
</div>
<!--/geen abbo-->
<? } else { ?>
<!--wel abbo-->
<div class="conversation-content" id="messages">
<?php
if($messages->num_rows >= 1) {
while($message = $messages->fetch_object()) {
$sender = $system->getUserInfo($message->sender_id);
?>
<div class="row">
<div class="conversation-message pull-left">
<div class="pull-left">
<img src="<?=$system->getProfilePicture($sender)?>" class="img-circle pull-left" style="height:50px;width:50px;">
</div>
<div class="well bg-grey pull-left emoticon-small">
<?php
if($message->is_sticker == 0) {
$message->message = $system->secureField($system->smart_wordwrap($message->message));
echo Emojione\Emojione::shortnameToImage($message->message);
} else {
$sticker = $db->query("SELECT * FROM stickers WHERE id='".$message->sticker_id."'");
$sticker = $sticker->fetch_object();
echo '<img src="'.$system->getDomain().'/img/stickers/'.$sticker->pack_id.'/'.$sticker->path.'" style="height:80px;width:80px">';
}
?>
</div>
</div>
</div>
<? } ?>
<!--/wel abbo-->
<?
}
}
?>
</div>
</div>
<div class="col-lg-12 col-md-12 col-sm-12">
<div class="conversation-input" style="position:static;">
<div class="row">
<div class="input-group message-input">
<?php if((!isset($blocked_msg))&&($user->expire != NULL)) {?>
<input type="text" id="message" placeholder="<?=$lang["Enter_Message"]?>" class="form-control input-lg message-input no-border" required>
<span class="input-group-btn">
<i class="fa fa-fw fa-gift"></i>
</span>
<?php } if(isset($blocked_msg)) { ?>
<input type="text" id="message" placeholder="JE BENT GEBLOKKEERD DOOR DEZE GEBRUIKER." class="form-control input-lg message-input no-border" required>
<?php } ?>
</div>
</div>
</div>
</div>
You should not use setInterval on AJAX. Instead use setTimeout from inside the success and then scroll to bottom each time - assuming that is what the getNiceScroll does, you can do this:
function refreshChat() {
var id = "'.$convers_id.'";
var receiver = "'.$system->getFirstName($second_user->full_name).'";
$.get("'.$system->getDomain().'/ajax/refreshChat.php?id=" + id + "&receiver=" + receiver, function(data) {
$("#messages").html(data);
$(".conversation-message-list").getNiceScroll(0).scrollTop($(".conversation-content").height(), -1);
setTimeout(refreshChat, 3000);
});
}
Also do you need to send the complete chat? Why not just append new messages if any. Then you can test to see if there is something new and not do anything if not:
$("#messages").append(data);