ajax, if successful refresh after 3 seconds - ajax

title says it all, the way the script currently works is if its successful, it brings back a message back from my php code, i want it to also refresh the page after 3 seconds
$(function(){
$('button[type=submit]').click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "postadvert.php",
data: $("#myform").serialize(),
beforeSend: function(){
$('#result').html('<div class="success"><img src="../../images/loading-blue.gif" width="25" /></div>');
},
success: function(data){
$('#result').html(data),
$('#result2').html('<meta http-equiv="refresh" content="3">'); // i added that doesn't working
}
});
});
});

A couple of things. First, you need a semicolon after your first line in the success function. Next, you can use the setTimeout function in javascript where you pass a function and a time to wait in milliseconds. Lastly, you can call the location.reload() to refresh the page.
success: function(data){
$('#result').html(data);
setTimeout(function(){location.reload();},3000);
}

Include the following in your success callback:
window.setTimeout(function() {
document.location.href = document.location.href;
}, 3000);
Assigning to document.location.href automagically causes the browser to load the URL so assigned; assigning its own value back to it therefore causes a refresh. The window.setTimeout() call tells the browser to wait three seconds, then run the function given as its first argument.

Related

AJAX loading image barely visible

I have a simple issue. I am posting data from a form to my DB using an AJAX request. I have coded in a loading GIF using the beforeSend and complete commands in my AJAX request.
<script>
$(function(){
//email the link
$("##emailTicket#get_active_tickets.ticket_id#").submit(function(){
// prevent native form submission here
$.ajax({
type: "POST",
data: $('##emailTicket#get_active_tickets.ticket_id#').serialize(),
url: "actionpages/email_dashboard_ticket.cfm",
beforeSend: function(){
$('.loader').show()
},
complete: function(){
$('.loader').hide();
},
success: function() {
$("##emailTicketResponse#get_active_tickets.ticket_id#").html("");
$("##emailTicketResponse#get_active_tickets.ticket_id#").append( "Ticket successfully sent." );
}
});
return false;
});
});
</script>
Everything seems to be working correctly however the loading GIF only flashes for a split second because the request doesn't take long at all to complete. Sometimes you can't even see it and users are confused if clicking the submit button actually did anything.
Is there a way to delay the 'complete' part of the function so that the animated GIF appears on the screen longer?
complete: function(){
$('.loader').hide();
},
I was able to achieve this by modifying my complete code in my function and adding a delay in milleseconds:
complete: function(){
$('.loader').hide(3000);
},

Using form data to dynamically construct url using ajax

I have the following ajax code that takes in 3 variables and passes them to a php file, and this is all fine and dandy. I want to do a redirect using the value stored in one of these variables. I figured I could just do window.location.href = within the success in the ajax call, but for some reason, it doesn't seem to respond to the click, and simply does nothing.
Here is the ajax function, hope y'all can help!
$("#findItem").click(function() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position){
$.ajax({
type: 'get',
url: 'http://plato.cs.virginia.edu/~aam3xd/cabbage/closestBuildingWeb.php',
data: {
foodItemId: $('#foodItem').val(),
sentLongitude: position.coords.longitude,
sentLatitude: position.coords.latitude
},
success: function(data){
//$('#answer').html(data);
//the following line doesn't seem to be executing....
window.location.href = foodItemId+"/"+sentLatitude+"/"+sentLongitude;
}
});
});
I think you should use your url into that window.location
window.location.href = "www.example.com/"+foodItemId+"/"+sentLatitude+"/"+sentLongitude;

load mypage.php via ajax into a div in wordpress

i have an ajax load request working in wordpress, but i would like to load the content from another page into the container div. at the moment it just passes the url in $dataToSend as a string?
jQuery(document).ready(function(){
var $dataToSend = "my-page.php";
var $testBtn = jQuery('#text-ajax-btn');
var $holdingCtn = jQuery('#my-holding-ctn');
$testBtn.click(function(){
jQuery.ajax({
type:'POST',
url: myAjax.ajaxurl,
data:{
action:'myAjax',
dataToSend:$dataToSend,
},
success: function(data,textStatus,XMLHttpRequest){
$holdingCtn.html("");
$holdingCtn.append(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
alert(errorThrown);
}
});
});
});
how can i pass an entire .php page through as the $dataTosend?
I do this all the time for wordpress, give me a sec to access my repository and I will show you example code.
I think problem is your my-page.php! I imagine you custom coded it. So it doesn't have necessary functions loaded.
put following code at the top of your my-page.php (this will help with 500 error you are getting)
require('../../../wp-load.php');
ajax part should look something like this:
//start ajax
$.ajax({
url: "http://localhost/wp-content/themes/theme/my-page.php",
type: "POST",
data: data,
cache: false,
success: function (data) {
console.dir(data);
}
})
If you want to load content from my-page.php file then you can load from the server side using
$data = file_get_contents('path/to/file/my-page.php'); // pass right path/url
Then, just echo the content from your function (registered ajax handler in WordPress using add_action) and in this case it should be
echo $data;
die(); // terminate the further execution
So, it should look something like
add_action( 'wp_ajax_myAjax', 'yourAjaxHandler' );
add_action( 'wp_ajax_nopriv_myAjax', 'yourAjaxHandler' );
function yourAjaxHandler(){
$data = file_get_contents('path/to/file/my-page.php');
die($data); // echo out the string and terminates execution
}
In your success callback, you can use
success: function(data){
jQuery('#my-holding-ctn').html(data);
}
Not sure if this is fully applicable, but the super easy way is just
$("#myDiv").load("myFile.php?foo=1&bar=2...");

Fade out on Ajax submit

I have this ajax submit script. It does submit properly and pops up the thank you message, but it does not fade out in 3.2 seconds. The goal is to have the message "Thank you for updating." pop up for a few seconds each time a user clicks on an update button (#tracking_submit).
$('#tracking_submit').click(function(){
$.ajax({
url: "php/tracking.php",
type:'POST',
data: dataString,
success: function(){
$('#tracking_message').replaceWith("Thank you for updating.");
$('#tracking_message').delay(3000).fadeOut(300);
}
});
return false;
});
I solved this issue this way
$('#tracking_submit').click(function(){
$.ajax({
url: "php/tracking.php",
type:'POST',
data: dataString,
success: function(){
$('#tracking_message').html("Thank you for updating.").fadeIn('slow');
setTimeout(function(){$('#tracking_message').fadeOut('slow');},2000);
}
});
return false;
});
Try using this:
setTimeout(function() { $('#foo').fadeOut(); }, 5000);
.delay() doesn't play well with anything else since the timer keeps ticking and a .dequeue() is executed when it's up...regardless of if you cleared the queue and added a whole new one.
It's better to use setTimeout() directly. setTimeout() is a native javascript function.

Ajax request error when changepage

guys. I have a juerymobile multi-page, and I have a button in #page-index, when click it, will send a ajax request to server, and changepage to #page-column, It run will in PC, but when i deploy the multi-page in phonegap, the button click can just run only twice, code is below:
function test()
{
$.mobile.changePage('#page_column');
$.ajax({
url: "http://192.168.168.120:8090/fcmobile/getTest",
dataType: "json"
}).done(function(data) {
alert(data.content);
});
}
I found if I remove $.mobile.changePage('#page_column');, the ajax request can be run well any times. but when I add the changePage code, it only can be run twice, in third time, ajax request can't even be send. Dose anybody know reason?
AJAX is made to be asynchronous, so no need to set async to false to get it working. Use events instead.
For example:
function test () {
$.ajax({
'url': "http://192.168.168.120:8090/fcmobile/getTest",
'dataType': 'json',
'success': function (json_data) {
$(document).trigger('test_json_data_loaded');
console.log(data);
}
});
}
$(document).on('test_json_data_loaded', function () {
$.mobile.changePage('#page_column');
});
When you set async to false, you're basically making it so that every time this AJAX request is made, the user will have to wait until all the data is fully loaded before the application/website can do/execute anything else...not good.

Resources