I have a button that calls a javascript function after an onclick event is called. This function validates my entries, and then creates an ajax object to populate my table of information. Everything seems to work fine, except when I add this code:
echo "$(document).ready(function() { $(\"#newDate\").submit( function() {
ValidateForm('$ID');
} ); });";
ValidateForm() is the same function my onclick event calls, except it does not seem to work without an empty alert placed after I send the ajax request. After looking around on SO I found a similar problem. I understand the problem in that particular post, except no matter what I do I can't solve my problem. I tried moving my send into my anonymous function after a successful ready state is established, and even tried setting my final parameter in my open method to -false-. (Which I know is not a valid solution, but it didn't work anyway.
So why does everything work perfectly with an onclick event, but not a jquery submit method?
function ValidateForm(CQID)
{
var dt=document.newDate.uinput;
if (isDate(dt.value)==false){
dt.focus();
return false;
}
populateDateTable(dt.value, CQID);
}
function populateDateTable(dateString, CQID)
{
//After recieving a date and checking validity populate a table of proceeding dates.
var xmlhttp = createReq();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("BoxCarCapacityDates").innerHTML= xmlhttp.responseText;
}
}
xmlhttp.open("GET",'populateDateTable.php?dateString='+dateString+'&CQID='+CQID, true);
xmlhttp.send();
}
Thanks in advance. (Switching everything into jquery slowly.. )
echo "$(document).ready($(function()
{
$('#newData').click(function()
{
var dt=document.newDate.uinput;
if (isDate(dt.value)==false)
{
dt.focus();
return false;
}
$.get(
{
url: 'populateDateTable.php',
data: 'dateString='+dateString+'&CQID='+CQID,
success: function()
{
$('#BoxCarCapacityDates').html(response);
}
});
});
});
); </script>";
The above code was submitted as an answer, but it doesn't seem to work at all.
Have you changed your button into a submit button? Without this, the form won't submit.
You will also need to add:
e.preventDefault();
into your function that you are attaching to the submit event of the form, to ensure that the form doesn't just POST(or GET) the information to it's action URL:
echo "$(document).ready(function() { $(\"#newDate\").submit( function(e) {
e.preventDefault();
ValidateForm('$ID');
} ); });";
Are you ready to jQuery'ify your code? If so, try this.
$(function() {
$('#newData').click(function() {
var dt=document.newDate.uinput;
if (isDate(dt.value)==false){
dt.focus();
return false;
}
$.get({
url: 'populateDateTable.php',
data: 'dateString='+dateString+'&CQID='+CQID,
success: function(){
$('#BoxCarCapacityDates').html(response);
}
});
});
});
Related
I'm trying to get some client side validation working to prevent a form submission occurring if an object has no value. I've been plugging away at this for a while now but cannot get a satisfactory solution.
My form submission Js looks like this:
$(document).ready(function () {
$('#localUsersDateTime').val(setLocalDateTime());
$('#createentry').ajaxForm({
beforeSubmit: checkTextObjHasValue($('#newentry'), 'You need to add some text.'),
dataType: 'json',
success: function (result) {
$('#entries-list').prepend('<li>' + $('#newentry').val() + '</li>');
$('#newentry').val('').blur();
},
error: function (xhr)
{
try {
var json = $.parseJSON(xhr.responseText);
alert(json.errorMessage);
} catch (e) {
alert('Oops, Something very bad has happened');
}
}
});
return false;
});
However when the page loads it runs my checkTextObjHasValue() specified in the beforeSubmit: function so that check needs to only execute on actual form submission.
function checkTextObjHasValue(obj, message) {
if ($(obj).val() === '') {
alert(message);
return false;
}
return true;
}
How can I prevent this beforeSubmit: callback from being executed when just loading the page and only execute on actual form submission?
The beforeSubmit option expects a reference to a function. You were immediately calling a function. Try using this:
beforeSubmit: function () {
return checkTextObjHasValue($('#newentry'), 'You need to add some text.');
},
The added return allows for the submission to cancel if false is actually returned (which is possible in checkTextObjHasValue under a certain condition).
Technically, it could've worked if you returned a function from checkTextObjHasValue, but I think this way is a little cleaner. And it lets you customize it in case you want to validate several fields.
UPDATE:
Like in the documentation for the plugin, you could take this approach:
beforeSubmit: beforeSubmitHandler,
And then define a function separately like this:
function beforeSubmitHandler() {
return checkTextObjHasValue($('#newentry'), 'You need to add some text.');
}
Okay, pretty straight forward JQuery question that I am struggling to find an answer for:
I have a JQuery event that is called on button click:
$(document).ready(function(){
resetForms('reservation');
$('#form-reservation').submit(function(event){
event.preventDefault(); //the page will no longer refresh on form submit.
var resCheck = $(this).find('input[class="reservationid"]').val(); //now we have the reservation ID, let's perform our check.
document.cancel_res.cancel_agree.checked = false;
//document.cancel_res.cancel_agree.disabled = false;
document.cancel_res.cancel_button.disabled=true;
document.form_reservation.search_button.value="Searching...";
document.form_reservation.search_button.disabled=true;
$.ajax({
url: 'inc/searchres.php',
type: 'POST',
data: 'resid='+resCheck,
success: function(data){ //data is all the info being returned from the php file
resetForms('reservation'); //clear forms
document.form_reservation.search_button.value="Search Reservation";
document.form_reservation.search_button.disabled=false;
$('#reservation-id').val(resCheck); //add read ID back into text box
var jsonData = $.parseJSON(data);
//BLAH BLAH BLAH BLAH
}
});
});
});
The function works perfectly... however, is there anyway to call this function without utilizing the submit event? I tried to take out everything after the $('#form-reservation').submit(function(event){ call and place it in a separate function, and then call the function from the submit event. However, for whatever reason, this failed.
Basically, I want the submit event to still trigger this function, but I also want to be able to call the entire function under other circumstances. Thanks in advance!
It's actually pretty easy:
var MyFunc = function(event){
typeof event !== 'undefined' ? event.preventDefault() : false; //the page will no longer refresh on form submit.
var resCheck = $(this).find('input[class="reservationid"]').val(); //now we have the reservation ID, let's perform our check.
document.cancel_res.cancel_agree.checked = false;
//document.cancel_res.cancel_agree.disabled = false;
document.cancel_res.cancel_button.disabled=true;
document.form_reservation.search_button.value="Searching...";
document.form_reservation.search_button.disabled=true;
$.ajax({
url: 'inc/searchres.php',
type: 'POST',
data: 'resid='+resCheck,
success: function(data){ //data is all the info being returned from the php file
resetForms('reservation'); //clear forms
document.form_reservation.search_button.value="Search Reservation";
document.form_reservation.search_button.disabled=false;
$('#reservation-id').val(resCheck); //add read ID back into text box
var jsonData = $.parseJSON(data);
//BLAH BLAH BLAH BLAH
}
}
$(document).ready(function(){
resetForms('reservation');
$('#form-reservation').submit(MyFunc); //this calls on submit
});
//this calls without need of a submit
MyFunc();
I would simply trigger the handler.
$("#form-reservation").triggerHandler("submit");
http://api.jquery.com/triggerHandler/
As per the api docs, this does not cause the form to submit, it just run's the handlers bound to that event.
I have a very simple scenario where I want to POST the form using JQuery's ajax() method but perform request some confirmation from the user before actually performing the post.
I have a JQuery UI dialog with localized buttons in place in case you wonder what all the code with buttons below is about.
This is my code so far:
var i18n_deleteButtons = {};
i18n_deleteButtons[i18n.dialogs_continue] = function () {
return true;
$(this).dialog('close');
};
i18n_deleteButtons[i18n.dialogs_cancel] = function () {
return false;
$(this).dialog('close');
};
$('#delete-dialog').dialog({
open: function () {
$(this).parents('.ui-dialog-buttonpane button:eq(1)').focus();
},
autoOpen: false,
width: 400,
resizable: false,
modal: true,
buttons: i18n_deleteButtons
});
$("form#form_attachments").submit(function (event) {
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
var $form = $(this), url = $form.attr('action');
// build array of IDs to delete (from checked rows)
var jdata = { 'attachmentIdsToDelete': [] };
$('input:checked').each(function () {
jdata['attachmentIdsToDelete'].push($(this).val());
})
$.ajax({
beforeSend: function (request) {
// Return false if you don't want the form submit.
$('#delete-dialog').dialog('open');
},
url: url,
type: "POST",
dataType: "json",
data: jdata,
traditional: true,
success: function (msg) {
$('#msg').html(msg);
}
});
});
The dialog actually opens up fine but clicking at any of the buttons results in nothing happening. The post doesn't happen and the dialog does not close regardless of which button was clicked.
How can I make this work?
Why not move the actual ajax call from the submit handler and trigger it when pushing a button in the delete dialog?
You could store you ajax call in a separat function and pass this functions and the url as parameters to the confirmation routine.
[pseudo code]
function callAjax() {
...
}
function submitHandler() {
confirmDialog({callback:callAjax,param:you_url});
}
function confirmDialog(obj) {
$('#yes_btn').click(function() {
// call the callback
obj.callback(obj.param);
});
$('#no_btn').click(function() {
// just close the dialog
});
}
This way the confirmDialog don't have to know anything about the ajax call, it will just execute the callback with the given parameter when the user clicks ok.
Because the default jquery UI dialog is a bit cumbersome for regular use and trouble to configure in some custom scenarios I looked around and found this Easy Confirm plugin which is based upon jquery&jquery UI default stuff. It also allows for very simple internationalization.
https://github.com/wiggin/jQuery-Easy-Confirm-Dialog-plugin
I'm checking my form with RSV validator. Want to get work following: Let's say user opened page for the first time. After filling all text input boxes, when user clicks #submit_btn FOR THE FIRST TIME, the form submit function fires RSV (validator), validator checks if there is any error. If all right, posts data via ajax, else RSV shows error messages array with the help of alert(). THIS PROCEDURE ONLY FOR THE FIRST TIME
BTW: RSV - validator. If no error occured during validation process the myoncomplete() function returns 1.. If something went wrong it alerts. Got from here
I can't get it work. Please help me to fix logic/code mistakes. Thx in advance
My JS
var int=null;
var counter=0;
function myOnComplete() {
return 1;
}
$(document).ready(function () {
$("#add_form").RSV({
onCompleteHandler: myOnComplete,
rules: [
"required,name,Page name required",
"required,title,Page title required.",
]
});
$("#add_form").submit(function (e) {
e.preventDefault();
dataString = $("#add_form").serialize();
$.ajax({
type: "POST",
url: "processor/dbadd.php",
data: dataString,
dataType: "json",
success: function (result, status, xResponse) {
//do something if ajax call is success
int = setInterval(call, 3000);
var message = result.msg;
var err = result.err;
if (message != null) {
$.notifyBar({
cls: "success",
html: message
});
}
if (err != null) {
$.notifyBar({
cls: "error",
html: err
});
}
},
error: function (e) {
//ajax call failed
alert(e);
}
});
});
$("#submit_btn").click(function () {
if(counter===0){
if(myOnComplete()===1) $('#add_form').submit();
else return false;
}
else $('#add_form').submit();
counter++;
});
$('#autosave').click(function(){
if($(this).is(':checked')){
int = setInterval(call, 3000);
$('#submit_btn').attr({'value':'Save&Exit'});
}
else{
$('#submit_btn').attr({'value':'Save'});
clearInterval(int);
}
});
});
function call() {
$('#add_form').submit();
}
Looking through the RSV code it looks like whatever you attach RSV to has its submit rebound to validate the data using .RSV.validate()
As seen here:
$(this).bind('submit', {currForm: this, options: options}, $(this).RSV.validate);
});
Which means that if you use .submit() you are calling .RSV.validate also.
So once you validate the info try binding your submit to the standard submit function.
Edit: To help explain
When you use
$("#add_form").RSV({...});
The RSV javascript code is binding .RSV.validate() to the submit event of your add_form element. Meaning when you submit your add_form form .RSV.validate() is being called before the submit.
Try running the script code below with and without the .RSV() call
This script will log ALL handlers for ALL events on the add_form element. You notice that calling $element.RSV({...}) attaches a second event handler to the submit event of the add_form element. I am unsure of the best way to access this event handler to .unbind() it. Good luck :)
jQuery.each($('#add_form').data('events'), function(i, event){
jQuery.each(event, function(i, handler){
console.log(handler);
});
});
OK, to my understanding now you only want to validate the first set of data and if that validates correctly trust the user, i got this working on jsFiddle with an easy example, i guess you can make use of that
http://jsfiddle.net/WqnYa/9/
Basically what i do is that i catch the submit button click and not the forms submit function, maybe it can be done that way, too. I assign a class "needsvalidation" and when ever the first validation passes, i simply remove that class. And if that class is not present, the validation will not be initialized due to $(this).hasClass('needval')
If that's not what you're looking for then your question needs way more clarity :( hope this helps though!
this seems like it should be straightforward, but I'm having trouble getting it to work.
I have a .click bind to many buttons of a certain class. When that button is clicked, it passes its id to a $.post call for processing.
When the $.post call returns successfully, I'd like to remove the button and add a message to the container, but I can't seem to even access the button at that point.
Here is the .click bind:
$('.button').click(function() {
$.post('process.php', {
action: 'checkit'
},
function(result) {
if (result == 'win') {
// Access the button that was pressed with jQuery
}
else {
alert("fail");
}
});
});
I've tried, $(this), this, and also setting a variable like var trigger=this as I enter the initial click function, but none of these are working. I get undefined, or it points to the actual JQuery object, not the button.
Does anyone have any insight into how I can access the button that was clicked at that point, using a jQuery wrapper, essentially something like $( triggered button ).html() so that I can manipulate the correct button?
Thanks for your time.
$('.button').click(function() {
var clicked = $(this);
....
Use a local variable for temporary storage.
try this
$('.button').click(function() {
var $button = $(this);
$.post('process.php', {
action: 'checkit'
},
function(result) {
if (result == 'win') {
$button.doStuff();
}
else {
alert("fail");
}
});
});
It's quite easy to do:
$(this).foo('bar');
Is
$('.button').click(function() {
$.post('process.php', {
action: 'checkit'
},
function(result) {
if (result == 'win') {
$(this).html('something');
}
else {
alert("fail");
}
}.bind(this));
});
working?
jsfiddle example of what you are attempting. Click on the text. Just keep a local variable.