Javascript Change setInterval on scroll height - javascript

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);

Related

Ajax form isn't submitted correctly

I am having this next issue with an Ajax form which is not submitted correctly.
I have 3 forms, one for desktop, one for mobile, and a form which is located inside a modal.
The first form for desktop version works perfectly and registers all data that I need through Cakephp.
The second one, which is for the mobile version displays an error which is coming from a function I developed for error handling with Jquery.
Both the mobile-version form and the modal form are appearing to have the same problem.
I send the query through ajax, but the problem persists in displaying the same error.
This is the Jquery code for the form which is working correctly.
$('#nueva_normalidad_form').on('submit', function(e){
e.preventDefault();
$('#errorMain').html('');
var formContainer = $('#form_container');
var errorArea = $('#errorMain');
if(!validateDocApplication(errorArea)){
return;
}
var data = $('#nueva_normalidad_form').serialize();
var beforeSend = function () {
$('#sendDataButton').attr("disabled", true);
};
var error = function (a) {
$('#errorMain').html('<div class="alert alert-danger">' + info.txt + '</div>');
return a;
};
var success = function(info) {
info = $.parseJSON(info);
if (info.id === 200) {
formContainer.animate({
display: "none"
}, {
duration: 600,
complete: function () {
formContainer.css("display", "none");
$('div#successText').css("display", "block");
}
});
$('#successText').animate({
display: "block"
}, {duration: 700,
complete: function () {
$('#successText').css("display", "block");
}
});
dataLayer.push({'eventcategory': 'Conversion', 'event': 'submitForm'});
} else {
$('#errorMain').html('<div class="alert alert-danger">' + error.txt + '</div>');
}
};
saveNewNormDoctor(data, beforeSend, success, error);
});
This is the function for the error handling of the field inputs.
//Validates the field inputs of Desktop Form
function validateDocApplication(errorArea) {
var noError = true;
if(!$('input[name="name"]').val()){
errorArea.html('<div class="alert alert-danger">Por favor, inserte el nombre</div>');
noError = false;
}
if(!$('input[name="surname"]').val()){
errorArea.html('<div class="alert alert-danger">Por favor, inserte el apellido</div>');
noError = false;
}
if(!$('input[name="email"]').val()){
noError = false;
errorArea.html('<div class="alert alert-danger">Por favor, inserte su correo</div>');
}else{
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
noError = re.test($('input[name="email"]').val());
}
if(!$('input[name="phone"]').val()){
errorArea.html('<div class="alert alert-danger">Por favor, inserte el número de teléfono</div>');
noError = false;
}
if(!$('input[name="colegiado"]').val()){
errorArea.html('<div class="alert alert-danger">Por favor, inserte el número de colegiado</div>');
noError = false;
}
var valorSpec = $('#spec option:selected').val();
if(!valorSpec){
errorArea.html('<div class="alert alert-danger">Seleccione una especialidad</div>');
noError = false;
}
return noError;
}
This is the function which sends the request and saves the data to the database.
function saveNewNormDoctor(data, beforeSend, success, error) {
$.ajax({
type: "POST",
url: "/staticpages/save_doc_new_norm",
data: data,
beforeSend: beforeSend,
success: success,
error: error
});
}
For my modal-version form I am using this submit function:
$('#sendDataNewNorm').on('submit', function (e) {
e.preventDefault();
$('#errorModal').html('');
var errorArea = $('#errorModal');
var formContainer = $('#formNewnorm');
var successArea = $('#successTextModal');
if(!validateDocApplication(errorArea)){
return;
}
var data = $('#sendDataNewNorm').serialize();
var beforeSend = function () {
$('#sendDataNewNormButton').attr("disabled", true);
};
var error = function (a) {
errorArea.html('<div class="alert alert-danger">' + info.txt + '</div>');
return a;
};
var success = function (info) {
info = $.parseJSON(info);
if (info.id === 200) {
formContainer.animate({
display: "none"
}, {
duration: 600,
complete: function () {
formContainer.css("display", "none");
successArea.css("display", "block");
}
});
successArea.animate({
display: "block"
}, {duration: 700,
complete: function () {
successArea.css("display", "block");
}
});
} else {
errorArea.html('<div class="alert alert-danger">' + info.txt + '</div>');
}
};
saveNewNormDoctor(data, beforeSend, success, error);
});
All inputs in 3 forms have the same name attributes such as name, surname, email,phone, colegiado and the value that it gets through the #spec select element.
This is the HTML markup of my modal's form. The same thing occurs in my mobile-version form.
I am at a dead-end. My Cakephp function for the server-side process is correct as my main form is being submitted correctly. Any hint on how to resolve the problem would be appreciating. The error is this one. While in the other form I always get all values correctly, in this ones, every one of these values come up empty.
errorArea.html('<div class="alert alert-danger">Por favor, inserte el número de colegiado</div>');
Thanks you.
<form id="sendDataNewNorm">
<div class="text-centers">
<h4 class="h4 font_Conv_Roboto-Regular text-center top_margin">
<?= __('Rellene el siguiente formulario <br>y nos pondremos en contacto con usted.'); ?>
</h4>
</div>
<div id="formNewnorm" class="bottom_margin">
<div class="col-md-12 col-sm-12 form-group top_margin no_side_paddings">
<div class="col-sm-6 col-md-6 no_padding_left">
<input name="name" id="name" class="desesc form-control" type="text" placeholder="<?= __('Nombre'); ?> *">
</div>
<div class="col-sm-6 col-md-6 no_side_paddings">
<input name="surname" id="surname" class="desesc form-control" type="text" placeholder="<?= __('Apellidos'); ?> *">
</div>
</div>
<div class="form-group">
<input name="email" id="email" class="desesc form-control" type="email" placeholder="<?= __('e-mail');?> *">
</div>
<div class="form-group">
<input name="phone" id="tel" class="desesc form-control" type="number" placeholder="<?= __('Número de contacto');?> *">
</div>
<div class="form-group">
<select class="desesc form-control" name="especialidad" id="spec">
<option value="0"><?= __('Seleccione su especialidad'); ?></option>
<?php foreach ($specs AS $k => $v) { ?>
<option value="<?= $k; ?>"><?= $v; ?></option>
<?php } ?>
</select>
</div>
<div class="form-group">
<input name="colegiado" id="collegiate" class="desesc form-control" type="text" placeholder="<?= __('Número de colegiado'); ?> *">
</div>
<div class="form-group">
<div class="radio radio_highlight">
<input type="radio" name="condiciones" id="condiciones_1" value="1" required="">
<label class="text-primary" for="condiciones_1">
<?= __('He leído y acepto las');?> <a target="_blank" href="http://topdoctors.local/terminos-legales">
<u><?= __('Condiciones de Uso'); ?></u></a>
</label>
</div>
<input type="hidden" name="created" value="<?php echo date('Y-m-d'); ?>" >
</div>
<div class="form-group">
<div id="errorModal"></div>
<button id="sendDataButton" class="btn btn-block btn-primary btn_md">
<?= __('Solicitar información'); ?>
</button>
</div>
</div>
<div id="successTextModal" class="top_margin_md bottom_margin_md top_padding_md bottom_padding bg_light text-center" style="display:none;">
<img class="top_padding_md img-responsive" src="/css/quironsalud/check.png" style="margin: 0 auto" />
<div class="box-success top_padding_md bottom_padding_md">
<span class="top_margin text-success font_Conv_Roboto-Regular ">
<?= __('Tu solicitud ha sido enviada correctamente'); ?>
</span>
</div>
</div>
</form>
Finally, I found the solution to my problem.
By assigning new ids for every input field which I needed, I came to this function:
function validateDocApplicationForm(errorArea) {
var noError = true;
if(!$('#name_form').val()){
errorArea.html('<div class="alert alert-danger">Por favor, inserte el nombre</div>');
noError = false;
} else {
name = $('#name_form').val();
return name;
}
if(!$('#surname_form').val()){
errorArea.html('<div class="alert alert-danger">Por favor, inserte el apellido</div>');
noError = false;
} else {
surname = $('#surname_form').val();
return surname;
}
if(!$('#email_form').val()){
noError = false;
errorArea.html('<div class="alert alert-danger">Por favor, inserte su correo</div>');
} else {
email = $('#email_form').val();
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
noError = re.test(email);
return email;
}
if(!$('#tel_form ').val()){
errorArea.html('<div class="alert alert-danger">Por favor, inserte el número de teléfono</div>');
noError = false;
}else {
phone = $('#tel_form').val();
return phone;
}
if(!$('#collegiate_form').val()){
errorArea.html('<div class="alert alert-danger">Por favor, inserte el número de colegiado</div>');
noError = false;
} else {
colegiado = $('#collegiate_form').val();
return colegiado;
}
var valorSpec = $('#spec_form option:selected').val();
if(!valorSpec){
errorArea.html('<div class="alert alert-danger">Seleccione una especialidad</div>');
noError = false;
}
return noError;
}
The changes I had to make on my markup were these:
<div id="formNewnorm" class="bottom_margin">
<div class="col-md-12 col-sm-12 form-group top_margin no_side_paddings">
<div class="col-sm-6 col-md-6 no_padding_left">
<input name="name" id="name_form" class="desesc form-control" type="text" placeholder="<?= __('Nombre'); ?> *">
</div>
<div class="col-sm-6 col-md-6 no_side_paddings">
<input name="surname" id="surname_form" class="desesc form-control" type="text" placeholder="<?= __('Apellidos'); ?> *">
</div>
</div>
<div class="form-group">
<input name="email" id="email_form" class="desesc form-control" type="email" placeholder="<?= __('e-mail');?> *">
</div>
<div class="form-group">
<input name="phone" id="tel_form" class="desesc form-control" type="number" placeholder="<?= __('Número de contacto');?> *">
</div>
<div class="form-group">
<select class="desesc form-control" name="especialidad" id="spec_form">
<option value="0"><?= __('Seleccione su especialidad'); ?></option>
<?php foreach ($specs AS $k => $v) { ?>
<option value="<?= $k; ?>"><?= $v; ?></option>
<?php } ?>
</select>
</div>
<div class="form-group">
<input name="colegiado" id="collegiate_form" class="desesc form-control" type="number" placeholder="<?= __('Número de colegiado'); ?> *">
</div>
<div class="form-group">
<div class="radio radio_highlight">
<input type="radio" name="condiciones_form" id="condiciones_form" value="1" required="">
<label class="text-primary" for="condiciones_form">
<?= __('He leído y acepto las');?> <a target="_blank" href="http://topdoctors.local/terminos-legales">
<u><?= __('Condiciones de Uso'); ?></u></a>
</label>
</div>
<input type="hidden" name="created" value="<?php echo date('Y-m-d H:i:s'); ?>" >
</div>
<div class="form-group">
<div id="errorModal"></div>
<button id="sendDataButton" class="btn btn-block btn-primary btn_md">
<?= __('Solicitar información'); ?>
</button>
</div>
</div>
With this approach, I was able to re-assign the values to every input with each respective name and new id. Therefore passing the new values through the ajax request, I was able to register my data to the database.

jQuery POST form that is viewed with Ajax

Ok, this is my first time logged in, but have a question which I can`t find. Maybe I used the wrong search terms or it is my broken English.
But hopefully, somebody can point me in the right direction.
My situation. I have a list of users. When I click on one of them a second screen opens using javascript/AJAX. Some CSS styling does the split screen thing.
In the second screen, I show a form with some info or not. So far so good.
What I want is that when you change some info and you press the submit/save button, data gets saved in the database without a page refresh. But I can't get it right. When I press the button the ajax split-screen disappears. But the page that I linked on the jquery does nothing.
Some code is in Dutch so ask if you need translation.
My code is as follows:
Page users.php
<script>
function jsAjaxVieuwUser(str) {
if (str == "") {
document.getElementById("mainRight").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("mainRight").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET", "ajaxBeheer.php?VieuwUser=" + str, true);
xmlhttp.send();
document.getElementById("mainRight").style = "display: inline-block;"; // Don`t show the start table
document.getElementById("closeUser").style = "display: block;"; // Don`t show the start table
}
}
</script>
<div class="main">
<div class="mainInfo">
<h3>Gebruikers</h3>
</div>
<div class="mainContent">
<div class="mainLeft" id="mainLeft">
<div class="actionBar">
<div><button class="button button2">Nieuwe gebruiker</button></div>
<div id="closeUser"><button class="button button2"> << </button></div>
</div>
<div class="list" id="userList">
<ul>
<li class="listheader"><div class="listFirstColum">Naam gebruiker</div> <div class="listSecondColum">Laatste login</div></li>
<?php
if(!isset($_GET['limit'])){
// START, AANTAL
$limit = '0 , 10';
}
$result = $db->select("SELECT ID, user_name, user_last_login FROM users ORDER BY ID ASC LIMIT ".$limit." ",array(''),array(''));
while ($row = $result->fetch_assoc()) {
echo '<li> <div class="listFirstColum">'.$row['user_name'].'</div> <div class="listSecondColum">'.$row['user_last_login'].'</div> </li>';
}
?>
</ul>
</div>
</div>
<div class="mainRight" id="mainRight">
<h1>HALLO</h1>
</div>
</div>
</div>
Page ajaxBeheer.php
if(isset($_GET['VieuwUser'])){
$disabled = 'disabled';
$idUser = $_GET['VieuwUser'];
$result = $db->select(" SELECT users.ID,
users.user_name,
users.user_email,
userinfo.userid,
userinfo.user_firstname,
userinfo.user_lastname,
userinfo.user_birthday,
userinfo.user_adress,
userinfo.user_adressnr
FROM users INNER JOIN userinfo
ON userinfo.userid = users.ID
WHERE users.ID=? ", array($idUser),array('%i'));
while ($row = $result->fetch_assoc()) {
//Gebruikers gegevens
$username = $row['user_name'];
$user_email = $row['user_email'];
//Personal data
$user_firstname = $row['user_firstname'];
$user_lastname = $row['user_lastname'];
$user_birthday = $row['user_birthday'];
$user_adress = $row['user_adress'];
$user_adressnr = $row['user_adressnr'];
}
// make the date readable, but if its empty make it 0000
if ($user_birthday == '0000-00-00' || empty($user_birthday)) {
$user_birthday = ' ';
}else{
$date = DateTime::createFromFormat('Y-m-d', $user_birthday);
$user_birthday = $date->format('d-m-Y');
}
?>
<div class="contentHolder" style="width: 100%;">
<div class="header">
<h3 style="width: 100%; text-align: center;">Gegevens medewerker: <?= $username ?></h3>
</div>
<div class="prLeftColomn colomn">
<form name="gebruiker" id="formId" method="POST">
<p><div class="omschrijving">Voornaam</div><div class="waarde"><input type="text" name="firstname" value="<?= $user_firstname ?>" /></div></p>
<p><div class="omschrijving">Achternaam</div><div class="waarde"><input type="text" name="firstname" value="<?= $user_lastname ?>" /></div></p>
<p><div class="omschrijving">Email</div><div class="waarde"><input type="text" name="firstname" value="<?= $user_email ?>" /></div></p>
<p><div class="omschrijving">Geboorte datum</div><div class="waarde"><input type="text" name="firstname" value="<?= $user_birthday ?>" /></div></p>
<p><div class="omschrijving">Telefoon</div><div class="waarde"><input type="text" name="firstname" value="" /></div></p>
<p><div class="omschrijving">Adres + huisnummer</div><div class="waarde"> <?= $user_adress.' '.$user_adressnr ?></div></p>
<p><div class="omschrijving">Postcode</div><div class="waarde"> </div></p>
<p><div class="omschrijving">Plaats</div><div class="waarde"> </div></p>
<p><div><input class="button" type="submit" name="updateGebruiker" value="UPDATE" onclick="save()"/></div></p>
</form>
</div>
<style type="javascript">
function save(){
var query = $('#formId').serialize();
var url = 'updateUser.php';
$.post(url, query, function (response) {
alert (response);
});
}
</style>
page updateUser.php
<?php
$table = 'userinfo';
$data = array('user_firstname' => 'test');
$format = array('%s');
$where = array('id' => '3');
$where_format = array('%i');
$updateCalc = $db->update($table, $data, $format, $where, $where_format);
?>
The reason of refreshing the page is because you're using a form with submit button, to prevent it just prevent the form to submit
if you have Jquery use the following
//option A
$("form#formId").submit(function(e){
e.preventDefault();
});
and Pure js solution is
document.getElementById('formId').addEventListener('submit', function(e) {
e.preventDefault();
});
Ok have it finally worked. Had the jquery in the ajaxBeheer.php script. Now i have it in the page where the ajax is executed. And that worked for me.
The Jquery link
Is located in the header.
I have now a second screen where the information is updated without a refresh page. :D
It`s without security so thats need too update for everyone that wants too use it! The question was for the second screen no refresh page.
Hopefully i can help some other people with it, becease it was a pain for me too find information.
The whole code:
Page users.php:
<?php
require_once (__DIR__.'/safeuser.php');
require_once (__DIR__.'/include/topheader.php');
require_once (__DIR__.'/include/config.inc.php');
require_once (__DIR__.'/classes/class-db.php');
?>
<script>
function jsAjaxVieuwUser(str) {
if (str == "") {
document.getElementById("mainRight").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("mainRight").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET", "ajaxBeheer.php?VieuwUser=" + str, true);
xmlhttp.send();
document.getElementById("mainRight").style = "display: inline-block;"; // Don`t show the start table
document.getElementById("closeUser").style = "display: block;"; // Don`t show the start table
}
}
function save(){
// Get the form.
var form = $('#formId');
// Get the messages div. Too show the messages on screen
var formMessages = $('#form-messages');
// TODO: The rest of the code will go here...
// Set up an event listener for the contact form.
$(form).submit(function(event) {
// Stop the browser from submitting the form.
event.preventDefault();
// TODO
// Serialize the form data.
var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
// Set the message text.
$(formMessages).text(response);
alert (response);
})
.fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
// Set the message text.
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
});
}
function closeUserVieuw() {
var x = document.getElementById("mainRight");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
document.getElementById("closeUser").style = "display: none;"; // Don`t show the start table
}
}
</script>
<style type="text/css">
</style>
<div class="main">
<div class="mainInfo">
<h3>Gebruikers</h3>
</div>
<div class="mainContent">
<div class="mainLeft" id="mainLeft">
<div class="actionBar">
<div><button class="button button2">Nieuwe gebruiker</button></div>
<div id="closeUser"><button class="button button2"> << </button></div>
</div>
<div class="list" id="userList">
<ul>
<li class="listheader"><div class="listFirstColum">Naam gebruiker</div> <div class="listSecondColum">Laatste login</div></li>
<?php
if(!isset($_GET['limit'])){
// START, AANTAL
$limit = '0 , 10';
}
$result = $db->select("SELECT ID, user_name, user_last_login FROM users ORDER BY ID ASC LIMIT ".$limit." ",array(''),array(''));
while ($row = $result->fetch_assoc()) {
echo '<li> <div class="listFirstColum">'.$row['user_name'].'</div> <div class="listSecondColum">'.$row['user_last_login'].'</div> </li>';
}
?>
</ul>
</div>
</div>
<div class="mainRight" id="mainRight">
<h1>HALLO</h1>
</div>
</div>
</div>
<!-- FOOTER -->
</div>
</body>
</html>
ajaxBeheer.php:
<?php
// name: ajaxBeheer.php
require_once (__DIR__.'/classes/class-users.php');
require_once (__DIR__.'/include/config.inc.php');
if(isset($_GET['q'])){
$zoek = $_GET['q'];
$param = "$zoek%"; // Zoek alleen op voorletter
$getGebruiker = $db->select("SELECT * FROM users WHERE naam LIKE ?",array($param),array('s'));
?>
<div id="tableUsers">
<div class="headRow" style="" id="tableUsers">
<div class="cell" style="width: 70%">Gebruiker</div>
<div class="cell" style="width: 30%; border-left: 2px solid #fff; border-right: 2px solid #fff;">Status</div>
</div>
<?php
while ($myrow = $getGebruiker->fetch_assoc()) {
if($myrow['active'] == '1'){
$gebrActive = 'Aktief';
} else {
$gebrActive = 'gedeaktiveerd';
}
echo '<a style="display:block" href="?ID='.$myrow['id'].'">
<div class="row">
<div class="cell" style="width: 70%">'.$myrow['naam'].'</div>
<div class="cell" style="width: 30%; border-left: 1px solid #fff; border-right: 1px solid #fff;">'.$gebrActive.'</div>
</div></a>';
}
echo '</div>';
}
if(isset($_GET['VieuwUser'])){
$disabled = 'disabled';
$idUser = $_GET['VieuwUser'];
$result = $db->select(" SELECT users.ID,
users.user_name,
users.user_email,
userinfo.userid,
userinfo.user_firstname,
userinfo.user_lastname,
userinfo.user_birthday,
userinfo.user_adress,
userinfo.user_adressnr
FROM users INNER JOIN userinfo
ON userinfo.userid = users.ID
WHERE users.ID=? ", array($idUser),array('%i'));
while ($row = $result->fetch_assoc()) {
//Gebruikers gegevens
$username = $row['user_name'];
$user_email = $row['user_email'];
//Personal data
$user_firstname = $row['user_firstname'];
$user_lastname = $row['user_lastname'];
$user_birthday = $row['user_birthday'];
$user_adress = $row['user_adress'];
$user_adressnr = $row['user_adressnr'];
}
// make the date readable, but if its empty make it 0000
if ($user_birthday == '0000-00-00' || empty($user_birthday)) {
$user_birthday = ' ';
}else{
$date = DateTime::createFromFormat('Y-m-d', $user_birthday);
$user_birthday = $date->format('d-m-Y');
}
?>
<div class="contentHolder" style="width: 100%;">
<div class="header">
<h3 style="width: 100%; text-align: center;">Gegevens medewerker: <?= $username ?></h3>
</div>
<div class="prLeftColomn colomn">
<form name="gebruiker" id="formId" action="updateUser.php">
<p><div class="omschrijving">Voornaam</div><div class="waarde"><input type="text" name="firstname" value="<?= $user_firstname ?>" /></div></p>
<p><div class="omschrijving">Achternaam</div><div class="waarde"><input type="text" name="lastname" value="<?= $user_lastname ?>" /></div></p>
<p><div class="omschrijving">Email</div><div class="waarde"><input type="text" name="useremail" value="<?= $user_email ?>" /></div></p>
<p><div class="omschrijving">Geboorte datum</div><div class="waarde"><input type="text" name="userbirthday" value="<?= $user_birthday ?>" /></div></p>
<p><div class="omschrijving">Telefoon</div><div class="waarde"><input type="text" name="usertel" value="" /></div></p>
<p><div class="omschrijving">Adres + huisnummer</div><div class="waarde"> <?= $user_adress.' '.$user_adressnr ?></div></p>
<p><div class="omschrijving">Postcode</div><div class="waarde"> </div></p>
<p><div class="omschrijving">Plaats</div><div class="waarde"> </div></p>
<p><div><input class="button" type="submit" name="updateGebruiker" value="UPDATE" onclick="save()"/></div></p>
</form>
</div>
<div class="header" style="margin-top: 5%">
<h3 style="width: 90%; text-align: center;">Uren overzicht</h3>
</div>
<div id="tableUserUren">
<div class="prLeftColomn colomn">
<label>Uren deze week</label>
<input type="text" value="" style="background: white;" <?= $disabled ?> />
<label>Uren deze maand</label>
<input type="text" value="" style="background: white;" <?= $disabled ?> />
<label>Uren vorige maand</label>
<input type="text" value="" style="background: white;" <?= $disabled ?> />
<label>Uren Vrij genomen</label>
<input type="text" value="" style="background: white;" <?= $disabled ?> />
<label></label>
<input type="text" value="" style="background: white;" <?= $disabled ?> />
</div>
<div class="prRightColomn colomn">
</div>
</div>
</div>
<?php
}
?>
updateUser.php
<?php
require_once (__DIR__.'/include/config.inc.php');
require_once (__DIR__.'/classes/class-db.php');
$username = $_POST['firstname'];
// Ready too add the username
$table = 'users';
$data = array('user_name' => $username);
$format = array('%s');
$newJob = $db->insert($table, $data, $format);
if($newJob != $db::SQLSUCCESFULL){ // Variable is 00000
echo 'Er is helaas iets fout gegaan met het toevoegen van de regel. Code:'.$newJob;
header('location: '.$_SERVER['REMOTE_HOST'].'newuser.php?err=DATABASE&code='.$newJob);
exit();
}else{
echo 'succes!'.$username;
}
?>

How to let load more data append on top?

I have done the load more result but the load result will append at the bottom. How do I make it append on the top?
Because the message I send is to go to the bottom so I want the old message to be appended on top.
Here is my html:
<form name ="chatroom">
<div class="count-user-online">
<?php echo $row ?>
</div>
<div class="chatroom-upper-container" id="chatroom-upper-container">
<input type="hidden" id="result_no" value="10">
<div id="inner">
Loading Message....<img src="../images/loading.gif"/>
</div>
</div>
<input type="button" id="load" value="Load More Results">
<div class="chatroom-lower-left-container">
<textarea class="message-setting" id="area-message" placeholder="type text" name= "msg"></textarea>
</div><div class="chatroom-lower-right-container">
<button type="button" class="btn sendmessage-btn" onclick= "submitChat()">Send</button>
</div>
</form>
Here is my js:
$(document).ready(function(){
$("#load").click(function(){
loadmore();
});
});
function loadmore()
{
var val = document.getElementById("result_no").value;
$.ajax({
type: 'post',
url: 'chatloadmore.php',
data: {
getresult:val
},
success: function (response) {
var content = document.getElementById("chatroom-upper-container");
content.innerHTML = content.innerHTML+response;
// We increase the value by 2 because we limit the results by 2
document.getElementById("result_no").value = Number(val)+10;
}
});
}
Here is my loadmorefile.php:
<?php
include '../config.php';
include'login.php';
$no = $_POST['getresult'];
$username = $_SESSION['username'];
$sql1= "SELECT * FROM (
SELECT * FROM logs ORDER BY id DESC LIMIT $no,40
) sub
ORDER BY id ASC ";
$result1 = mysqli_query($connection,$sql1);
while($extract = mysqli_fetch_array($result1)){
$color = ($extract['username'] == $username) ? ' #F5F5F5' : '#DCDCDC';
$position = ($extract['username'] == $username) ? 'right' : 'left';
echo "
<div class='left-wrap-message' style='background-color:$color; float:$position;'>
<p style='text-align:$position; margin:0;'>". $extract['username']. " : </p>
<p style='text-align:$position; margin:0; text-align:left;'> " . $extract['msg']. "</p></div>
<div class='msg-dateandtime' style='text-align:$position;'> " . $extract['date']. "</div>";
}
?>
Instead of
content.innerHTML = content.innerHTML+response;
Do a
content.innerHTML = response + content.innerHTML;

user profile update via ajax

hi guys im trying to update user details via ajax but its not updating my users table and just stop executing when possessing... appear here is my code please help if possible
edit_profile.php
<?php
if(isset($_POST["la"])){
$firstname = strip_tags(preg_replace('#[^a-z0-9]#i', '', $_POST['fi']));
$lastname = strip_tags(preg_replace('#[^a-z]#', '', $_POST['la']));
$age = strip_tags(preg_replace('#[0-9]#', '', $_POST['ag']));
$gender = strip_tags(preg_replace('#[^a-z]#', '', $_POST['g']));
// FORM DATA ERROR HANDLING
if($gender == "" || $firsname == "" || $lastname == "" || $age == ""){
echo "some account info is empty.";
exit();
}else{
$sql = "UPDATE users SET gender='$gender', age='$age', lastname='$lastname, firstname='$firstname' WHERE username='$log_username' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
echo "account_success";
exit();
}
}
?>
ajax and js
<script type="text/javascript" language="javascript">
function _(x){
return document.getElementById(x);
}
function toggleElement(x){
var x = _(x);
if(x.style.display == 'block'){
x.style.display = 'none';
}else{
x.style.display = 'block';
}
}
function restrict(elem){
var tf = _(elem);
var rx = new RegExp;
if(elem == "firstname"){
rx = /[^a-z0-9]/gi;
} else if(elem == "lastname"){
rx = /[^a-z0-9]/gi;
}
tf.value = tf.value.replace(rx, "");
}
function emptyElement(x){
_(x).innerHTML = "";
}
function ajaxObj( meth, url ) {
var x = new XMLHttpRequest();
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
function update_profile() {
var fi = _("firstname").value;
var la = _("lastname").value;
var g = _("gender").value;
var ag = _("age").value;
var status2 = _("status_profile");
if(fi == "" || la == "" || ag == "" || g == ""){
status2.innerHTML = "Fill out all of the form data";
status2.style.color = "red";
}else {
_("profilebtn").style.display = "none";
status2.innerHTML = 'processing ...';
var ajax = ajaxObj("POST", "edit_profile.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText != "account_success"){
_("profilebtn").style.display = "block";
}
}
}
ajax.send("&fi="+fi+"&la="+la+"&g="+g+"&ag="+ag);
}
}
</script>
the html
<div class="row profile-classic">
<div class="col-md-12 m-t-20">
<form name="updateform" id="updateform" onsubmit="return false;">
<div id="profile_form" class="panel">
<div class="panel-title line">
<div class="caption"><i class="fa fa-phone c-gray m-r-10"></i>ACCOUNT</div>
</div>
<div class="panel-body">
<div class="row">
<div class="control-label c-gray col-md-3">Username:</div>
<div class="col-md-6">
<input type="text" class="form-control" value="<?php echo $uname; ?>" disabled="disabled">
</div>
</div><br />
<div class="row">
<div class="control-label c-gray col-md-3">Firstname: *</div>
<div class="col-md-6">
<input type="text" onfocus="emptyElement('status_profile')" class="form-control" id="firstname" contenteditable="true" value="<?php echo $firstname; ?>">
</div>
</div><br />
<div class="row">
<div class="control-label c-gray col-md-3">Lastname: *</div>
<div class="col-md-6">
<input type="text" onfocus="emptyElement('status_profile')" class="form-control" id="lastname" placeholder="your lastname" value="<?php echo $lastname; ?>" >
</div>
</div><br />
<div class="row">
<div class="control-label c-gray col-md-3">Age: *</div>
<div class="col-md-6">
<input type="text" onfocus="emptyElement('status_profile')" class="form-control" id="age" value="<?php echo $age; ?>">
</div>
</div><br />
<div class="row">
<div class="col-md-6">
<select class="form-control" onfocus="emptyElement('status_profile')" id="gender" class="form-control">
<option value="<?php echo $gender; ?>"><?php echo $sex; ?></option>
<option value="m">Male</option>
<option value="f">Female</option>
</select>
</div>
<button id="profilebtn" onclick="update_profile()" class="btn btn-sm btn-default"><i class="fa fa-floppy-o"></i> Save</button><span id="status_profile"></span>
</div><br />
</div>
</div></form>
</div></div>
You can use mysqli_error($db_conx) to determine what the error is... just have your javascript display it nicely for you.
But also - the variable in your WHERE clause ( $log_username ) is undefined.

HTML/JS Contact Form Not Sending or Showing Error Message

I have a contact form that I can't seem to send to my Gmail account. It's different from all the contact forms I've seen because the error message is within the HTML. Nothing happens when the submit button is pressed (no email, no error or success message). Please be gentle for I am somewhat new to PHP. I just need some help please.
The HTML
<div class="contactForm">
<div class="successMessage alert alert-success alert-dismissable" style="display: none">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
Thank You! E-mail was sent.
</div>
<div class="errorMessage alert alert-danger alert-dismissable" style="display: none">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
Oops! An error occured. Please try again later.
</div>
<form class="liveForm" role="form" action="form/send.php" method="post" data-email-subject="Contact Form" data-show-errors="true" data-hide-form="false">
<fieldset>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Name <span>(Required)</span></label>
<input type="text" required name="field[]" class="form-control">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Email <span>(Required)</span></label>
<input type="email" required name="field[]" class="form-control">
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label class="control-label">Subject</label>
<input type="text" name="field[]" class="form-control">
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label class="control-label">Message <span>(Required)</span></label>
<textarea name="field[]" required class="form-control" rows="5"></textarea>
</div>
</div>
</div>
<input type="submit" class="btn btn-primary" value="Send Message">
</fieldset>
</form>
</div>
</div>
The JS
/**
* Contact Form
*/
jQuery(document).ready(function ($) {
"use strict";
$ = jQuery.noConflict();
var debug = false; //show system errors
$('.liveForm').submit(function () {
var $f = $(this);
var showErrors = $f.attr('data-show-errors') == 'true';
var hideForm = $f.attr('data-hide-form') == 'true';
var emailSubject = $f.attr('data-email-subject');
var $submit = $f.find('[type="submit"]');
//prevent double click
if ($submit.hasClass('disabled')) {
return false;
}
$('[name="field[]"]', $f).each(function (key, e) {
var $e = $(e);
var p = $e.parent().find("label").text();
if (p) {
var t = $e.attr('required') ? '[required]' : '[optional]';
var type = $e.attr('type') ? $e.attr('type') : 'unknown';
t = t + '[' + type + ']';
var n = $e.attr('name').replace('[]', '[' + p + ']');
n = n + t;
$e.attr('data-previous-name', $e.attr('name'));
$e.attr('name', n);
}
});
$submit.addClass('disabled');
$f.append('<input class="temp" type="hidden" name="email_subject" value="' + emailSubject + '">');
$.ajax({
url: $f.attr('action'),
method: 'post',
data: $f.serialize(),
dataType: 'json',
success: function (data) {
$('span.error', $f).remove();
$('.error', $f).removeClass('error');
$('.form-group', $f).removeClass('has-error');
if (data.errors) {
$.each(data.errors, function (i, k) {
var input = $('[name^="' + i + '"]', $f).addClass('error');
if (showErrors) {
input.after('<span class="error help-block">' + k + '</span>');
}
if (input.parent('.form-group')) {
input.parent('.form-group').addClass('has-error');
}
});
} else {
var item = data.success ? '.successMessage' : '.errorMessage';
if (hideForm) {
$f.fadeOut(function () {
$f.parent().find(item).show();
});
} else {
$f.parent().find(item).fadeIn();
$f[0].reset();
}
}
$submit.removeClass('disabled');
cleanupForm($f);
},
error: function (data) {
if (debug) {
alert(data.responseText);
}
$submit.removeClass('disabled');
cleanupForm($f);
}
});
return false;
});
function cleanupForm($f) {
$f.find('.temp').remove();
$f.find('[data-previous-name]').each(function () {
var $e = jQuery(this);
$e.attr('name', $e.attr('data-previous-name'));
$e.removeAttr('data-previous-name');
});
}
});
The PHP
<?php
// Contact subject
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
// Enter your email address
$to ='divagraphicsinc#gmail.com';
$send_contact=mail($to,$subject,$message,$header);
?>
<?php
$ajax = (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
$ajax = true;
//we do not allow direct script access
if (!$ajax) {
//redirect to contact form
echo "Please enable Javascript";
exit;
}
require_once "config.php";
//we set up subject
$mail->Subject = isset($_REQUEST['email_subject']) ? $_REQUEST['email_subject'] : "Message from site";
//let's validate and return errors if required
$data = $mail->validateDynamic(array('required_error' => $requiredMessage, 'email_error' => $invalidEmail), $_REQUEST);
if ($data['errors']) {
echo json_encode(array('errors' => $data['errors']));
exit;
}
$html = '<div style="width: 640px; font-size: 11px;">
<h2>' . $mail->Subject . '</h2><ul>
';
foreach ($data['fields'] as $label => $val) {
$html .= '<li>' . $label . ': ' . $val . '</li>';
}
$html .= '</ul></div>';
$mail->setup($html, $_REQUEST, array());
$result = array('success' => 1);
if (!$mail->Send()) {
$result['success'] = 0;
}
echo json_encode($result);
exit;

Categories