still looking for a solution but not find yet, I have a function to manage different forms on same/differents pages
function formStantardAction(correctAnswer,addCustomData){
addCustomData = (typeof addCustomData == "undefined")?'':addCustomData;
correctAnswer = (typeof correctAnswer == "undefined")?'Saved.':correctAnswer;
$('form.standard').submit(function(event){
event.preventDefault();
var modalWin = $(this).parent();
var values = $('form.standard').serialize() + addCustomData;
$.ajax({
url: "inc/gateway.php",
data: values,
type: "POST",
success: function(data){
if (data == "OK"){
$(modalWin).html(correctAnswer).delay(500).fadeOut(500);
setTimeout(function() {
mw_close();
}, 1000);
}else{
alert(data);
}
}
});
});
}
after loaded the page and form with an input type="button" named SEND
$('form.standard [name="SEND"]').click(function(){
var str = $('#sortableTo').serializelist();
formStantardAction('New train inserted.',str);
$('form.standard').submit();
});
all the values reach a php page via POST that made all the things (validating, insert in db, update log...) and answer with 'OK' if all OK (so the form in the modal window is substituted with custom message and fade out) or... if there is an error, php answer with some text that js popups with an alert keeping the modal window open with the form.
It's all ok BUT, if php answer with an error, with second click of button SEND the post is sent 2 times.
And if I make another error on second send, and click again the send button, the post values is sent three time... and so on.
What can I do? Where is my error?
thanks.
Try excluding submit block:
function formStantardAction(correctAnswer,addCustomData){
addCustomData = (typeof addCustomData == "undefined")?'':addCustomData;
correctAnswer = (typeof correctAnswer == "undefined")?'Saved.':correctAnswer;
//$('form.standard').submit(function(event){
// event.preventDefault();
//change 'this' to form.standard
var modalWin = $('form.standard').parent();
var values = $('form.standard').serialize() + addCustomData;
$.ajax({
url: "inc/gateway.php",
data: values,
type: "POST",
success: function(data){
if (data == "OK"){
$(modalWin).html(correctAnswer).delay(500).fadeOut(500);
setTimeout(function() {
mw_close();
}, 1000);
}else{
alert(data);
}
}
});
});
// }
and after loaded page:
$('form.standard [name="SEND"]').click(function(){
var str = $('#sortableTo').serializelist();
formStantardAction('New train inserted.',str);
//excluding submit event
// $('form.standard').submit();
});
Because $.ajax {} with type:"Post" is already a submit process and then when script call submit then it re-submit.
Hope this right and help
Is it possbile that somewhere in your code you bind the submit event to the form everytime you get the data back from the ajax-request?
I can't check this in the code you submitted here.
Create a global variable as flag
var flag = 0;
and check this flag while posting and reset it after completed
function formStantardAction(correctAnswer,addCustomData){
**if(flag == 1){
return false;
}
flag = 1;**
addCustomData = (typeof addCustomData == "undefined")?'':addCustomData;
correctAnswer = (typeof correctAnswer == "undefined")?'Saved.':correctAnswer;
$('form.standard').submit(function(event){
event.preventDefault();
var modalWin = $(this).parent();
var values = $('form.standard').serialize() + addCustomData;
$.ajax({
url: "inc/gateway.php",
data: values,
type: "POST",
success: function(data){
**flag = 0;**
if (data == "OK"){
$(modalWin).html(correctAnswer).delay(500).fadeOut(500);
setTimeout(function() {
mw_close();
}, 1000);
}else{
alert(data);
}
}
});
});
}
I put some custom code at the beginning of your submit function - basically if a submit is in progress nothing should be done, but otherwise return an error message as usual.
var submitting = false; //initialise the variable, this needs to be out of the function!
function formStantardAction(correctAnswer,addCustomData){
addCustomData = (typeof addCustomData == "undefined")?'':addCustomData;
correctAnswer = (typeof correctAnswer == "undefined")?'Saved.':correctAnswer;
$('form.standard').submit(function(event){
if (submitting) {
return false; //if a submit is in progress, prevent further clicks from doing anything
} else {
submitting = true; //no submit in progress, but let's make one now
}
event.preventDefault();
var modalWin = $(this).parent();
var values = $('form.standard').serialize() + addCustomData;
$.ajax({
url: "inc/gateway.php",
data: values,
type: "POST",
success: function(data){
if (data == "OK"){
$(modalWin).html(correctAnswer).delay(500).fadeOut(500);
setTimeout(function() {
mw_close();
}, 1000);
}else{
alert(data);
}
}
});
});
}
Related
<script type="text/javascript">
//$('#student').change(function() {
$('#but').click(function() {
var payid = $("#feType").val();
var course = $("#course").val();
var course_id = $("#course_id").val();
var stud_id = $("#student").val();
var paid_amt1 = $("#paid_amt").val();
var serializedData = $("form").serialize();
$.ajax({
dataType: "json",
url: '<?php echo ADMINPATH;?>student/getNewFee/'+payid+'/'+course_id+'/'+stud_id+'/'+course,
data: '',
async: true,
success: function(data){
if(data == false){
$("form").unbind('submit').submit();
alert("This student doesn't have transport");
return false;
}
var result = data;
if(Number(result) >= Number(paid_amt1)){
$("#fee_data").submit(function(){
return true;
});
}else {
$("form").unbind('submit');
alert("Due Amount is less than paid amount");
return false;
}
}
});
});
</script>
If the data is coming to if condition the form has to submit, and if data is coming to else condition form submitting should stop. "if" condition is working well, but coming to else the form is still getting submitted.
You are calling submit() method from else portion.
Remove below code from else portion.
$("form").unbind('submit').submit();
Remove this line, it is not needed and you are triggering the submit with it:
$("form").unbind('submit').submit();
If you only want to remove the on submit callback, you can do this:
$("form").unbind('submit');
You need to add a return false before the end of the click event:
$('#but').click(function() {
// ....
return false;
});
I have created a button on my website when it is clicked, I sent data on some php file using ajax and return the results. The code I am using is below,
My Goal :
When that button is clicked for the first time. I want to send the data on some php file using ajax and return the results, and
When it is clicked for the second time, I just want to hide the content, and
When it is clicked for the third time, I just want to show the container without calling the ajax again.
jQuery:
$(function() {
$('#click_me').click(function(){
var container = $('#container').css('display');
var id = $('#id').html();
if(container == 'none'){
$.ajax({
type: 'POST',
data: {id: id},
url: "ajax/get_items.php",
}).done(function(data) {
$('#container').html(data);
}).success(function(){
$('#container').show('fast');
});
}else if(container == 'block'){
$('#container').hide('fast');
}
});
});
Html :
<input type="button" id="click_me" value="Click Me"/>
<div id="container"></div>
The jQuery way would be like this:
$(function() {
$('#click_me').one('click', function() {
$.ajax({
// ... other params ...,
success: function(result) {
$('#container').html(result).show('fast');
$('#click_me').click(function() {
$('#container').toggle('fast');
});
});
});
});
});
http://api.jquery.com/one/
http://api.jquery.com/toggle/
You can use the counter
http://forum.jquery.com/topic/making-a-number-counter
(function () {
var count = 0;
$('table').click(function () {
count += 1;
if (count == 2) {
// come code
}
});
})();
JQuery Mouse Click counter
Working Example of your code :-
http://jsfiddle.net/2aQ2g/68/
Something like this should do the trick...
$("#click_me").click(function(){
var $btn = $(this);
var count = ($btn.data("click_count") || 0) + 1;
$btn.data("click_count", count);
if ( count == 1 ) {
$.ajax({
var container = $('#container').css('display');
var id = $('#id').html();
if(container == 'none'){
$.ajax({
type: 'POST',
data: {id: id},
url: "ajax/get_items.php"
})
}
else if ( count == 2 ) {
$('#container').hide('fast');
}
else {
$('#container').show('fast');
$btn.unbind("click");
}
return false;
});
One way to do it would be to add a class call count using jQuery every time the user clicks on the button (http://api.jquery.com/addClass/) and you can get the count value in the handler and based on that you can handle the click appropriately.
You can do this by defining a simple variable counting the clicks.
$(function() {
var clickCount = 1; //Start with first click
$('#click_me').click(function(){
switch(clickCount) {
case 1: //Code for the first click
// I am just pasting your code, if may have to change this
var container = $('#container').css('display');
var id = $('#id').html();
if(container == 'none'){
$.ajax({
type: 'POST',
data: {id: id},
url: "ajax/get_items.php",
}).done(function(data) {
$('#container').html(data);
}).success(function(){
$('#container').show('fast');
});
}else if(container == 'block'){
$('#container').hide('fast');
}
break;
case 2:
//code for second click
break;
case 3:
//Code for the third click
break;
});
clickCount++; //Add to the click.
});
So I'm creating this form validator with PHP and jQuery.
The PHP code will check through the form and then return an array with fields that contain errors. Example: {"email":1,"password":1}
But now I have concerns regarding if no errors were to be found. The problem here is that I've included "return false" in the end of the code to prevent page redirection. I've read that this is bad code practice but not found another way that works as intended.
The second problem is how to pass the o-array into the $('input').each function. Right now it will say that all forms are valid since nothing was passed. If I use $.post instead of $.ajax this scope problem doesn't appear for some reason.
jQuery:
$(function() {
$('#register').submit(function() {
var url = $(this).attr('action');
var data = $(this).serialize();
$.ajax({
type: 'GET',
url: url,
data: data,
success: function(o) {
console.log(o);
$('input').each(function() {
var msgId = o[$(this).attr('name')];
console.log(o[$(this).attr('name')]);
if (msgId > 0) {
$('#listError').css('visibility', 'visible');
$('#listError').append('<li>' + $(this).nextAll('span.msg').eq(msgId - 1).text() + '</li>');
$(this).addClass('invalid');
} else if (msgId != 0) {
$(this).addClass('valid');
}
$('#listError').append('</ul>');
})
}
}, 'json');
return false;
});
});
Fist, why are you submitting a form when you really don't want to?! Use a button instead and make the AJAX request from its click handler.
$('#registerButton').click(function() {
var form = $('#register')
var data = form.serialize();
$.ajax(...);
});
"The second problem is how to pass the o-array into the $('input').each"
What is the problem here? If you have an each() inside a success callback, you can use the data parameter that is passed to the callback (or o in your case) in that each().
Try this
$(function() {
$('#submit_button_id').click(function() {
var url = $(this).attr('action');
var data = $(this).serialize();
var ret = true;
$.ajax({
type: 'GET',
url: url,
async: false,
data: data,
success: function(o) {
console.log(o);
$('input').each(function() {
var msgId = o[$(this).attr('name')];
console.log(o[$(this).attr('name')]);
if (msgId > 0)
ret = false;
$('#listError').css('visibility', 'visible');
$('#listError').append('<li>' + $(this).nextAll('span.msg').eq(msgId - 1).text() + '</li>');
$(this).addClass('invalid');
} else if (msgId != 0) {
$(this).addClass('valid');
}
$('#listError').append('</ul>');
})
}
}, 'json');
if(ret==true){
$('#register').submit();
}
});
});
I have an Jquery submit textarea, now I want to set textarea submit without button submit. Just using enter key.
<textarea id="ctextarea"></textarea>
Here it's the JS :
$('.comment_button').live("click",function()
{
var ID = $(this).attr("id");
var uid = $("#uid").val();
var comment= $("#ctextarea"+ID).val();
var dataString = 'comment='+ comment + '&msg_id=' + ID + '&uid=' + uid;
if(comment=='')
{
$('#ctextarea').html("").fadeIn('slow');
$("#ctextarea"+ID).focus();
}
else if (!$.trim($("#ctextarea"+ID).val()))
{
$("#ctextarea"+ID).focus();
}
else
{
$.ajax({
type: "POST",
url: "comment_ajax.php",
data: dataString,
cache: false,
success: function(html){
$("#commentload"+ID).append(html);
$("#ctextarea"+ID).val('');
$("#ctextarea"+ID).focus();
}
});
}
return false;
});
I already search the tutorials and found, but I confused where can I put the code in My JS code.
Someone can give the idea ?
Thanks for helps.
$('#ctextarea').on('keyup', function(e){
if(e.which == 13 || e.keyCode == 13){
//enter key pressed..
}
});
You can subscribe to a keydown/keyup event and submit the form inside the event handler:
var KEY_ENTER = 13;
$('#ctextarea').keyup(function (event) {
if (event.keyCode === KEY_ENTER) {
$('form').submit();
// Or perform any necessary ajax calls here
}
});
i am having some problems with getting my form to submit. It doesnt seem like anything is being send, is their anything wrong with this code as javascripting isn't my strong point...
$("#send").click(function() {
var complete = true;
$('input#name, input#email, input#subject, textarea#message').each(function() {
if ($(this).val()) {
$(this).css("background","#ffffff").css("color","#5c5c5c");
} else {
$(this).css("background","#d02624").css("color","#ffffff");
complete = false;
}
});
if (complete == true){
var name = $("input#name").val();
var email = $("input#email").val();
var subject = $("input#subject").val();
var message = $("textarea#message").val();
var data = '{"name":"'+name+'","sender":"'+email+'","subject":"'+subject+'","message":"'+message+'"}';
$.ajax({
type:"POST",
url:"contact.php",
data:$.base64.encode(data),
success:function(data){
data = $.parseJSON(data);
if (data.status == "success") {
$.fancybox.close();
}
}
});
}
});
There is also a live version of this in action which can be viewed over at: http://idify.co.uk, thanks :)
You can do it better.
$('form')
.submit(function(event) {
var form = $(this);
$.ajax({
url: '[url here]',
type: 'post',
data: $.base64.encode(form.serialize()), // $.serialize() - it gets all data from your form
dataType: 'json', // function in success callback knows how to parse returned data
success: function(data) {
if (data['status'] == true) {
// your code here
// e.g.
$.fancybox.close();
}
}
});
event.preventDefault();
});
Enjoy! :)
I got an error after submitting:
data is null http://idify.co.uk/javascripts/landing.js Line 25
It looks like the data was sent successfully and there was a response:
{"status":"error","responce":"No token parameter was specified."}
This should help you ensure you've got data in your success callback:
success:function(response) {
if (response) {
var data = $.parseJSON(response);
if (data && data.status == "success") {
$.fancybox.close();
}
} else {
// handle errors
}
}
Haha, thanks guys. I was silly enough not to include the variable that needs to be passed via the php file, got it sorted and it works like a dream, i ended up using the first solution as the form submission one wasnt working for me.