I am using ajaxForm to send data to php file which runs in background, and some js functions will be checking if php file is running asynchroniously. So in case of some failure(internet/electricity went off), I want my user be able to retry the last form submission. So I found some ajax retry functions as this, best way to retry ajax but it is on the same ajax request, i need to be able to retry my ajax from another function. Is it even possible? Given that I am storing passed values in form.
$(document).ready(function(){
$('#form').ajaxForm({
target: '#ajax-response',
success: function(){
initAjaxCheck();
}
});
Check();
});
So, basically lockcheck() checks if process is still runing after page refresh/reload, and if any failure was detected with prevous run, it should be able to retry the form submission.
Here's js scripts:
function Check(){
$.ajax({
type:"POST",
url:"ajax.php",
data:{'flag':'Check'},
success:function(result){
if (result=="1") {
initAjaxCheck();
}
}
});
}
function initAjaxCheck(){
$.ajax({
type:"POST",
url:"ajax.php",
data:{'flag':'initProcCheck'},
success:function(data){
if (data=="1"){
timerCheck=setInterval(function(){
ajaxCheck(timerCheck);
},1000);
} else { //unsuccessful
var toRepeat = confirm ("Last try was unsuccessful. Retry?");
if (toRepeat){alert("retry");} else {alert("cancel");}
}
}
});
}
So if my user press RETRY, I should have to retry my ajaxForm submission.
I'm a little confused with what exactly you are asking, however I believe I somewhat understand.
Trigger a form submission.
$('#form').trigger("submit");
or
var event = jQuery.Event("submit");
$('#form').trigger(event);
To implement this in your code, simply add it after your confirm function.
var toRepeat = confirm ("Last try was unsuccessful. Retry?");
if (toRepeat){
alert("retry");
$('#form').trigger("submit");
} else {
alert("cancel");
}
Related
Overview:
I'm using the JQuery Form Plugin to send Form Data to a remote file via AJAX. The File then processes the form data and inserts it into the MySQL Database.
Problem:
The Problem is, however, when I want to run code on a successful add, (usually completed using the "success" option, it never runs. Doing further research I found that I needed to send back "responseText" to make the function under "success" run.
Questions:
1) Is this true?
2) How do I go about sending back responseText?
3) (If number on is that it is not true) How do I get the function under success to run?
A few code Snippets:
JQuery (Using the JQuery Form Plugin):
$("#form1").ajaxForm({url: 'submit.php', type: 'post', resetForm: true, success: function () { $('#new-paste').modal({show: false}) }});
I can provide the contents of the remote file (submit.php) if needed.
Thank you in advance!
Change your success to:
function(response) {
$('#new-paste').modal({show: false});
alert(response); // response is the output from the php script it submitted to.
}
Hope this helps.
Alright, so I found the solution.
The Script had to be included on the page itself, not in a remote .js file.
so:
<script>
// wait for the DOM to be loaded
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#myForm').ajaxForm(function() {
alert("Thank you for your comment!");
});
});
</script>
Should be included in the head.
I have the below JavaScript code that iterates through a list of textfields on a page. It takes the text in the textfield as a price, sends it to the server via an AJAX GET, and gets the parsed double back from the server. If any of the returned prices are less than an existing price, the form shouldn't submit.
The problem is that the form is submitting before all the AJAX requests are finished because of the non-blocking immediate response nature of the Ajax calls. I need to set up a wait() function (or a callback when all the Ajax methods are complete) but don't know how to do that with jQuery.
Any suggestions?
// .submitForm is a simple button type="button", not type="submit"
$(".submitForm").click(function(e){
var submittable = validatePrices();
if (submittable) {
$("#myForm").submit();
}
});
function validatePrices() {
var submittable = true;
$(".productPrice").each(function(){
var $el = $(this);
$.ajax({
type: "POST",
url: "/get_price.jsp",
async: false,
dataType: "html",
data: "price=" + $el.val(),
success: function(data)
{
var price = new Number(data.split("|")[1]);
var minPrice = new Number($el.data("min-price"));
if (price < minPrice)
{
$el.addClass("error");
$(".dynamicMessage").show().addClass("error").append("<p>ERROR</p>");
submittable = false;
}
}
});
return submittable;
});
}
You're already using synchronous AJAX (a really bad idea for your user experience), so that's not the problem. The problem is that you need to cancel the default action in the "submit" handler:
$(".submitForm").click(function(e){
var submittable = validatePrices();
e.preventDefault(); // this line
if (submittable) {
$("#myForm").submit();
}
});
Using a synchronous HTTP request back to your server for each separate field is going to make your site terribly slow. You're going to have to check the parameters at the server again when you submit the form anyway, so it'd be much better to just check then and return an error.
edit — now that the situation is clearer, I think that the way to proceed is to stop doing the AJAX validation checks completely. Why? Well, even if you perform those tests, you still need to make essentially the same validity tests when the form is actually submitted. You can't rely on the JavaScript validation code actually running, as in any other form validation scenario. If you're doing the validation at form submission time anyway, it'll save on a bunch of HTTP requests to just do it all at the same time.
You're not canceling the form submission. You have to work strictly with the ajax callbacks (if you would like to use them asynchronously, which would be nice).
$(".submitForm").click(function(e){
e.preventDefault();
validatePrices().done(function () { /* ajax success function here */
if (submittable) {
$("#myform").trigger('submit');
}
}
});
function validatePrices() {
var checks = [];
$(".productPrice").each(function(){
var $el = $(this);
checks.push($.ajax({
/* snip */
});
return $.when.apply(null, checks);
}
Is it possible to check the Availability of a page before loading it?
I have a form, running on mobile device using wireless connection. The problem is: not always this connection is available and I would like to alert the user when is doing a submit or an unload of the page.
The problem is that the page contains elements doing redirect like this:
<input type="button" value="MyText" onClick="script1;script2;...window.location='mylocation'" />
If the user click on this button and the server is not achievable, i will receive some undesirable errors.
Also if I want to generalize my script i do not know the value of "mylocation" previously.
The page contains elements to submit the Form also:
<input type="submit" name="SUBMIT" value="MyValue" onClick="return eval('validationForm()')" />
For the submitting I'm using the ajaxForm plugin and it works quite well.
to navigate back easily use this instead:
<input type="button" value="Back" onClick="window.location='history.go(-1);" >
where -1 means previous page. If you want to reload the current page use 0 instead, to navigate forward, use 1, etc.
If you use ajax from jquery, it sould handle it by itself... http://api.jquery.com/jQuery.ajax/
$.ajax({
///... need argument here...
timeout: 5000, // in milliseconds
success: function(data) {
//Do something success
},
error: function(request, status, err) {
if(status == "timeout") {
alert("can't reach the server");
}
}
});
EDIT AFTER COMMENTS:
You can check How do I check if file exists in jQuery or JavaScript?
in your case this sould work as expected:
//Initialize the var as global so you can use it in the function below
var goto_url = "http://www.mywebsites.com/foo.html";
$.ajax({
url:goto_url;
type:'HEAD',
error: function()
{
//do something if the gile is not found
},
success: function()
{
document.location = goto_url; //docuemnt.location will redirect the user to the specified value.
}
});
this will actually check if the file exist.. If it can't connect to the file it will not be able to find it..
If he can find the file, he obviouly was able to connect, so either case you win.
cheers!
Thanks to your answer I found the solution to the problem.
This check if the server is achievable before launching a script and redirect.
That's the code:
function checkConnection(u,s){
$.ajax({
url:u,
cache:false,
timeout:3000,
error: function(jqXHR, textStatus)
{
alert("Request failed: " + textStatus );
},
success: function()
{
eval(s);
}
});
}
$(document).ready(function() {
// part of the function that checks buttons with redirect
// for any button that contain a redirect on onClick attribute ("window.locarion=")
$("input[type=button]").each(function(){
var script = $(this).attr("onClick");
var url = "my_url";
var position = script.indexOf("window.location") ;
if (position >= 0) { // case of redirect
url = "\'"+url+"\'"; // that's my url
script = "\""+script+"\""; // that's the complete script
$(this).attr("onClick","checkConnection("+url+","+script+")");
}
});
// part of the function that checks the submit buttons (using ajaxForm plugin)
var options = {
error: function() {
alert("Message Error");
},
target: window.document,
replaceTarget: false,
timeout: 3000
};
$("form").ajaxForm(options);
});
I hope that this will be usefull.
You should use the callback of the jQuery Ajax function to catch the problem of a server not available.
You cant check the servers' availibility without making a request to it.
You're trying to see if there is a connection. AFAIK the only way for actually checking if a server is reachable is making a request to that server.
Set a timeout of a reasonably small amount of time (let's say 3s) and make a request. If you get a timeout error, then there is no connection, else you're good to send the form.
I want to validate user entries on a WordPress post upon hitting the submit button, display an error message is there are problems, and submit the form if everything is OK. I have a PHP function that does the checking, returning true if data in form_data is OK, some error code otherwise. The following JavaScript issues the AJAX request, and was supposed to continue submitting the form upon successful checking, but it doesn't:
jQuery(document).ready(function() {
jQuery('#post').submit(function() {
var form_data = jQuery('#post').serializeArray();
var data = {
action: 'ep_pre_submit_validation',
security: '<?php echo wp_create_nonce( 'pre_publish_validation' ); ?>',
form_data: jQuery.param(form_data),
};
var proceed = false;
jQuery.post(ajaxurl, data, function(response) {
if (response.indexOf('true') > -1 || response == true) {
proceed = true;
} else {
alert("Error: " + response);
proceed = false;
}
});
jQuery('#ajax-loading').hide();
jQuery('#publish').removeClass('button-primary-disabled');
return proceed; //breakpoint here makes the code run
});
});
The code is adapted from a WPSE question, which originally didn't work for me as the form didn't get submitted. I found out that if the jQuery function bound to .submit() returns true, the form should be submitted, so that's what I tried to implement. With the code above, it doesn't seem to work at first (form doesn't get submitted when there are no errors), but upon close inspection with Firebug proceed seems to get the right result if a breakpoint is inserted at the return proceed line. It works as intended with valid data only if I wait it out a bit upon hitting the breakpoint, and then continue execution. If there are errors, the alert is issued without a problem.
What is the best way to handle this?
EDIT
Based on #Linus answer below, the following code works with both valid and invalid data:
jQuery(document).ready(function() {
jQuery('#post').submit(function() {
if(jQuery(this).data("valid")) {
return true;
}
var form_data = jQuery('#post').serializeArray();
var data = {
action: 'ep_pre_submit_validation',
security: '<?php echo wp_create_nonce( 'pre_publish_validation' ); ?>',
form_data: jQuery.param(form_data),
};
jQuery.post(ajaxurl, data, function(response) {
if (response.indexOf('true') > -1 || response == true) {
jQuery("#post").data("valid", true).submit();
} else {
alert("Error: " + response);
jQuery("#post").data("valid", false);
}
//hide loading icon, return Publish button to normal
jQuery('#ajax-loading').hide();
jQuery('#publish').removeClass('button-primary-disabled');
});
return false;
});
});
Short answer: You can't - not in this manner.
Some background: The callbacks you supply as arguments to functions such as $.post are executed asynchronously. This means that you will return proceed before your success callback has been executed, and proceed will always be false. With your breakpoint, if you wait until the success callback has executed, proceed will be true and all will be well.
So, if you want to submit the form after your ajax request has finished, you must submit it using javascript. This is pretty easy with jQuery, just do a jQuery $.post with data: $("yourForm").serialize() and url: yourForm.action.
This is basically what you already are doing, you just have to repeat that call to the URL to which you actually want to post the data.
EDIT:
Another way would be to set an attribute on your form, say valid, and in your submit handler check that:
jQuery("#post").submit(function() {
if($(this).data("valid")) {
return true;
}
// Rest of your code
});
And in the success callback for your validation ajax request you would set/clear that attribute, and then submit:
$("#post").data("valid", true).submit();
EDIT:
You also want to do your "ajax-loading"/button enabling inside the callback for $.post for the same reasons stated above - as it is, they will happen immediately, before your ajax call returns.
Bind your button to a validation function instead of submit. If it passes validation, call submit().
Wordpress has its own mechanism to process Ajax requests, using wp-admin/wp-ajax.php. This allows you to run arbitrary code on either side of the Ajax boundary without having to write the back and forth status-checking code and all that. Set up your callbacks and go....
The real question is - why are you doing validation server-side? Why can't you load in the validation criteria before - as the post is being written? Then your validation can happen real-time and not on-submit.
jquery.post is performed asynchronously, which means the JS will continue before it gets the reply. You're stuck with Diodeus's answer - bind the button to validtion which then submits the form (which makes it not degrade well), or change your $.post to ajax and turn off async, which will force it to wait for response before proceeding...possibly locking up JS on your page until it times out.
$.ajax({
type: 'POST',
url: ajaxurl,
async:false,
data: data,
timeout:3000,
success: function(){
}
});
I have a toolbar that exists on all my webpages that makes requests to a server side XML file regularly.
Some of the web pages also make requests to the same XML file, but more frequently. Ideally I would like to, where possible, combine this easily into a single request. Where the toolbar uses the same request that the page made (as the page refresh rate is greater than that of the toolbar)
Is there any way to tell if any jQuery AJAX calls have been made to a certain resources and, if so, be notified on success?
Update:
Based on Darin Dimitrov's answer I have tried the following:
$.ajaxSetup({
success: function(){ console.log("woop"); }
});
This never fires, I presume because the success handler is being overwritten when I make my other AJAX calls.
You could use the $.ajaxSetup() to subscribe for the common events.
Subscribe to all ajax events at the document level;
$(document).bind("ajaxSend", function(){
alert('ajax fired');
});
In your AJAX add response callback, something like this:
$.ajax({
type: "POST",
url: "mypage.php",
data: "name=John&location=Boston",
success: function(data){
alert(data);
}
});
and on your php page where you process AJAX request add some echo statement:
echo "POSTed OK!";
If you post is a success you'll get an alert confirmation.
You can also get a confirmation if it failes but modifying the code slightly:
success: function(result) {
if (result==1) {
alert('Success');
} else {
alert('Failed');
}
}
Good luck!