Hello guys I want to do one thing: from back end i receive a number and if it's equal to one i want to do one condition and if it's equal to 2 i want to repeat ajax, until condition would be equal to one, can someone explain me how to do it? :) here is the code:
<script type="text/javascript">
$(document).ready(function() {
$(".match").click(function(){
$.ajax({
url: 'includes/matchmaking.php',
success: function (data) {
alert("Isejo" + data);
//if data is equal to 1 do this
//if data is equal to 2 repeat ajax request
}
});
});
});
</script>
p.s. i am getting data from back end using php
Thank you in advance :)
function getData(){
$.ajax({
url: 'https://jsonplaceholder.typicode.com/posts/1',
success: function(data) {
console.log(data)
if(data.id === 1){
console.log('is equal to 1 do this')
}
if(data.id === 2){
console.log('call getData again')
getData()
}
}
})
}
getData()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Wrap ajax in function and call it from inside it on appropriate condition.
It can make infinite loop, but I'm sure you are aware of that
You can do jQuery trigger to repeat ajax request.
$(document).ready(function() {
var oncourse = false;
$(".match").click(function() { // can be changed to id selection - $('#match')
if (oncourse == true) return;
oncourse = true;
$.ajax({
url: 'includes/matchmaking.php',
success: function(data) {
if (data == '1') {
// do something
oncourse = false;
} else if (data == "2") {
// do something
oncourse = false;
$('.match').trigger('click');
}
}
});
});
});
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 am validating a form with ajax and jquery in WordPress post comments textarea for regex. But there is an issue when i want to alert a error message with return false. Its working fine with invalid data and showing alert and is not submitting. But when i put valid data then form is not submit. May be issue with return false.
I tried making variable and store true & false and apply condition out the ajax success block but did not work for me.
Its working fine when i do it with core php, ajax, jquery but not working in WordPress .
Here is my ajax, jquery code.
require 'nmp_process.php';
add_action('wp_ajax_nmp_process_ajax', 'nmp_process_func');
add_action('wp_ajax_nopriv_nmp_process_ajax', 'nmp_process_func');
add_action('wp_head', 'no_markup');
function no_markup() {
?>
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery('form').submit(function (e) {
var comment = jQuery('#comment').val();
jQuery.ajax({
method: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: 'action=nmp_process_ajax&comment=' + comment,
success: function (res) {
count = res;
if (count > 10) {
alert("Sorry You Can't Put Code Here.");
return false;
}
}
});
return false;
});
});
</script>
<?php
}
And i'm using wordpress wp_ajax hook.
And here is my php code.
<?php
function nmp_process_func (){
$comment = $_REQUEST['comment'];
preg_match_all("/(->|;|=|<|>|{|})/", $comment, $matches, PREG_SET_ORDER);
$count = 0;
foreach ($matches as $val) {
$count++;
}
echo $count;
wp_die();
}
?>
Thanks in advance.
Finally, I just figured it out by myself.
Just put async: false in ajax call. And now it is working fine. Plus create an empty variable and store Boolean values in it and then after ajax call return that variable.
Here is my previous code:
require 'nmp_process.php';
add_action('wp_ajax_nmp_process_ajax', 'nmp_process_func');
add_action('wp_ajax_nopriv_nmp_process_ajax', 'nmp_process_func');
add_action('wp_head', 'no_markup');
function no_markup() {
?>
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery('form').submit(function (e) {
var comment = jQuery('#comment').val();
jQuery.ajax({
method: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: 'action=nmp_process_ajax&comment=' + comment,
success: function (res) {
count = res;
if (count > 10) {
alert("Sorry You Can't Put Code Here.");
return false;
}
}
});
return false;
});
});
</script>
<?php
}
And the issue that i resolved is,
New code
var returnval = false;
jQuery.ajax({
method: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
async: false, // Add this
data: 'action=nmp_process_ajax&comment=' + comment,
Why i use it
Async:False will hold the execution of rest code. Once you get response of ajax, only then, rest of the code will execute.
And Then simply store Boolean in variable like this ,
success: function (res) {
count = res;
if (count > 10) {
alert("Sorry You Can't Put Code Here.");
returnval = false;
} else {
returnval = true;
}
}
});
// Prevent Default Submission Form
return returnval; });
That's it.
Thanks for the answers by the way.
Try doing a ajax call with a click event and if the fields are valid you submit the form:
jQuery(document).ready(function () {
jQuery("input[type=submit]").click(function (e) {
var form = $(this).closest('form');
e.preventDefault();
var comment = jQuery('#comment').val();
jQuery.ajax({
method: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: {'action':'nmp_process_ajax','comment':comment},
success: function (res) {
var count = parseInt(res);
if (count > 10) {
alert("Sorry You Can't Put Code Here.");
} else {
form.submit();
}
}
});
});
});
note : you call need to call that function in php and return only the count!
Instead of submitting the form bind the submit button to a click event.
jQuery("input[type=submit]").on("click",function(){
//ajax call here
var comment = jQuery('#comment').val();
jQuery.ajax({
method: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: 'action=nmp_process_ajax&comment=' + comment,
success: function (res) {
count = res;
if (count > 10) {
alert("Sorry You Can't Put Code Here.");
return false;
}else{
jQuery("form").submit();
}
}
});
return false;
})
Plus also its a good idea to put return type to you ajax request.
Let me know if this works.
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.
});
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);
}
}
});
});
}
I have looked around quite a bit and it seems absolute urls is the way to go here. I have no problem in chrome but firefox and IE IE still wants to redirect fully to the wrong page.
my states:
<script type="text/javascript">
$(function() {
$('#page_submit').click(function () {
event.preventDefault();
$('.standard span').hide();
var pw = $("input#pw").val();
if (pw == "") {
$("span#pw_err").show();
$("input#pw").focus();
return false;
}
var pw2 = $("input#pw2").val();
if (pw2 == "") {
$("span#pw2_err").show();
$("input#pw2").focus();
return false;
}
if (pw != pw2) {
$("span#match_err").show();
$("input#pw2").focus();
return false;
}
var data = 'pw=' + pw + '&pw2=' + pw2;
$('.standard input').attr('disabled','true');
$('.loading').show();
$.ajax({
url: "/members/includes/change.php",
type: "GET",
data: data,
cache: false,
success: function (html) {
//hide the form
$('#pw_form').fadeOut('slow');
//display results
$('#pw_form_result').fadeIn('slow');
$("#pw_form_result").html(html);
}
});
return false;
});
});
</script>
the structure of the file I am trying to access is:
www.site.com/members/includes/change.php
Not sure what the cause is really. I know the jquery initiator is working because i can summon alert calls to and from the function itself.
edit
after commenting out
event.preventDefault();
it seems to function right? everything I had read before said this was a necessary piece however.
This line
$('#page_submit').click(function () {
should be
$('#page_submit').click(function (event) {
so this code
event.preventDefault();
can take effect.
And the 'return false;' is unneccesarry.