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();
};
});
Related
I have a form with multiple select fields allowing you to select multiple entries per select.
Each select is named id1[], id2[], id3[] etc.
With Jquery when trying to submit the form can I check if any of the selects haven't had anything selected ?
I've tried this, but the form still submits.
$("#submit").click(function() {
$("select[name^='id']:visible").each(function(index, element) {
if ($(this).val() == "") return false;
});
});
I don't need to know which specific 'id' select hasn't had an option selected, but it would be nice if I did..
Thanks
You can use the filter function to return all selects that have no value selected
var selectsWithNoValue = $("select[name^='id']:visible").filter(function() {
return !this.value.length;
});
Then you can just check the length to see if you have any with no value - and you also have access to those elements
if(selectsWithNoValue.length) { // if there are selects with no value
//do something
}
Also since you're working with a form bind to the submit handler of the form so instead of the click of a button.
So if you want to prevent the form submit you can do
return !selectsWithNoValue.length
Which will return false if there are any selects with no value
FIDDLE
Attach the code to form submit handler instead of submit button's click handler, so you can prevent the form from being submitted.
$("form").submit(function() {
var rtn = true;
$("select[name^='id']:visible").each(function(index, element) {
if ($(this).val() == "") {
console.log(this.id); // id
rtn = false;
return false;
}
});
return rtn;
});
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"
});
So all i need to do is refresh a variable displayed on a php page which is stored in a MySQL db. This value is an int which is subtracted by 1 everytime the submit button from a form is clicked. As i've opted to use AJAX to post the form the page isn't being refreshed, therefore the value isn't being updated along with the form submission.
$qry = mysql_query("SELECT codes_remaining FROM users WHERE email= '".$_SESSION['email']."'");
while($row = mysql_fetch_array($qry)) {
if ($row['codes_remaining'] ==1 )
{
echo "You have ".$row['codes_remaining'].' code remaining';
}
else {
echo "You have ".$row['codes_remaining'].' codes remaining';
}
}
So this code just displays how many "codes" a person has left. I need this value to be refreshed once the submit button has been clicked from the form on the same page.
I'm using the following JavaScript to not refresh the page.
$("#form-submit").click(function(e) {
e.preventDefault();
$.ajax({
cache: true,
type: 'POST',
url: 'process-register.php',
data: $("#form-register").serialize(),
success: function(response) {
$("#output-div").html(response);
}
});
});
Thanks,
LS
If you'd like to update the value, do it like this (jQuery is easiest):
$(".submit").click(function(event) {
event.preventDefault();
$(this).load('file.php',function(val){
$('#output').text(val);
});
});
And in file.php:
<?php
connect_to_db();
$returned = get_info_from_db();
echo $returned;
?>
The jQuery will grab the info on file.php and put it into #output.
Maybe It's just me, but why not use jQuery .load function?
$("#form-submit").click(function(e) {
e.preventDefault();
$(this).load('process-register.php');
});
Maybe not ethical nor the correct way of doing this but everytime you click on #form-submit, it loads that file and therefore processes it everytime. Also note that if you load a file that uses MySQL connection yes has no mysql_connect or mysql_select_db configured, it obviously won't work. I've had that for quite some times.
In your 'success', you could possibly just throw in
$("#WhereYouWantTheOutput").load("process-register.php");
That way whenever your submit succeeds, it'll also load the output for you. Just replace #WhereYouWantTheOutput with the name of where you want the output placed.
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.
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;
}
}