Modifying jQuery $.ajax() success method during request - javascript

In the web app I am working on there is potential for very long running ajax queries.
I'm using jQuery's $.ajax method to do something like:
this._xhr = jQuery.ajax({
type: "GET",
url: "/path/to/service",
data: "name=value",
success: function(data, message){
// handle a success
},
dataType: "json"
});
Is there a way to modify the success callback after this._xhr.readyState = 2 (loaded) and before this._xhr.readyState = 4 (completed)
I tried modifying this._xhr.onreadystatechange but found that jQuery does not define onreadystatechange.

The abort method sounds like the best option to me.
I don't know much about the ajax method internals, but I can think of a few ways to do what you want. Both involve global state and would break if it's possible for your user to send a second request before the first has finished, so I'm not sure I recommend them.
First, you could keep a reference to the method that does your success work, and change it:
MySuccessMethod = function(d, m) { /* handle a success */ };
this._xhr = jQuery.ajax({
type: "GET",
url: "/path/to/service",
data: "name=value",
success: function(data, message){ MySuccessMethod(data, message); },
dataType: "json"
});
// later...
// user cancels request, so change the success method
MySuccessMethod = function(d, m) { /*print a simple message*/ }
Alternatively, you could just put all the logic in the one success method, and use a global flag to determine what to do:
success: function(data, message){
if (RequestHasBeenCancelled) {
//display a simple message
}
else {
// handle a success
}
},

Related

A part of AJAX response storing in PHP variable

I need to store a piece of data, into PHP variable, which is received through AJAX response in an input box. How can I do this?
<script type="text/javascript">
$(document).ready(function() {
$("#user_id").change(function() {
var id = $(this).val();
var dataString = 'user_id='+ id;
$.ajax({
type: "POST",
url: "wmat_details.php",
data: dataString,
cache: false,
success: function(result) {
var data = result.split(",");
$('#name').val(data[0]);
$('#email').val(data[1]);
$('#ref_id').val(data[2]);
$('#candidature_start').val(data[3]);
$('#candidature_end').val(data[4]);
$('#default_attempts').val(data[5]);
$('#existing_complimentary').val(data[6]);
$('#wmat_start').val(data[9]);
$('#wmat_end').val(data[10]);
$('#attempts_taken').val(data[11]);
}
});
});
});
</script>
As shown in above code, I want to store $('#attempts_taken').val(data[11]); this value to a PHP variable. Any insight is appreciated.
Unfortunately you can't.
PHP is server side while jQuery (JS) is client side. They are two separate layers of abstraction that interact only when the client call the server.
I don't have enough informations about what you need to do with data[11] but it seems that you have only one option: make a consecutive AJAX call to the php file that will manipulate data[11].
The consecutive AJAX call must be executed from inside the first call success callback; something like this:
success: function(result){
// Your on success logic
// ...
// Prepare the object to send to the server
var objData = {};
objData.attemptsTaken = data[11];
// Execute the second AJAX call to the server
$.ajax({
type: "POST",
url: "second_call_destination_file.php",
data: objData,
success: function(result){
// Do something on success
},
error: function(){
// Do something on error
},
complete: function(){
// Do something on complete (executed after success and error)
}
}
You cannot store ajax response into a php variable.
way 1 :
You can make another ajax call.
way 2 :
you can set session.

Uncaught TypeError: object is not a function (in AJAX callback)

I am trying to update a FullCalendar object using a function that receives an array of events.
$('#sh1_cal').fullCalendar({
events: function(callback) {
$.ajax({
type: 'GET',
url: 'http://localhost:8080/getEvents',
dataType: 'json',
success: function(reply) {
//var events = [];
console.log("printing " + reply.first)
alert(typeof reply.first);
callback(reply.first);
}
});
}
});
Reply is intended to be an object containing two arrays as its properties. I'm extracting the first, and it seems that the typeof alert is returning the correct type, but the callback is not working. Any suggestions?
I have not used this plugin but from the docs (http://arshaw.com/fullcalendar/docs/event_data/events_function/) it looks like the events function takes 3 parameters: start, end, and callback.
Start and end are date objects indicating when the event starts and ends. The way you have it now, that function thinks there is a date object called 'callback' which is why you're getting the error. In JavaScript the name of the parameter is not important (for example you can call it 'cb' or 'foo' instead of 'callback') but the order is.
Try (untested):
$('#sh1_cal').fullCalendar({
events: function(start, end, callback) {
$.ajax({
type: 'GET',
url: 'http://localhost:8080/getEvents',
dataType: 'json',
success: function(reply) {
callback(reply.first);
}
});
}
});
Try this:
$('#sh1_cal').fullCalendar({
events: 'http://localhost:8080/getEvents'
});
Shouldn't be any need for writing your own ajax call, it's built in.
If that doesn't work, can you post the output of your JSON feed?
try this and let me know if it works:
$('#sh1_cal').fullCalendar({
events: function(cb) {
$.ajax({
type: 'GET',
url: 'http://localhost:8080/getEvents',
dataType: 'json',
success: function(reply) {
return cb(reply.first);
//or try: cb(reply.first);
}
});
}(callback)
});
if not that, remove the return on the callback.
did either work?
*please note: I assume that "callback" is a function you are passing in and have instantiated it somewhere.
Event (As Function) in fullcalendar has been changed. Now the third parameter is timezone.
Further information on FullCalendar Documentation v2

jQuery ajax success callback function - how to make it anonymous?

I am unable to get the success callback to work in a jQuery ajax call. The following code calls interpretResponse() just fine, but of course resultJSON is undefined:
var that = this;
jQuery('#fsForm1492441').submit(function(event) {
event.preventDefault();
jQuery.ajax({ type: "POST",
url: "format_result.php",
data: jQuery(this).serialize(),
success: that.interpretResponse(),
dataType: "json"
});
});
function interpretResponse(resultJSON) {
// code here to handle resultJSON
}
I want something like:
success: function(resultJSON) {
that.interpretResponse(resultJSON);
},
How should the success callback be written?
just do this :
success: interpretResponse,
your code will look like this -
var that = this;
jQuery('#fsForm1492441').submit(function (event) {
event.preventDefault();
jQuery.ajax({
type: "POST",
url: "format_result.php",
data: jQuery(this).serialize(),
success: interpretResponse,
dataType: "json"
});
});
function interpretResponse(resultJSON) {
// code here to handle resultJSON
}
The answer above was correct, but it turned out that I was dealing with a different problem. The weird bug in FireFox that keeps ajax calls from getting past readyState 1 was causing the callback function to not load. I ended up using the workaround described here:
Ajax won't get past readyState 1, why?
Basically getting Firefox to set the callback onload rather than onreadystatechange.
Thanks to pXL for the answer to the question the way I asked it.

Ajax function to PHP

I have two problems here, 1st the code below won't work, anybody could tell me what am i missing? 2nd, i want to return the value from php to success function and then that value also will be returned to the parent function...
function myFunc(e){
$.ajax({
type: "post",
url: "path/myPhp.php",
data: "val="+e,
dataType: "php",
success: function(result){
return result; //i want this result to be returned to parent function myFunc(e)
},
error: function(e){
alert('Error: ' + e);
}
});
}
There is no data type named php for jquery ajax.
legal data type is as below:
xml
html
script
json
jsonp
text
Do you mean "json" data type?
If you want your response to return as function return value, then you need to make it ajax synchronize and later ajax unsynchronize after ajax finish
If your return response is not array ,then I think this will work.
function myFunc(e){
var returnValue = '';
$.ajaxSetup({async:false}); // synchronize
$.ajax({
type: "post",
url: "path/myPhp.php",
data: "val="+e,
success: function(result){
returnValue = result;
},
error: function(e){
alert('Error: ' + e);
}
});
$.ajaxSetup({async:true});// Unsynchronize
return returnValue;
}
1) You have an invalid value in 'dataType'. Valid values are: xml, json, script, or html.
2) As I see it, you want the ajax call to behave in a synchronous way.
Use 'async: false' to accomplish that. Try:
function myFunc(e){
var value = "";
$.ajax({
type: "post",
url: "path/myPhp.php",
data: "val="+e,
dataType: "json",
success: function(result){
value = result;
},
error: function(e){
alert('Error: ' + e);
},
async: false // set synchronous
});
alert(value); // use value
}
Or
$.ajaxSetup({async:false});
before issuing $.ajax() call.
A discussion about using synchronous ajax can be found here How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?

Save temporary Ajax parameters in jQuery

I am developing a heavily scripted Web application and am now doing some Error handling. But to do that, I need a way to access the AJAX parameters that were given to jQuery for that specific AJAX Request. I haven't found anything on it at jquery.com so I am asking you folks if you have any idea how to accomplish that.
Here is an example of how I want to do that codewise:
function add_recording(filename) {
updateCounter('addRecording','up');
jQuery.ajax({
url: '/cgi-bin/apps/ajax/Storyboard',
type: 'POST',
dataType: 'json',
data: {
sid: sid,
story: story,
screen_id: screen_id,
mode: 'add_record',
file_name: filename
},
success: function(json) {
updateCounter('addRecording','down');
id = json[0].id;
create_record(id, 1, 1, json);
},
error: function() {
updateCounter('addRecording','error',hereBeData);
}
})
}
hereBeData would be the needed data (like the url, type, dataType and the actual data).
updateCounter is a function which updates the Status Area with new info. It's also the area where the User is notified of an Error and where a Dismiss and Retry Button would be generated, based on the Info that was gathered in hereBeData.
Regardless of calling complete() success() or error() - this will equal the object passed to $.ajax() although the values for URL and data will not always be exactly the same - it will convert paramerters and edit the object around a bit. You can add a custom key to the object to remember your stuff though:
$.ajax({
url: '/',
data: {test:'test'},
// we make a little 'extra copy' here in case we need it later in an event
remember: {url:'/', data:{test:'test'}},
error: function() {
alert(this.remember.data.test + ': error');
},
success: function() {
alert(this.remember.data.test + ': success');
},
complete: function() {
alert(this.remember.data.url + ': complete');
}
});
Of course - since you are setting this data originally from some source - you could rely on the variable scoping to keep it around for you:
$("someelement").click(function() {
var theURL = $(this).attr('href');
var theData = { text: $(this).text(); }
$.ajax({
url: theUrl,
data: theData,
error: function() {
alert('There was an error loading '+theURL);
}
});
// but look out for situations like this:
theURL = 'something else';
});
Check out what parameters you can get in the callback for error.
function (XMLHttpRequest, textStatus, errorThrown) {
// typically only one of textStatus or errorThrown
// will have info
this; // the options for this ajax request
}
You can use the ajax complete event which passes you the ajaxOptions that were used for the request. The complete fires for both a successful and failed request.
complete : function (event, XMLHttpRequest, ajaxOptions) {
//store ajaxOptions here
//1 way is to use the .data on the body for example
$('body').data('myLastAjaxRequest', ajaxOptions);
}
You can then retireve the options using
var ajaxOptions = $('body').data('myLastAjaxRequest');

Categories