Got a slight problem here. I have a form for a guestbook and each input gets validated so that is its empty, an error message appears. I have adjusted the jquery section so that the error message is delayed for 2 seconds, before fading out as shown below:
$(document).ready(function(){
var working = false;
$('#addCommentForm').submit(function(e){
e.preventDefault();
if(working) return false;
working = true;
$('#submit').val('Working..');
$('.error').remove();
$.post('submit.php',$(this).serialize(),function(msg){
working = false;
$('#submit').val('Submit');
if(msg.status){
$(msg.html).hide().insertAfter('#new').slideDown();
$('#body').val('');
}
else {
/* This is the section im stuck with */
$.each(msg.errors,function(k,v){
$('[for='+k+']').append('<div class="error">'+v+'</div>').delay(2000).fadeOut();
});
}
},'json');
});
});
However, after the error message fades out, the label also disappears. I have the feeling its to do with this part of the code:
'[for='+k+']'
Is there any way I can get around this, so that only the error message fades out rather than the label too?
Should you require any more code from me, please let me know.
You're right :
$('[for='+k+']').append('<div class="error">'+v+'</div>').delay(2000).fadeOut();
means you append an element, wait, and fadeOut any element with [for=...] selected.
A solution could be using appendTo()
$('<div class="error">'+v+'</div>').appendTo('[for='+k+']').delay(2000).fadeOut();
Related
This is a very difficult problem to explain and demo, basically I am using a mixture of PHP, Smarty, Ajax and Bootstrap.
I have a smarty template with an Ajax form in it (this works), a PHP backend which adds the form details into a database (this also works), on success or failure an alert is shown, this alert is from the Bootstrap CSS, it is written to the page as follows.
$('form').append('<div class="alert alert-success alert-dismissible" role="alert">' + data.message + '×</div>');
The alert does display in the page, and the alert does close! However, for example if I or the user should want to use the form again for example, to say add another record to the database, the alert does show, but this time it never closes! So if I add another 10 records and click the submit button after each one as normal I have 10 alert boxes under the form that never close.
<script type="text/javascript">
window.setTimeout(function() {
$(".alert").fadeTo(1000, 0).slideUp(1000, function() {
$(this).hide();
});
}, 5000);
</script>
Does anyone have an idea as to what I could do instead that would work perhaps?
The below code closes the alert, but there is some inconsistency as to when the alert closes.
$(document).ready(function() {
$('form').submit(function(event) {
// snip
var alertTimer1 = window.setInterval(function() {
if (typeof alertTimer2 === 'undefined') {
var alertTimer2 = window.setTimeout(function() {
$('#alert').find('.alert').fadeTo(1000, 0).slideUp(1000, function() {
$(this).remove();
window.clearInterval(alertTimer1);
window.clearTimeout(alertTimer2);
});
}, 5000);
}
}, 100);
}
}
setTimeout function only execute once where setInterval checks on a regular time interval. For example: https://codepen.io/anon/pen/VGPYXB
The better solution could be when you adding alert message set setTimeout function after adding message or use delay function like this https://codepen.io/anon/pen/XPpJGe.
Initializing alert with $('.alert').alert()
Close it with $('.alert').alert('close') or $('.alert').alert('dispose')
Add the code lines within setTimeout() to delay event like so:
setTimeout(() => {
$('.alert').alert('close')
}, 10000)
Bootstrap 3.3 Documentation - Alerts
Bootstrap 4.0 Documentation - Alerts
use bootstrap's alert class. It will help you close the alert box elegantly.
Just a quick question regarding this issue i am having. I am using jeditable to edit in place some fields on a page. This is working perfectly. Now I wish to implement some data checking. I have my php code to check the data entered and if its correct, it updates that database, and if it isn't it will return the error. The issue I am having is I want it to spit out the error to tell them but when they click the field again to edit it, it shows the error in the field until a page refresh. What i want it to do is have the same data in the field when they click on it after the error occurs instead of having to refresh the page then click the field again to edit it. Perhaps there is a way to return back the error and pass that into a tooltip of some sort above the field? Of course the way jeditable works is the div is surrounding the field then i have some js calling on my update.php file, this parses what jeditable passes to it and returns a $value to be error checked and by default if it is fine it simply at the bottom of the php "return $value;" to be put back int he field after its been saved in the DB.
Hopefully someone can understand what I am asking here and any assistance would be appreciated.
Easiest way is probably to do some client side validation. Right now you are doing server side validation by checking in PHP when the form is submitted. What are you checking for?Without code it is hard to give you a good example of client side validation.
Basic field checking:
var check_field = $("#field").val();
if (!check_field) { alert("Error message"); } else
{
// submit POST or whatever
}
Edit
Since the MAC address validation algorithm is already written server side, I recommend a separate ajax POST request that calls the checker function. Take the result of that request (true, false) and check it client side. If true, proceed with the update call.
Example:
$("#form").submit(function() {
var mac = $("#macfield").val();
if (!mac) { alert("MAC address can't be empty!"); } else
{
$.POST("checkmacaddress.php", {macval: mac}).success(function(a){
//assuming a comes back as a bool
if (!a) { alert("Invalid MAC!"); } else
{
// if the checker returned true, update the record
$.POST("update.php" ...);
}
});
} });
This doesn't include the checkmacaddress.php but you should be able to handle that if you already have the function on hand.
Hate when I do this, post here then figure out the answer myself...but at least if someone has the same issue they will see it. I found out about the jeditable onsubmit functions...i am using a tooltip to show on hover when editing the field so this will set the tooltip to the error and not submit the data unless its a valid mac.
function isMAC(value) {
teststr = value;
regex=/^([0-9a-f]{2}([:-]|$)){6}$|([0-9a-f]{4}([.]|$)){3}$/i;
if (regex.test(teststr)){
return true;
}
else {
return false;
}
}
$(".edit_mac").editable("edit_mac.php", {
onsubmit: function(settings, data) {
var input = $(data).find('input');
var value = input.val();
if (isMAC(value)) {
return true;
} else {
//display your message
$("#tooltip").html("Bad MAC Address...");
return false;
}
},
indicator : "Saving...",
submitdata: { _method: "put" },
submit : 'Save',
cssclass : "editable",
type : "text"
});
I have a PHP notification system, and the amount of notifications is put into a DIV using jQuery. The only problem is that when there are 0 notifications, the empty DIV still shows up. This is the jQuery I am currently using:
$(document).ready(function() {
$.get('/codes/php/nf.php', function(a) {
$('#nfbadge').html(a);
$('#nfbadge:empty').remove();
})
});
setInterval(function() {
$.get('http://localhost/codes/php/nf.php', function(a) {
$('#nfbadge').html(a);
$('#nfbadge:empty').remove();
})
}, 8000);
The only problem is that if at document load there is 0 notifications and a notification is added, the badge will not show up, so basically if the element is removed it won't come back unless the page is reloaded, but I made the notification system so that the page wouldn't have to be reloaded. How can I fix this?
.remove() takes the element out of the DOM as well as the content. This is why it doesn't come back unless you reload. Use .fadeOut() or .hide() instead
You should probably do something more like this:
var elm = $('#nfbadge'),
T = setInterval(getCodes, 8000);
function getCodes() {
$.get('/codes/php/nf.php', function(a) {
elm.html(a);
if (elm.is(':empty') && elm.is(':visible')) {
elm.hide();
}else{
elm.show();
}
});
}
Will need some more work on your part, but should get you on the right track!
If you have control over the PHP, you shouldn't be using jQuery to be removing DIVs, it's a waste of resources and load time, even if it's just a few lines of code.
In your PHP template you should include the #nfbadge div in a conditional statement, something like:
if($notifications) {
echo '<div id="nfbadge">';
//notification stuff
echo '</div>';
}
Then with your jQuery code you could do something like the following:
var $nfbadge = $('#nfbadge');
if($nfbadge) {$nfbadge.html(a)}
Why don't you just make the div hidden?
http://www.randomsnippets.com/2008/02/12/how-to-hide-and-show-your-div/
I have a form that when you submit it, it sends the data for validation to another php script via ajax. Validation errors are echo'd back in a div in my form. A success message also is returned if validation passes.
The problem is that the form is still displayed after submit and successful validation. I want to hid the div after success.
So, I wrote this simple CSS method which works fine when called from the page the form is displayed on.
The problem is that I cannot seem to call the hide script via returned code. I can return html like
echo "<p>Thanks, your form passed validation and is being sent</p>";
So I assumed I could simply echo another line after that
echo "window.onload=displayDiv()"; inside script tags (which I cannot get to display here)...
and that it would hide the form div.
It does not work. I am assuming that the problem is that the javascript is being returned incorrectly and not being interpreted by the browser...
How can I invoke my 'hide' script on the page via returned data from my validation script? I can echo back text but the script call is ineffective.
Thanks!
This is the script on the page with the form...
I can call it to show/hide with something like onclick="displayDiv()" while on the form but I don't want the user to invoke this... it has be called as the result of a successful validation when I write the results back to the div...
<script language="javascript" type="text/javascript">
function displayDiv()
{
var divstyle = new String();
divstyle = document.getElementById("myForm").style.display;
if(divstyle.toLowerCase()=="block" || divstyle == "")
{
document.getElementById("myForm").style.display = "none";
}
else
{
document.getElementById("myForm").style.display = "block";
}
}
</script>
PS: I am using the mootools.js library for the form validation if this matters for the syntax..
The AJAX call is:
window.addEvent('domready', function(){
$('myForm').addEvent('submit', function(e) {
new Event(e).stop();
var log = $('log_res').empty().addClass('ajax-loading');
this.send({
update: log,
onComplete: function() {
log.removeClass('ajax-loading');
}
});
});
});
Div ID log is where the ajax call back text (validation errors and success message) and loading graphic appear
This is a duplicate of How to make JS execute in HTML response received using Ajax? where I provided the chosen solution.
var response = "html\<script type=\"text/javascript\">alert(\"foo\");<\/script>html";
var reScript = /\<script.*?>(.*)<\/script>/mg;
response = response.replace(reScript, function(m,m1) {
eval(m1); //will run alert("foo");
return "";
});
alert(response); // will alert "htmlhtml"
Your AJAX call should have a "success" callback. It looks like you can simply call displayDiv() in that callback.
Also note that the var divstyle = new String(); line is unnecessary. Strings are immutable in JavaScript, so you are creating an empty string object, which remains unreferenced in the following line. Simply declare the variable when you assign it from document.getElementById():
var divstyle = document.getElementById("myForm").style.display;
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
//Since your making php do the validation, there would be two cases,
//the first case is that the php script is not echoing any thing on success, and
//the other case is that its echoing the error massages which will be assignedxmhttp.responseText
//so we need to check that xmlhttp.resposeText has been asigned a value.
if(xmlhttp.resposeText){
document.getElementById(displayContainers_id).innerHTML=xmlhttp.responseText;
}
}
I have a form, and before it submits I want to check some of the input against a database. The idea: 1) submit form, 2) check values, 3) show error or actually submit the form. Example:
$(form).submit(function() {
$.post('check.php', {
values
}, function(res) {
// result I need before submitting form or showing an error
});
return false;
});
Now, it takes some time before I get the result (i.e. not instantly), so I put in the return false at the bottom, preventing the form to submit before I get the $.post results back and do something with it.
Problem: after I get the results from $.post, and everything turns out to be OK, how do I tell the script to go on with submitting the form? If I use submit() it'll just take it back to this check script, creating an endless loop.
You're essentially submitting the form twice, if you did it this way. That seems wasteful. Instead, just prevent the form submission, and handle the values asynchronously (as you already are). From the server, accept the data if it's good and reject it if it's not. There's no need to submit the form if you're already sending the data to the server to begin with. It's a bit redundant.
You can use a boolean flag for this:
var isValid = false;
$(form).submit(function() {
if (isValid) return true;
$.post('check.php', {
values
}, function(res) {
if (res.valid) {
isValid = true;
$(form).submit();
}
// result I need before submitting form or showing an error
});
return false;
});
Try replacing the submit button with a link that has an onclick. Submit the form programatically afterward. E.g.:
<a id="submit">Submit</a>
$($("a#submit").click(function() {
$.post('check.php', {
values
}, function(res) {
// result I need before submitting form or showing an error
});
if (condition) {
$('[name=form_name]').submit();
};
});