PHP JQuery and Jeditable - php

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

Related

Ajax Call Worked; Doesn't Work Anymore

I have an AJAX call on a page for administrators to e-sign. When a button (adminEsign_btn) is pressed, this jQuery is called:
$("#adminEsign_btn").click(function(e){//admin esign submitted
e.preventDefault();
//validate esign
var valid = true;
if($.trim($('#adminSignature').val()).length < 3){
valid = false;
}
//action
if(valid === false){
$('#adminEsignError').html('<span class="error">You must agree to the statement and sign.</span>');
}
else{//validation passed, submit data
var schoolID = <?php echo $schoolProfile['schoolID']; ?>;
var signature = $('#adminSignature').val();
$('#adminEsignLoader').css({'display':'inline-block'});
$('#submitForm').attr("disabled","disabled");
$('#submitForm').val("Updating...");
$.ajax({
type: "POST",
url: 'bin/schoolProfile.saveEsign.php',
data: { schoolID:schoolID, signature:signature}
}).done(function(response) {
//$('#debug').html(response);
//alert(response);
if(response.indexOf('success') >= 0){//if 'success' exists in the response text
$('#submitForm').removeAttr("disabled");
$('#submitForm').val("Update School Profile");
$('#adminEsignLoader').hide();
//disable the e-sign
$('#adminAgree').attr("disabled","disabled");
$('#adminSignature').attr("readonly","readonly");
$('#adminEsign_btn').attr("disabled","disabled");
}
});
$('#adminEsignError').html('');
}
});
I didn't write the original code, so I don't know exactly what is going on in the if statement:
if(response.indexOf('success') >= 0){//if 'success' exists in the response text
But the call isn't expecting a return other than an echo of success. The following php page (schoolProfile.saveEsign.php) is what is called:
<?php
include($_SERVER['DOCUMENT_ROOT'] . '/includes/init.php');
$Page->clearance('Admin');
$Main->saveSchoolAdminEsign($_POST['schoolID'], $_POST['signature']);
echo 'success';
?>
NOTE: $Main is initialized in init.php as well as is $Page.
This code worked up until today when I tested it again. It is supposed to post the data to schoolProfile.saveEsign.php and run a function to save the schoolID and signature to a mysql database.
I've used the javascript alert() function to post the results of the "response" and it always shows the code for the entire current page (schoolProfile.edit.php).
I've run the code in Chrome and it shows that the data is being posted. It has status 302 - Found. The size is 485 B (sounds reasonable for 2 variables with only text), but underneath size in Chrome Network Debugger is content and content is 0 B - empty. I don't know if this means the data isn't being sent or what.
I've tested setting a Session variable to see if the session gets saved and I haven't been able to change it's value so that may be a sign that the data isn't actually being pushed across. But when I view the header for the page being called, it shows the 2 variables - schoolID and signature - with values.
I'm new to Chrome Network Debugger so if there are any other things I can check or if anyone has any suggestions any help would be appreciated.
EDIT: I've also tested the success and error functions inside the ajax call and success is always called. Once again it only returns the entire code for the current page (schoolProfile.edit.php).
I found the issue. In my include($_SERVER['DOCUMENT_ROOT'] . '/includes/init.php'); The init.php document redirects the user to schoolProfile.edit.php if they haven't completed filling out the school profile and it also makes sure that they aren't already at that url using PHP's $_SERVER['REQUEST_URI'].
The issue was that when trying to call schoolProfile.saveEsign.php, this url was not in the "list" of okay'd URL's so the AJAX request was always being redirected to schoolProfile.edit.php - AKA the current page. That is why I would always see the current page code when I would do an alert.
For future reference for myself. Original code:
if($_SERVER['REQUEST_URI'] != '/settings/schoolProfile.edit?f='.$Main->encrypt("INCOMPLETE")) {
header("Location:/settings/schoolProfile.edit?f=".$Main->encrypt("INCOMPLETE"));
exit();
}
Fixed Code:
if($_SERVER['REQUEST_URI'] != '/settings/schoolProfile.edit?f='.$Main->encrypt("INCOMPLETE")
&& $_SERVER['REQUEST_URI'] != '/settings/bin/schoolProfile.saveEsign'
&& $_SERVER['REQUEST_URI'] != '/settings/bin/schoolProfile.saveEsign.php') {
header("Location:/settings/schoolProfile.edit?f=".$Main->encrypt("INCOMPLETE"));
exit();
}

Label disappears after validation error message fades out

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

Check in ajax/jquery a form beform submit ( check the value whether it is in database)

ajax is not yet sothin i master.
I have two forms field
code :
name :
and the submit button like :
<form><input type=text name=code><input type =text name=name/></form>
I would like in php/jquery to check if the code the user fill exist in a table of my db.
If it does not exits, when the user leave the textfield to fill the next one, i would like to print a message like: this code is not in the db and then clean the fied. Until the user provide a valide code.
If your php service returns true or false for validation.
and the placeholder for the error is a label called
then an example (in jQuery) would be
$(document).ready(function() {
$("form").submit(function(e) {
var code = $("input[name='code']");
var error = $("#error");
e.preventDefault();
var form = this;
$.getJSON('urlToPhp',
{ code: code.val() },
function(valid) {
if (!valid) {
error.text(code.val() + ' is not found try another code...');
code.val('');
} else {
form.submit();
}
}
);
});
});
I've created a simple example at http://jsfiddle.net/nickywaites/e4rhf/ that will show you have to create a jQuery ajax post request.
I'm not too familiar with php so that part of it I'll have to leave aside although you can use something along the lines of $_POST["Name"].
Here is php example that I googled http://php4every1.com/tutorials/jquery-ajax-tutorial/ that might be better for you.

How To Call Javascript In Ajax Response? IE: Close a form div upon success

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

Problem with jQuery-check after submitting a form

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

Categories