Passing a parameter along with callback? - jquery-callback

This is my code:
var title = 'test'
function onlineStatus(callback){
$.ajax({
url: "https://blabla,
cache: false,
success: callback
});
onlineStatus(function(test) {
// doing stuff with `test`
$('#forTest').attr('title', title);
});
The problem is that the onlineStatus call doesn't see title, which is correct, because it is out of scope. Is there a way to pass it into the function, so that the title is seen?

function statusCheck (test) {
console.log(test);
}
function onlineStatus (callback) {
callback (arguments[1]);
}
onlineStatus (statusCheck, "test");

Related

jquery -jtable- listAction get object from javascript function

Is it possible that listAction not call server function use AJAX , and the function will call to javascript function that return object ?
$('#ExecActDelays').jtable({
actions: {
listAction://get object from javascript no call server method
},
///...
can help me?
thank
i solve my proble, by edit jquery.jtable.js
my script:
function getObject(){
var result={};
result.Result="OK";
var array=[];
//...
{
array.push(new object...);
}
result.Records=array;
return result;
}
$('#ExecActDelays').jtable({
actions: {
listAction: getObject()
},
and in jquery.jtable.js i change
self._ajax({
url: loadUrl,
data: self._lastPostData,
success: function (data) {
self._hideBusy();
//Show the error message if server returns error
if (data.Result != 'OK') {
self._showError(data.Message);
return;
}
//Re-generate table rows
self._removeAllRows('reloading');
self._addRecordsToTable(data.Records);
self._onRecordsLoaded(data);
//Call complete callback
if (completeCallback) {
completeCallback();
}
},
error: function () {
self._hideBusy();
self._showError(self.options.messages.serverCommunicationError);
}
});
}
to:(line 442)
if (typeof loadUrl == "string") {
self._ajax({
url: loadUrl,
data: self._lastPostData,
success: function (data) {
self._hideBusy();
//Show the error message if server returns error
if (data.Result != 'OK') {
self._showError(data.Message);
return;
}
//Re-generate table rows
self._removeAllRows('reloading');
self._addRecordsToTable(data.Records);
self._onRecordsLoaded(data);
//Call complete callback
if (completeCallback) {
completeCallback();
}
},
error: function () {
self._hideBusy();
self._showError(self.options.messages.serverCommunicationError);
}
});
}
else {//no from server method
self._hideBusy();
//Re-generate table rows
self._removeAllRows('reloading');
self._addRecordsToTable(loadUrl.Records);
self._onRecordsLoaded(loadUrl);
//Call complete callback
if (completeCallback) {
completeCallback();
}
}
my complete my jquery.jtable.js
Try do this
function foo(){
return object;// JSON object
}
$('#ExecActDelays').jtable({
actions: {
listAction: foo()
},
///...
OR try this too
var object = null;
function foo(){
object = objectJSON;
}
$('#ExecActDelays').jtable({
actions: {
listAction: object
},
///...

Backbone Model URL responseText

I have the following:
DiaryEntries.Collection = Backbone.Collection.extend({
url: '/rest/diary/'
});
So I initiate a collection like so:
var collection = new DiaryEntries.Collection()
And then collection.fetch() returns this:
Object {readyState: 1, getResponseHeader: function, getAllResponseHeaders: function, setRequestHeader: function, overrideMimeType: function…}
abort: function ( statusText ) {
always: function () {
complete: function () {
done: function () {
error: function () {
fail: function () {
getAllResponseHeaders: function () {
getResponseHeader: function ( key ) {
overrideMimeType: function ( type ) {
pipe: function ( /* fnDone, fnFail, fnProgress */ ) {
progress: function () {
promise: function ( obj ) {
readyState: 4
responseJSON: Array[1]
responseText: "[{"DEID":"1","DEOwnerID":"1","DEClientID":null,"DEDateStart":"2013-06-28 00:00:00","DEDateEnd":"2013-06-29 00:00:00","DEEventLocationID":null,"DEJobID":null,"DEName":"Ricky's test event","DELocation":"Kettering","DEFurtherDetails":"None","DEVisibility":"0","DENotes":"None","DEType":"1"}]"
setRequestHeader: function ( name, value ) {
state: function () {
status: 200
statusCode: function ( map ) {
statusText: "OK"
success: function () {
then: function ( /* fnDone, fnFail, fnProgress */ ) {
__proto__: Object
Why is it not just getting the response? I have a mime type of application/json
Call to the server are AJAX calls (asynchronous). What fetch returns is the XHR object, not the response (as the server hasn't responded yet). To do something once the client received the data, use a callback or a listener (or something similar).
For example, you can declare a parse method to see the reponse (it's not the actual goal of the method, but whatever):
DiaryEntries.Collection = Backbone.Collection.extend({
url: '/rest/diary/',
parse: function(response) {console.log(response); return response;}
});

How to return result from function that has an $.ajax call

I'll say right off the bat that this question seems to address the same situation, but for the life of me I'm not seeing what the solution/answer is there. Perhaps someone just needs to "spell it out" more clearly for me!
I have the following function:
function CheckIfUrlExists(checkUrl) {
var exists = '';
$.ajax({
type: 'POST',
url: '../scripts/branchAdmin.php',
data: {checkUrl: checkUrl},
cache: false,
success: function(response) {
console.log('response: ' + response);
if (response === 'true') {
exists = 'true';
} else if (response === 'false') {
exists = 'false';
}
},
error: function(response) {
// return false and display error(s) from server
exists = 'false';
}
});
console.log('exists: ' + exists); // always displays empty string, regardless of what the php script returns
return exists;
}
And I'm calling it with this:
var exists = CheckIfUrlExists($tr.find('input.editUrl').val());
if (exists === 'false') {
//if (!CheckIfUrlExists($tr.find('input.editUrl').val())) {
// New URL entered, verify user want to save it
$('#confirmAddNewUrlDialog').data('row', $tr).dialog('open');
... // code to handle result
}
How can I get the "CheckIfUrlExist() function to return a true or false (or any value for that matter) so I can use it in the above code?
Make the ajax call async option to false. then you'll get the result.
see the link https://stackoverflow.com/a/1531710/399414
$.ajax({
type: 'POST',
async: false,
url: '../scripts/branchAdmin.php',
...

jquery validation onSubmit ajax post JSON response

I have a very complicated post using jquery validation and an AJAX post that gets a JSON response back from the server and puts it in a jqGrid... But it seems as though my onsuccess is never being called at any point...
$(document).ready(function () {
$("#formSearchByMRN").validate({
rules: {
MRN: { required: true, minLength: 6 }
},
messages: {
MRN: 'Please Enter a Valid MRN'
},
submmitHandler: function (form) {
e.preventDefault();
animateLoad();
debugger;
var theURL = form.action;
var type = form.methd;
var data = $(this).serialize();
$.ajax({
url: theURL,
type: type,
data: data,
dataType: "json",
success: function (result) {
debugger;
var data = result;
if (data.split(':')[0] == "Empty record") {
$("#list").unblock();
$('#resultDiv').html('<b><p style="color: #ff00ff">' + data + '</p></b>');
setTimeout(function () {
$('#resultDiv').html("");
}, 10000);
}
else {
binddata(data);
}
}
});
return false;
}
});
});
It would seem I never get into the submmitHandler. Event though I manage to get to my server side function and it does return, it prompts my UI to save a file which contains the JSON results...
No good.
Am I going about validating my form before my AJAX post the wrong way? Does anybody have any advice about best practices in validating AJAX posts?
UPDATE... MARK R. This is what I attempted. It seems as though I never get in to the success function... My suspicion is that I am not really posting via ajax, but instead doing a full post. I don't understand why.
$('#submitMRN').click(function () {
$("#formSearchByMRN").validate({
rules: {
MRN: { required: true, minLength: 6 }
},
messages: {
MRN: 'Please Enter a Valid MRN'
}
});
if ($('#submitMRN').valid()) {
$("#list").block({ message: '<img src="../../Images/ajax-loader.gif" />' });
$.ajax({
url: $('#submitMRN').action,
type: $('#submitMRN').method,
data: $('#submitMRN').serialize(),
dataType: "json",
success: function (result) {
debugger;
var data = result;
if (data.split(':')[0] == "Empty record") {
$("#list").unblock();
$('#resultDiv').html('<b><p style="color: #ff00ff">' + data + '</p></b>');
setTimeout(function () {
$('#resultDiv').html("");
}, 10000);
}
else {
binddata(data);
}
}
});
}
});
$('#SubmitButton').click(function (){
//Check that the form is valid
$('#FormName').validate();
//If the Form is valid
if ($('#FormName').valid()) {
$.post(...........
}
else {
//let the user fix their probems
return false;
}
});//$('#SubmitButton').click(function (){

how to return ajax suceess from user defined function [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I am having the bellow function .
Here i want to return ajax success from user defined function . How to do this
alert(Ajaxcall(id_array,"del"));
function Ajaxcall(id_array,type){
$.ajax({
type: "POST",
url: "serverpage.php",
cache:false,
data: ({id:id_array,type:type}),
success: function(msg){
return msg; //this returns nothing
}
});
alert(msg); // this one undefined
}
thanks
The "a" in "ajax" stands for "asynchronous" ("Asynchronous JavaScript And XML", although these days most people use it with JSON rather than XML).
So your Ajaxcall function returns before the ajax call completes, which is why you can't return the message as a return value.
The usual thing to do is to pass in a callback instead:
Ajaxcall(id_array,"del", functon(msg) {
alert(msg);
});
function Ajaxcall(id_array,type, callback){
$.ajax({
type: "POST",
url: "serverpage.php",
cache:false,
data: ({id:id_array,type:type}),
success: function(msg){
callback(msg);
}
});
}
It's surprisingly easy with JavaScript, because JavaScript's functions are closures and can be defined inline. So for instance, suppose you wanted to do this:
function foo() {
var ajaxStuff, localData;
localData = doSomething();
ajaxStuff = getAjaxStuff();
doSomethingElse(ajaxStuff);
doAnotherThing(localData);
}
you can literally rewrite that asynchronously like this:
function foo() {
var localData;
localData = doSomething();
getAjaxStuff(function(ajaxStuff) {
doSomethingElse(ajaxStuff);
doAnotherThing(localData);
});
}
I should note that it's possible to make an ajax call synchronous. In jQuery, you do that by passing the async option in (setting it false). But it's a very bad idea. Synchronous ajax calls lock up the UI of most browsers in a very user-unfriendly fashion. Instead, restructure your code slightly as above.
But just for completeness:
alert(Ajaxcall(id_array,"del"));
function Ajaxcall(id_array,type){
var returnValue;
$.ajax({
type: "POST",
url: "serverpage.php",
cache:false,
async: false, // <== Synchronous request, very bad idea
data: ({id:id_array,type:type}),
success: function(msg){
returnValue = msg;
}
});
return returnValue;
}
JQuery has a number of global Ajax event handlers, including $.ajaxComplete() and $.ajaxSuccess() (ref: http://api.jquery.com/ajaxSuccess/).
The code can be attached to any DOM element and looks like this:
/* Gets called when all request completes successfully */
$("#myElement").ajaxSuccess(function(event,request,settings){
$(this).html("<h4>Successful ajax request</h4>");
});
This code will execute whenever any successful Ajax call is completed.