I open a jquery dialog, it opens very good, the content of this dialog is a form, one input of that form is:
<input onkeyup="testOnKeyUp();" type="text" name="userName" id="userName">
Here is where come my problem, it's suppose that when someone type a Key in this input the following code is activated and should run, but it just does not work.
var validateUserNameSpan = $j('#userNameSpan');
function testOnKeyUp(){
validate(this, validateUserNameSpan, 'username');
}
function validate(field, span, property) {
if (field.value != field.lastValue) {
if (field.timer) clearTimeout(field.timer);
field.timer = setTimeout(function () {
span.value = "";
span.removeClass('error').html('checking ...');
$j.ajax({
url: '/signup/'+property,
data: property + '=' + field.value,
dataType: 'json',
type: 'post',
success: function (json) {
updateMessage(span, json.success, json.message);
if(property=="email"){
emailValid = true;
}else if(property=="username"){
userNameValid = true;
}
},
error: function() {
ajFailureInitSignup(span);
if(property=="email"){
emailValid = false;
}else if(property=="username"){
userNameValid = false;
}
}
});
}, 400);
if(userNameValid && emailValid) document.getElementById('buttonLink').onclick=null ;
field.lastValue = field.value;
}
}
What am I doing wrong ?
I don't know but googling I've got info that make me feel that the:
$j.ajax({
that I'm running inside of this dialog (validate function) is not being executed, why I say that ? because this dialog is created in the DOM and after be created there this $j.ajax is not executed.
is this true ?
I really thank any help.
Ok, the main problem is that your AJAX call returns IMMEDIATELY after you issue it - this is normal (it's the first 'A' in ajax - asynchronous). That means your code continues on immediately to the if (usernamevalid && emailvalid) code section. Those variables do not exist at that point, as the AJAX call has not yet returned. So you're comparing undefined variables, which will also fail.
You have to move that comparison inside your ajax success/error handlers, so that the comparison will only be done when the ajax call has actually produced data that can be compared.
Related
I have created a button
<button type="submit" class="btn btn-info" name="enroll" onClick="return clicknow()">
in JS I have written clicknow function as follow :
<script>
function clicknow()
{
jQuery('#sheduling_wait').show();
var roll_number = jQuery('#roll_number').val();
var class_n = jQuery('#class_n').val();
//alert(class_n);
var FirstData = "roll_number=" + roll_number+"&class_n="+class_n;
var currenturl = jQuery(location).attr('href');
var url = currenturl;
jQuery.ajax({
dataType : 'html',
type: 'GET',
url : url,
data : FirstData,
complete : function() { },
success: function(data)
{
data1=jQuery(data).find('div#stfflistdiv');
//jQuery('#staff').show();
jQuery('#staff').html(data1);
var data2 = jQuery('#staff #stfflistdiv').html();
console.log(data2);
if(data2 == '2')
{
jQuery('#staff').show();
jQuery('#staff').html("This roll No is already Saved, Please add another roll no");
jQuery('#sheduling_wait').hide();
return false;
}
else
{
jQuery('#sheduling_wait').hide();
return true;
}
}
});
}
</script>
I have problem that when the value of data2 is equal to 2 then the page directs instead of staying on same page due to return false,
How can I stay on same page if data2 == 2 and submit when the value of data2 == 1
you have to do it like this
<button type="submit" class="btn btn-info" name="enroll"> <!-- remove onclick-->
and then
$(document).ready(function() {
$("#myform").submit(function(event){
if(data ==2)
{
event.preventDefault(); //prevent the default submit action
//...your code
}else{
//other code
}
});
});
The value you return from the success callback is not returned by the outer function. In fact, the success callback is not called until the ajax call returns, which is after the outer function has already returned.
Instead of adding an onclick attribute to the submit button, you can register a submit-event handler on the form. Inside the submit-event handler, you can call e.preventDefault() to stop the normal form submission. Then when the ajax call returns and you want the form to submit, you can call the form element's submit() method. (Do not call submit() on a jQuery object that represents the form, that would cause the submit-event handler to get called again, which would result in an infinite loop. You call submit() on the actual form element.)
<script>
jQuery(function($) {
$('#myForm').submit(function(e) { // <-- Use your form's id
e.preventDefault();
var form = this;
$('#sheduling_wait').show();
$.ajax({
type: 'GET',
url: $(location).attr('href'),
data: {
roll_number: $('#roll_number').val(),
class_n: $('#class_n').val()
},
dataType: 'html',
success: function(html) {
var $stfflistdiv = $(html).find('#stfflistdiv');
if ($stfflistdiv.html() == '2') {
$('#staff').html("This roll No is already Saved, Please add another roll no").show();
} else {
$('#staff').html($stfflistdiv).show();
form.submit();
}
},
complete: function() {
$('#sheduling_wait').hide();
}
});
});
});
</script>
Note:
Register the event handler in a document-ready handler. That is the jQuery(function($) { part of the code above. The jQuery object is passed as the first parameter, so if you name it $, you can then safely use $ to represent jQuery inside the function even if you have called jQuery.noConflict().
Use an object for the ajax data setting, rather than concatenating your own query string. It's cleaner, plus the values get properly encoded.
Use the complete callback to hide the #sheduling_wait element since complete executes even when there is an error.
the return statement return data for succes function. not for clicknow()
options:
set variable in clicknow initial in false.
var ret=false;
and set ajax async:false (not recommended)
into success function set your variable for true or false;
if(data2 == '2') { ret=false; } else { ret=true; }
and into end function clicknow return ret;
sorry my english.
regards.
I have a simple page that takes a form and makes a jsonp ajax request and formats the response and displays it on the page, this is all fine, but I wanted to add it so that if the form was populated (via php $_GET variables) then the form would auto-submit on page load but what happens instead is that the page constantly refreshes despite the submit function returning false.
Submit Button (just to show it doesn't have an id like submit or anything)
<button type="submit" id="check" class="btn btn-success">Check</button>
jQuery
$(document).ready(function() {
$('#my_form').on('submit', function() {
var valid = 1;
$('#my_form .required').each(function() {
if ($(this).val() == '') {
$(this).parents('.form-group').addClass('has-error');
valid = 0;
} else {
$(this).parents('.form-group').removeClass('has-error');
}
});
if (valid === 1) {
$.ajax({
url: '/some_url',
data: $('#my_form').serialize(),
type: 'GET',
cache: false,
dataType: 'jsonp',
success: function(data) {
var html = 'do something with data';
$('#results').html(html);
},
error: function() {
$('#results').html('An error occurred, please try again');
}
});
} else {
$('#results').html('Please fill in all required fields');
}
return false;
});
});
The part I added just after the $(document).ready(function(){ and before the submit was:
if ($('#input_1').val() != '' || $('#input_2').val() != '') {
// $('#check').trigger('click');
$('#my_form').submit();
}
Both those lines have the same effect but I am doing the same in another project and it works fine, as far as I can see, the only difference is the jQuery version, I'm using 1.11 for this page.
Update
Apologies, I seem to have answered my own question, I thought that since the programmatic submit was the first thing in $(document).ready(function(){ then maybe it was the case that the actual submit function wasn't being reached before the event was triggered so I simply moved that block after the submitfunction and it now works fine.
url: ''
it seems like you are sending your ajax request to nothing.
just an additional: if you want to submit your form through jquery without using AJAX, try
$("#myForm").submit();
it will send your form to the action attribute of the form, then redirect the page there.
I have a button that calls a function in javascript. The javascript in turn runs two consecutive ajax calls. After the first one finishes, it does some extra work, then runs the second ajax call.
The button works upon first clicking it. However, when I want to click it again the following error pops up...
Uncaught TypeError: object is not a function
It is in reference to my function that is being called 'onclick' from the button.
I am pretty new to ajax but I'm sure that this shouldn't be happening. Other buttons are working just fine, and they all call functions from the same script. It just seems to be this one function. I would have expected there to be a semicolon missing or something, but then the first time wouldn't have worked... Also, I do know that the function finished executing, since I debugged the function and it reaches the bottom...
Here are my ajax calls in case you're interested...
var $response = $.ajax({
url: $abs_filename,
type: 'HEAD',
async: false,
success: function () {
console.log('done');
}
}).status;
($response != "200") ? $exist = false : $exist = true;
....lots of extra code here
....
var response = $.ajax({
type: 'POST',
url: '/SERT/includes/file_operations.php',//url of receiver file on server
data: {saves: $save_data}, //your data
dataType: 'text', //text...
success: function(res) {
alert(res);
},
async: false
}).status;
EDIT:
My function is called by
<input type="button" .... onclick="save_session()">
You've not actually shown the code that is causing the error.
However...
Don't do this; it doesn't do what you think it does.
($response != "200") ? $exist = false : $exist = true;
Do this:
$exist = $response == "200";
And just DON'T use synchronous XHR.
I was able to figure it out...
So I had a jQuery append operation going on inside of the save_session() function. This operation was as such...
$bottom_section.append('<input type="hidden" name="save_session" value="' + $total + ' ' + $paragraph + '">');
When I took this out then the whole thing worked as expected. My guess is that by naming the input "save_session" messed with the function definition of save_session() in memory. Now there wasn't a definition conflict, then it was okay.
What's the best way to trigger errors on elements for server-side validation errors that come back after the form passes the initial client-side validation?
$("#contact_form").validate({
submitHandler: function(form) {
$.ajax({
type: 'POST',
dataType: 'json',
url: '/contact/send',
data: $(form).serialize(),
success: function(response) {
if(response.error) { //server came back with validation issues
var fields = response.fields;
for(var i=0, var len = fields.length; i < len; i++) {
var field_name = fields[i].name;
var field_error = fields[i].error;
// TRIGGER ERROR ON AFFECTED ELEMENT
}
return false;
}
//everything went ok, so let's show a thanks message
showThanks();
}
}
});
I'm thinking something like:
$(form).find("[name='" + field_name + "']").triggerError(field_error);
But I didn't see any api methods for manually triggering errors in that manner.
I think I figured it out from the documentation of Validator/showErrors
var validator = $("#contact_form").validate();
validator.showErrors({"state": "Bad state."});
Make it. Write a plugin that will do whatever you want.
Or if you get to complicated, simply write a javascript function to do it and call that.
I would write a plugin that would create a div, fill it with the error text and animate it nicely.
On submit of the form, I would make the target of the form an invisible iframe on the page which would then call a function in the topWindow with it's result.
<iframe id="subject_frame" name="submit_frame" src="#" style="width:0;height:0;border:0px solid #fff;"></iframe>
then in the page in the iframe call a javascript method in the top window that either redirects on success or displays the errors.
In the iframe
<script language="javascript" type="text/javascript">
window.top.window.submitComplete("<?php echo $response; ?>");
</script>
In the top window (as an example)
function uploadComplete( result ){
$.unblockUI();
if(result == "OK"){
$.blockUI({ message: "<span style='color:green;'>File upload successful, request submitted.</span><br/><br/>Redirecting..." });
setTimeout(function() {
$.unblockUI({
onUnblock: function(){ window.location='thankyou.php'; }
});
}, 2000);
} else {
$.blockUI({ message: "<span style='color:red;'>Failed.</span><br/><br/>"+result });
$('.blockOverlay').attr('title','Click to remove').click($.unblockUI);
}
}
Inside a tab, I have a form that is dynamically loaded via ajax. Since the name of the field is dynamic too(e.g. <input name='title1' id='title1', class='tRequired'>), I write a custom validation method inside the "on complete" like this. However, the custom code does not get executed (the alert never pops up) no matter what i try.
$.ajax
(
{
url: 'index.php?func=trainingmgr&aAction=displayAddForm', <br>
type: 'GET',<br>
dataType: 'html',<br>
complete: function(req, err)
{
//Append response to the tab's body <br>
$(href, '#trainingTabs').append(req.responseText);
$.validator.addMethod
(
'tRequired',
function(value, element)
{
if(value == '')
{
alert('I am empty'); <====== Never pops up
return true;
}
else return false;
},
'<br>Required field'
);
$('#upload' + index).click
(
function()
{ $('#addForm' + index).validate(); }
);
}
}
);
Try
value == null
Similar to Jeremy's answer,
Try
value === ''