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.
Related
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
Here is what bothering me. My code is running on document.ready. I need the request to be asynchronous, meaning async: true
for (var i = 0; i < totalGraphs; i++) {
var kpiId = kpiIds[i];
jQuery.ajax({
type: 'POST',
url: graphUrl,
data: "kpiId="+kpiId+"&divId="+(i+1),
async: true, //if false things are working fine
cache:false,
success: function(response){
document.getDocumentById("graph" + (i + 1)).innerHTML("hello");
},
error:function(XMLHttpRequest, textStatus, errorThrown) {
}
});
}
This request does not put hello in my graphX divs, but whenever i put async: false things are working fine. I really need the request to be asynchronous.
Thanks in advance for any help.
Try this...
for (var i = 0; i < totalGraphs; i++){
(function ajaxCall(index) {
var kpiId = kpiIds[index];
jQuery.ajax({
type: "POST",
url: graphUrl,
data: {
kpiId : kpiId,
divId : index + 1
},
async: true, //if false things are working fine
cache: false,
success: function(response) {
document.getDocumentById("graph" + (index + 1)).innerHTML("hello");
},
error: function(XMLHttpRequest,textStatus,errorThrown) {}
});
})(i);
}
I've wrapped the ajax call in an anonymous function so that the value of i will never change, relative to the ajax call.
I'm guessing the i count is getting mixed up in your loop when success is returned. success will return after the loop has run through and thus this will give an unexpected result.
Can you return the i value that went sent in data in your response then use this in your getDocumentById method? I'm guessing this would fix your issue.
New code to try:
for(var i=0;i<totalGraphs;i++){
jQuery.ajax({
type: 'POST',
url: graphUrl,
data: { kpiId: kpiIds[i], divId: (i+1) },
async: true, //if false things are working fine
cache:false,
success: function(response){
document.getDocumentById("graph" + response.count).innerHTML("hello");
},
error:function(XMLHttpRequest,textStatus,errorThrown){}
});
}
First of all, you are running an ajax call inside a loop. This will be okay if you've turned off the async. But since you've turned on the async, the loop doesn't wait for the ajax to finish its work.
The best thing to do would be to get the values to a global variable using the inner loop ajax and then use the variable to draw the graph later.
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?
I'm having a trouble since jQuery.ajax, in this particular case, doesn't seem to happen, so that the function always return NaN undefined as result:
function requestUploadedSearch()
{
var cookie = JSON.parse(readCookie("user_search_cookie"));
$.ajax({
dataType: "script",
async: false,
data: {
context: "search-get",
code: removeNull(cookie, cookie !== null, "code")
},
success: function(data)
{
return search_return["keywords"];
}
});
delete cookie;
}
I've also tried to write something like
success: function() { return "<nothing happens>"; }
But what I receive is undefined.
Please answer, I'm really freaking out with that.
Thanks in advance.
What you're trying to do is fundamentally impossible. Your ajax operation is asynchronous (no it isn't durrr).
Instead, re-architect your API:
function requestUploadedSearch( callback )
{
var cookie = JSON.parse(readCookie("user_search_cookie"));
$.ajax({
dataType: "script",
async: false,
data: {
context: "search-get",
code: removeNull(cookie, cookie !== null, "code")
},
success: function(data)
{
callback( search_return["keywords"] );
}
});
delete cookie;
}
Then, when you invoke it, instead of expecting a return value, pass in a function to respond to the returned data:
requestUploadedSearch( function( value ) {
// ... do stuff with "value" ...
});
edit — Doh! #nickd is correct; since you're making the call synchronously (which you really should seriously consider not doing; it's pretty bad for your user experience) the story is different. Still, however, the approach above would work.
Pointy is pointing (hah) you in the more usual way of doing things. However as you have async: false set, your success: function is never called. Putting
return search_return["keywords"];
after the delete cookie line will return as you have it in your example, but you aren't using the result of the ajax call anywhere I can see, so I'm not sure that there's any point.
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
}
},