I have an ajax request as follows:
jQuery.ajax({
type: 'GET',
url: '/logical_interface/delete',
context: this, // had to add this to get the line in the success function to work, never used it before nor do I understand why it works
data: 'id=' + id,
beforeSend: function() {
// jQuery(this).parent().html('processing...');
// if this line is uncommented then the DOM will be updated correctly
// but the snippet in the success function won't fire but the delete
// is still executed on the server side
// the page is then stuck with the 'processing' text
},
success: function(data) {
jQuery(this).closest('tr').stop().animate({ backgroundColor: '#ffc6be' }, 'fast').hide('slow');
}
});
Update
Server side code is simply the following Rails method:
def delete
#logical_interface = LogicalInterface.find(params[:id])
#logical_interface.destroy
render :text => '1' // which is what I get in console.log
end
As mentioned in comments, the reason your success may not work is because you deleted the $(this) node.
What you are doing in your beforeSend function is going up one level and replacing ALL HTML with "processing...". This in turn deleted your reference point jQuery(this) from the DOM before the success case is reached. if jQuery(this) is removed then nothing happens (obvious).
Instead of overwriting the entire html with Processing, may i suggest you have a single element hidden until you trigger the ajax and show it beforeSend and hide it with the complete function.
Related
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.
Consider the code below. If myField1 does NOT equal myField2, then the alert appears. When I click okay on the alert pop up my form is still there, with all of the fields still populated with the data I had previously entered. However, when I modify the fields so that myField1 DOES equal myField2, and then submit the form it is actually submitted TWICE! Why is this?
$(document).ready(function(){
$("#myForm").submit(function() {
var myField1 = $('#myID1).val();
var myField2 = $('#myID2).val();
if(myField1 == myField2)
{
$.ajax({
type: "POST",
url: 'myFile.php',
dataType: 'html',
data: {myData:myField1,
myData2:myField2},
success: function(data){
alert(data);
}
});
return false;
}
else
{
alert('These two fields are not equal!)
}
});
});
Okay, so I found this on another question and it solves the problem:
$('#myForm').unbind('submit').bind('submit',function() {
// do stuff here...
});
By unbinding the event, then re-binding it, the form no longer submits twice.
Your submit event is going to fire the submit action of the form unless you prevent it from doing so. Running an AJAX call in does not prevent this from happening. You need to stop this yourself.
You need:
$("#myForm").submit(function(event) {
event.preventDefault()
...
I have the following code I am using to submit my form to a processing script. the form gets submitted but I am getting redirected to the response html from the server. I want to stay on the same page and run the callback function inside success:
the response header is sending
location:http://url-I-am-Redirected-to-and-don't-want-to-be.html
I am working with third party and have no control over the server side code I am submitting to.
$('#go').click (function () {
$.ajax ( {
type: 'POST',
data: $('#newsletter form').serialize(),
url: $('#newsletter').attr('action'),
success: function(){
$('#image_container').hide (1000,
);
}
});
}
At the end of the click block add
return false
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.
I have a button that performs an ajax post -- I want to disable the button, then perform my work, then upon completion -- I want to re-enable the button. My interaction includes swapping out the image button (to a grayed out image button), and presenting a spinner. When complete, I hide the spinner and restore the original button image.
My approach includes unbinding, then rebinding the click event.
Here's my code -- it works great -- but, I want to know if this is a proper/efficient/acceptable strategy?
// Update club name
$j('#btnUpdateClubName').bind('click', updateClubName);
function updateClubName() {
var $this = $j(this);
var $spinner = $this.next('.spinner');
var renderURL = RES.BuildClubUpdateURL("UpdateClubName");
$this.ajaxStart(function() {
$this.attr("src", imgPathSaveAndUpdateBtnDisabled).unbind('click').addClass('wait-cursor');
$spinner.show();
});
$j.ajax({ type: "POST", data: $j('#hidStandingOrderId, #txtClubName, #clubOrderIdEditClubName').serialize(), url: renderURL, dataType: 'html', contentType: 'application/x-www-form-urlencoded',
success: function(data) {
// do some stuff
}
}
});
$this.ajaxComplete(function() {
$spinner.hide();
$this.attr("src", imgPathSaveAndUpdateBtn).bind('click', updateClubName).removeClass('wait-cursor');
$j("#cbEditClubName").colorbox.close();
});
}
What you have works but it is a bit wasteful, as it adds a new ajaxStart and ajaxComplete handler each time the function runs, I would make one suggestion though, change your .unbind() call to be more specific since you have the information. If you change this:
.unbind('click')
To this:
.unbind('click', updateClubName)
You can have other click events without the .unbind() interfering, it'll only unbind that one handler.
An overall better alternative (to me, you can debate whether it's "better") without rebinding would be to store a variable to know you're currently posting using $.data() and .data(), for example:
$j('#btnUpdateClubName').bind('click', updateClubName);
function updateClubName() {
if($.data(this, "posting")) return false; //are we posting? abort!
$.data(this, "posting", true); //set variable
var $this = $j(this);
var $spinner = $this.next('.spinner');
var renderURL = RES.BuildClubUpdateURL("UpdateClubName");
$this.attr("src", imgPathSaveAndUpdateBtnDisabled).addClass('wait-cursor');
$spinner.show();
$j.ajax({ type: "POST", data: $j('#hidStandingOrderId, #txtClubName, #clubOrderIdEditClubName').serialize(), url: renderURL, dataType: 'html', contentType: 'application/x-www-form-urlencoded',
success: function(data) {
// do some stuff
$spinner.hide();
$this.attr("src", imgPathSaveAndUpdateBtn).removeClass('wait-cursor')
.data("posting", false); //clear it out, ready to post again
$j("#cbEditClubName").colorbox.close();
}
});
}
With this approach if you're doing a POST the data for "posting" is true, and future clicks just abandon out...not until the response comes back and your success code runs is the button re-enabled. It's the same effect but no duplicate handlers and no re/un-binding.