AJAX ResponseText as DOM? - javascript

Consider the following function using jQuery:
function getVal() {
jQuery.get('/relative/url/', function (data) {
return data.getElementById('myInput').value;
}
}
This is basically what I want to do, but I have no idea how it should be done.
The only methods I know would work involve frames or innerHTML which I can't use because I have to wait for the element to be ready. The only way to do that is to use a callback, and this function must return the value of the element rather than something else.
My logic is likely faulty here, so please feel free to correct me.

First of all, with your current structure you should use a callback to return the value. To parse the HTML string retrieved via AJAX, you can hand it to jQuery and then query it just as usual.
function getVal(callback) {
jQuery.get('/relative/url/', function (data) {
callback($(data).find('#myInput').val());
}, 'html');
}
Then, when you are calling the function getVal, you'll need to provide a callback:
getVal(function(input_val) {
/**
* This code will be run once the GET request finishes.
* It will be passed one parameter - the value of #myInput in the HTML
* response to the request (see getVal function).
*/
alert(input_val);
});

No, you could not do that.. since it is ansync call. What you need is to provide a callback to you code, to return the value
function getVal(callback) {
jQuery.get('/relative/url/', function (data) {
callback(data.getElementById('myInput').value);
}
}
getVal(function (value) {
alert(value);
});

if the it's valid html markup, you can use browse its xml with the selector:
*[id=myInput]
or you can just render the markup on some dummy element in your page and then do you lookup:
function getVal() {
jQuery.get('/relative/url/', function (data) {
dummyNode.innerHTML = data; //not sure data points to responseTxt
return getElementById('myInput').innerHTML;
}
}

You cannot do that unless the elements are added to dom tree.
function getVal() {
jQuery.get('/relative/url/', function (data) {
return $(document.body).append(data).find('#myInput').val();
}
}

Several problems there. First, you cannot return from a callback like that. You would just return to the anonymous function itself, not from the getVal() method.
To solve that, you can return the jXHR object and apply some magic:
function getVal() {
return jQuery.get('/relative/url/');
}
getVal().done(function (data) {
var val = $( data ).find('#myInput').val();
// do something with val
}
I don't know how the structure from data looks like, but it should work that way. If not, its probably because of myInput is on the top level. In that case, replace .find() with .filter().

Oh, alright. I've got it. I don't think I provided enough information. I assumed context was irrelevant. Alright, here's an example depicting my solution.
function getVal() {
$.get('/relative/url/', function (data) {
$.get('relative/url/2', function (data2) {
var data_obj = [];
data_obj.push({
"data_1":data[i].name
}, {
"data_2":$(data).find('#myInput').val()
});
});
}
}

Related

What does this mean? getData([renderData]);

Can someone help me understand the logic behind this?
$(document).ready(function() {
getData([renderData]);
});
function renderData(JSON) {
$.each(JSON, function(i, item) {
//logic
}
}
function getData(callBacks) {
var url= '/data/data2';
$.getJSON(url, function() {
}).done(function(JSON) {
if(callBacks) {
for( var i = 0; i < callBacks.length; i++ ) {
callBacks[i](JSON);
}
}
}).fail(function(xhr, status, error) {
//alert(xhr.responseText);
});
}
Is the function renderData getting set as its own parameter?
Thank you.
It's passing the function renderData, inside an array, to another function called getData.
note thats its passing the function and not calling anything, so the array holds a reference to the function and not it's return value, inside getData the renderData function can be called by accessing the first value of the array passed as an argument.
i.e. callBacks[i](JSON); //callBacks[i] is renderData
Looking at getData it would seem that it's been done this way to avoid another layer of nesting inside the ajax calls/responses making the code more readable (once you understand it that is).
getData loads asynchronously some JSON and then calls any amount of callbacks you need (through an array) when everything is loaded. Any callback will be called with the loaded data as first parameter.
In this case, renderData is the only callback given.

How can I get the return value of jquery post function?

function readMemory(ptr, size)
{
$.post("readMemory.php", { ptr : ptr, size : size}, function(data)
{
});
//return "data"
}
Hi, I just want to get data variable as return of readMemory function. Is there any proper way to do this?
The best thing to do is use a callback:
function readMemory(ptr, size, callback)
{
$.post("readMemory.php", { ptr : ptr, size : size}, function(data)
{
callback(data, ptr, size);
});
}
(Note that we have ptr and size being passed to callback as well as data; this is usually good practice.)
So code you were expecting to use readMemory like this:
var data = readMemory(ptr, 100);
doSomethingWith(data);
doSomethingElseWith(data);
...will instead look like this:
readMemory(ptr, 100, function(data) {
doSomethingWith(data);
doSomethingElseWith(data);
});
This is because your readMemory function only starts the POST operation; it returns before the operation completes (the operation is asynchronous).
The improper way would be to make it a synchronous request (which I think would require using the lower level ajax method instead of post).
The proper way would be to forget about returning anything and use your callback function to do whatever you need to do with the data.
AJAX is asynchronous. This means that by the time your readMemory function returns, the result might not be available yet.
The only place that you can reliably consume the results of an AJAX call is inside the success callback:
function readMemory(ptr, size)
{
$.post("readMemory.php", { ptr : ptr, size : size}, function(data)
{
// here and only here you can use data
});
// at this stage there is no way to get the data
}
So the proper way is to not return anything from your function and do whatever you intended to do with those results inside the callback.
var tabela;
function doSomethingWith(response)
{
tabela = response;
}
function get_more(id)
{
var a = id + 11;
var b = id + 21;
$.post("../php/empresas/empresas_tab.php",{id:a, _id:b},function(data){
doSomethingWith(data);
$("#tabEMP").html(data);
//console.error(data);
});
}

jQuery Ajax How do callbacks work?

Hello fellow programmers! I just started an additional programming project and swore to god my code will bo SO much cleaner and easily upgradeable than it has been before.
Then I stumbled upon my "arch enemy" the jQuery AJAX returning. Last time I wanted to return something from an AJAX call I had to bend over and just make the call synchronous. That made things sticky and ugly and I hope that this time I will find something better.
So I have been googling/searching stackoverflow for a while now, and just don't understand this solution many ppl has gotten which is called callback function. Could someone give me an example on how I could exploit these callback functions in order to return my login statuses:
function doLogin(username, password) {
$.ajax({
url: 'jose.php?do=login&user='+username+'&pass='+password,
dataType: 'json',
success: function(data) {
if(data.success==1) {
return('1');
} else {
return('2');
}
$('#spinner').hide();
},
statusCode: {
403:function() {
LogStatus('Slavefile error: Forbidden. Aborting.');
$('#spinner').hide();
return (3);
},
404:function() {
LogStatus('Slavefile was not found. Aborting.');
$('#spinner').hide();
return (3);
},
500:function() {
LogStatus('Slavefile error: Internal server error. Aborting.');
$('#spinner').hide();
return (3);
},
501:function() {
LogStatus('Slavefile error: Not implemented. Aborting.');
$('#spinner').hide();
return (3);
}
},
async: true
});
}
So as you probably know, you cannot use return the way I have done from inside an AJAX call. You should instead use callback functions which I have no idea of how to use.
I'd be VERY greatful if someone could write me this code using callback functions and explaining to me just HOW they WORK.
EDIT:
I REALLY need to return stuff, not use it right away. This function is being called from within another function and should be able to be called from different places without being rewritten even slightly.
/EDIT
Sincerly,
Akke
Web Developer at Oy Aimo Latvala Ab
There are three parts to the basic "I need an asynchronous callback" pattern:
Give the function a callback function parameter.
Call the callback function instead of returning a value.
Instead of calling the function and doing something with its return value, the return value will be passed to your callback function as a parameter.
Suppose your synchronous mind wants to do this:
function doLogin(username, password) {
// ...
return something;
}
switch(doLogin(u, p)) {
case '1':
//...
break;
case '2':
//...
break;
//...
}
but doLogin has to make an asynchronous call to a remote server. You'd just need to rearrange things a little bit like this:
function doLogin(username, password, callback) {
return $.ajax({
// ...
success: function(data) {
if(data.success == 1)
callback('1');
else
callback('2');
},
//...
});
}
var jqxhr = doLogin(u, p, function(statusCode) {
switch(statusCode)) {
case '1':
//...
break;
case '2':
//...
break;
//...
}
});
The jqxhr allows you to reference the AJAX connection before it returns, you'd use it if you needed to cancel the call, attach extra handlers, etc.
A callback is simply a function that runs when certain conditions are met. In this case, it is when ajax has a "success".
You are already using a callback, but you don't recognize it. success: function(data) {} is a callback, but it's just what's called an anonymous function. It has no name or reference, but it still runs. If you want to change this anonymous function to a named function, it is really simple: take the code in the anonymous function, and put it in a named one, and then just call the named one:
[...]success: function(data) {
if(data.success==1) {
return('1');
} else {
return('2');
}
$('#spinner').hide();
}, [...]
should change to:
[...]success: function(){ callbackThingy(data) }, [...]
And now just create the callbackThingy function:
function callbackThingy(data){
if(data.success==1) {
someOtherFunction('1');
} else {
someOtherFunction('2');
}
$('#spinner').hide();
}
Note that the "return" value does nothing. It just stops the callback function, whether you are in an anonymous function or a named one. So you would also have to write a second function called someOtherFunction:
function someOtherFunction(inValue){
if(inValue=='1') {
// do something.
} else if(inValue=='2') {
// do something else.
}
}
The above example is if you have to pass parameters. If you do not need to pass parameters, the setup is simpler:
[...]success: callbackThingy, [...]
function callbackThingy(){
// do something here.
}
From the edit in your original post, I can see that you just need to store a (more) global variable. Try this:
// in the global scope , create this variable:
// (or -- at least -- in the scope available to both this ajax call
// and where you are going to use it)
var valHolder = -1;
// then edit your ajax call like this:
[...]
success: function(data) {
if(data.success==1) {
valHolder = 1;
} else {
valHolder = 2;
}
$('#spinner').hide();
},
[...]
Now you can verify 3 things:
valHolder = -1 means that the ajax call has not yet returned successfully
valHolder = 1 means data.success = 1
valHolder = 2 means data.success != 1.
Another option is to store the variable in an HTML attribute of some element.
Finally, you should probably look at jquery.data for the most jquery way of managing stored data.
Does this help?
Just as a small point of interest, you don't have to include
async : true;
as part of your $.ajax options. The default setting for async is already "true".
Sorry to post this as a response, but until I have 50 rep I can't make a simple comment. (Feel free to help me out with that! ^_^ )

How to get value returned by Callback function?

Here is my piece of code am trying:
initData:function(period)
{
this.getLoadObject('0',url, this.callbackFunction);
},
I want to receive a return value from callBackFunction, which I want to be returned by initData.
Can any body help me, am not so proficient with JS.
I tried similar question but didn't get help.
Actually, the callback function may very well be called asynchronously, that is after the return from the call to initData.
If it is synchronous however, you can do this:
initData:function(period)
{
var that = this;
var result;
this.getLoadObject('0',url, function() {
result = that.callbackFunction(arguments));
});
return result;
},
Although it's impossible to tell from your code snippet, it looks like your callback function will be called asynchronously. if this is the case you will need to set variables that you want to be populated by initData within the callback function itself.
you could also wrap the callback function:
var context = this;
this.getLoadObject('0',url, function() {
var returnedval = context.callbackFunction.apply(context,arguments);
context.SomeFuctionToUseValue(returnedval);
});
I think you could use variable outside the function, so you can access it inside the callback function and outside.
var result = false;
initData:function(period)
{
this.getLoadObject('0',url, this.callbackFunction);
//inside the callback you can modify the "result" then
return result;
},

Access array returned from a function - javascript/jquery noob moment

When the form is submitted, I'm calling a function getPosts and passing through a variable str. What I'd like to do is get the data returned from that function.
// when the form is submitted
$('form#getSome').submit(function(){
var str = $("form#getSome").serialize();
var something = getPosts(str);
* This is where I'd like to get the data returned from getPosts()
return false;
});
// get the data
function getPosts(str){
$.getJSON('http://myurl.com/json?'+str+'&callback=?',
function(data) {
arrPosts = new Array();
$.each(data.posts, function(i,posts){
// build array here
});
return arrPosts;
});
};
I've tried many things, but have only gotten 'undefined' returned. I've tried console.log(something);, console.log(getPosts).
I'm missing something very fundamental here. Any help would be greatly appreciated.
EDIT:
What I'm trying to do is create a single function that would get posts. Then different events would call that function. I could then use that data. So one event may be submitting a form, another may be clicking a link, another lazy/endless scrolling. All could use the same getPosts function.
There's a lot of parsing out the results which amounts to a lot of lines of code. Was just trying to find a way to reuse that function. Do you think that would be possible?
$('a.thisLink').click(function(){
getPosts();
get the return from getPosts() and do something with it
});
$('form.thisForm').submit(function(){
getPosts();
get the return from getPosts() and do something with it
});
function getPosts(){
get the posts and return an array
}
Ajax requests are executed asynchronously, the callback function (function (data)) of getJSON is executed when the request ends, and returning a value in that callback has no effect, because is a nested function inside getPosts and its return value is never used.
Actually in your example, getPosts doesn't return anything and it ends its execution before the data is returned.
I would recommend you to work on your submit event handler, if you want to keep the getPosts function, you can introduce a callback parameter:
$('form#getSome').submit(function(){
var str = $("form#getSome").serialize();
getPosts(str, function (data) {
var array = [];
$.each(data.posts, function(i,posts){
// build array here
array.push(/* value to add */);
});
// array ready to work with...
//...
});
return false;
});
function getPosts(str, callback){
$.getJSON('http://myurl.com/json?'+str+'&callback=?', callback);
}
Edit 2: In response to your second comment, you could make another callback, that will be executed when the data has been processed by the first callback, and you can define it when you execute the getPosts function on the submit event handler:
$('form#getSome').submit(function(){
var str = $("form#getSome").serialize();
getPosts(str, reusableCallback, function (result) {
// result contains the returned value of 'reusableCallback' <---
});
return false;
});
function reusableCallback(data) {
var array = [];
$.each(data.posts, function(i,posts){
array.push(/* value to add */);
});
//...
return array;
}
function getPosts(str, callback, finishCallback){
$.getJSON('http://myurl.com/json?'+str+'&callback=?', function (data) {
finishCallback(callback(data)); // pass the returned value
// of callback, to 'finishCallback' which is
// anonymously defined on the submit handler
});
}
Edit 3: I think that the getPosts function and the "reusableCallback" function are strongly related, you might want to join them, and make the code easier to use and understand:
$('form#getSome').submit(function(){
var str = $("form#getSome").serialize();
getPosts(str, function (result) {
// result contains the processed results
});
return false;
});
function getPosts(str, finishCallback){
$.getJSON('http://myurl.com/json?'+str+'&callback=?', function (data) {
// process the results here
var array = [];
$.each(data.posts, function(i,posts){
array.push(/* value to add */);
});
//...
finishCallback(array); // when the array is ready, execute the callback
});
}
Your getPosts function looks incomplete, I'm no jquery expert but should it look something like:
function getPosts(str) {
$.getJSON('http://myexample.com/json?'+str+'&callback=?',function(data){
var arrPosts = [];
$.each(data.posts, function(i,posts){
... build array yada yada ...
});
return arrPosts;
});
}
The problem is that the $.getJSON callback function gets called when the get request returns the data, not inline with your function.

Categories

Resources